code stringlengths 2 1.05M |
|---|
var menuControllers = angular.module('menuControllers', []);
menuControllers.controller('UserCtrl', [ '$rootScope', '$scope', 'UserService', '$localStorage', '$location', ( rootScope, scope, UserService, localStorage, location ) => {
scope.currentUser = UserService.getCurrentUser();
rootScope.$on('user-logged-in', () => {
scope.currentUser = UserService.getCurrentUser();
});
scope.logout = () => {
scope.currentUser = null;
UserService.logout();
rootScope.$broadcast('user-logged-out');
};
scope.changePassword = () => {
location.path('/account/changePassword');
};
}]);
module.exports = menuControllers;
|
import React, { Component } from 'react';
import { StyleSheet, Text } from 'react-native';
import { Container, Content, Button, Card, CardItem } from 'native-base';
import LoginForm from '../forms/login';
export default class Login extends Component {
login() {
const { login } = this.props;
const value = this.refs.form.getValue();
if(value) {
login(value);
}
}
render() {
const { error, success } = this.props;
return (
<Container>
<Content style={styles.content}>
<LoginForm ref="form" />
<Button block onPress={this.login.bind(this)} style={styles.loginButton}>Login</Button>
{success &&
<Card>
<CardItem header>
<Text>Success</Text>
</CardItem>
<CardItem>
<Text>You are logged in</Text>
</CardItem>
</Card>
}
{error &&
<Card>
<CardItem header>
<Text>Error</Text>
</CardItem>
<CardItem>
<Text>{error}</Text>
</CardItem>
</Card>
}
</Content>
</Container>
);
}
}
const styles = StyleSheet.create({
content: {
padding: 10
},
loginButton: {
marginBottom: 20
}
});
|
import Grammar from "./grammar";
import Rule from "./rule";
import { Turtle3D } from "./turtle";
export default {
Grammar,
Rule,
Turtle3D
};
|
var Settings = {
defaultColor: '#330066',
setUrls: function(urls) {
localStorage.setItem('urls', JSON.stringify(urls));
},
setColor: function(color) {
localStorage.setItem('color', color);
},
getColor: function() {
var color = localStorage.getItem('color') || Settings.defaultColor;
return color;
},
getUrls: function() {
var urls = localStorage.getItem('urls');
return urls ? JSON.parse(urls) : '';
}
};
|
'use strict';
const globalHooks = require('../../../hooks');
const hooks = require('feathers-hooks');
exports.before = {
all: [],
find: [],
get: [],
create: [],
update: [],
patch: [],
remove: []
};
exports.after = {
all: [],
find: [],
get: [],
create: [],
update: [],
patch: [],
remove: []
};
|
//for clones and deletes
function compile(pairs,ind){
var n,links,i,v,nn;
n = pairs[ind][0];
if(nset[n].Link){
links = nset[n].Link;
$.each(links,function(i,v){
pairs.push([v,n]);
});
delete nset[n].Link;
pass(pairs,ind);
function pass(pairs,ind){
var pair,nn;
ind += 1;
pair = pairs[ind];
if(!pairs[ind]){
return;
}
nn = newLab();
nset[nn] = $.extend(true, {}, nset[pair[0]]);
nset[nn].Backlink[0] = pair[1];
if(nset[pair[1]].Link){
nset[pair[1]].Link.push(nn);
}
else{
nset[pair[1]].Link = [nn];
}
nset[nn].clone = pair[0];
pairs[ind][0] = nn;
if(nset[pair[0]].Link){
compile(pairs,ind);
}
else{
pass(pairs,ind);
}
}
}
}
function legitNode(node){
var nn,bn;
nn = nset[node];
if(nn.Type === "Assembly" || nn.Type === "Product"){
node = node;
}
else{
bn = node;
while(nset[bn].Type !== "Assembly" ){
bn = nset[bn].Backlink[0];
if(nset[bn].Type === "Assembly"){
node = bn;
break;
}
}
}
return node;
}
//for analysing/modelling assemblies
function pairAssembler(node) {
var set,par,pairs,ind,pair,node,pode,np,repair,last,va,sn;
set = $.extend(true,{},nset);
if(!set[node].Link){
return;
}
node = legitNode(node);
pairs = [[node]];
ind = 0;
aCompile(pairs,ind);
function aCompile(pairs,ind){
var n,i,v;
pair = pairs[ind];
node = pair[0];
pode = pair[1];
//passes on grouping links
np = set[node].Type === "Grouping"? pode : node;
$.each(set[node].Link,function(i,v){
pairs.push([v,np]);
});
aPass(pairs,ind);
function aPass(pairs,ind){
var pair;
ind += 1;
pair = pairs[ind];
if(!pair){
repair = [];
$.each(pairs,function(i,v){
//first node acts as first parent
if(!v[1]){
return;
}
t = set[v[0]].Type;
if(t === "Assembly" || t === "Product"){
if(v[1] !== last){
va = [v[1],[v[0]]];
repair.push(va);
}
else{
va[1].push(v[0]);
}
last = v[1];
}
});
return;
}
sn = set[pair[0]];
if(sn.Link){
aCompile(pairs,ind);
}
else{
aPass(pairs,ind);
}
}
}
return repair;
}
//called from monitor (passing id extracted from event event)
function rerun(node){
var nt;
nt = [node];
while(nset[node].Backlink){
node = nset[node].Backlink[0];
nt.unshift(node);
}
cfig.nTrail = nt;
cfig.trail = nt;
nRun();
tRun();
} |
/**
* @license Copyright (c) 2012, Viet Trinh All Rights Reserved.
* Available via MIT license.
*/
/**
* A private node tests results handler. This will run the unit tests in node's environment and pipe back the results.
*/
define([ 'framework/request/base_request_handler',
'../tests_private_tests_results_server_request',
'framework/core/deferred/deferred' ],
function(BaseRequestHandler,
TestsPrivateTestsResultsServerRequest,
Deferred)
{
var TestsNodeTestsResultsServerHandler = BaseRequestHandler.create(TestsPrivateTestsResultsServerRequest, [ 'testsRunTestsModule' ]);
// @override
TestsNodeTestsResultsServerHandler.prototype.execute = function(requestContext, request, response)
{
return this._testsRunTestsModule.execute(requestContext, 'private');
};
return TestsNodeTestsResultsServerHandler;
}); |
import DataProcessor from './data.processor';
const ARRAY_POSITION = 1,
FRAME_SIZE_POSITION = 0;
/**
* messageHandler - Entry point of a data processing WebWorker, contains full life cycle
*
* @param {object} event - generyc JS webworker event, contains passed from window data
*/
self.onmessage = function messageHandler(event) {
if (event.data) {
let dataProcessor = new DataProcessor(event.data[ARRAY_POSITION], event.data[FRAME_SIZE_POSITION]),
processedData = 0,
currentProgress = 0,
percents = 0;
const STEP = 5,
ONE_STEP_OF_DATA = event.data[ARRAY_POSITION].length * STEP / 100;
while (!processedData.length) {
try {
processedData = dataProcessor.process();
} catch (error) {
postMessage({ id: '', error: 'error' });
}
if (processedData - currentProgress > ONE_STEP_OF_DATA) {
percents += STEP;
currentProgress += ONE_STEP_OF_DATA;
postMessage({ id: '', progress: percents });
}
}
let blob = new Blob([processedData.join('\r\n')], { type: 'text/csv' });
postMessage({ id: '', file: blob });
close();
} else {
postMessage('error');
}
};
|
// @flow
///////////////////////////////////////////////////////////////////////////////
// @file : Settings.js //
// @summary : //
// @version : 0.0.1 //
// @project : tickelr //
// @description : //
// @author : Benjamin Maggi //
// @email : benjaminmaggi@gmail.com //
// @date : 02 Sep 2017 //
// @license: : MIT //
// ------------------------------------------------------------------------- //
// //
// Copyright 2017 Benjamin Maggi <benjaminmaggi@gmail.com> //
// //
// //
// License: //
// 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. //
// //
///////////////////////////////////////////////////////////////////////////////
import type { SettingsActions } from '../types';
import { SettingsActionKeys as Action } from '../types';
import SettingsStore from '../lib/SettingsStore';
const settings = new SettingsStore();
export default function Settings (state: any = settings, action: any) {
switch (action.type) {
case Action.SETTINGS_GET: {
const { key } = action;
return state;
}
case Action.SETTINGS_SET: {
const { key, value } = action;
state.set(key, value);
return state;
}
default:
return state;
}
}
|
/* global ExpressionManager, TextProperty */
(function addDecorator() {
function searchExpressions() {
if (this.data.d.x) {
this.calculateExpression = ExpressionManager.initiateExpression.bind(this)(this.elem, this.data.d, this);
this.addEffect(this.getExpressionValue.bind(this));
return true;
}
return null;
}
TextProperty.prototype.getExpressionValue = function (currentValue, text) {
var newValue = this.calculateExpression(text);
if (currentValue.t !== newValue) {
var newData = {};
this.copyData(newData, currentValue);
newData.t = newValue.toString();
newData.__complete = false;
return newData;
}
return currentValue;
};
TextProperty.prototype.searchProperty = function () {
var isKeyframed = this.searchKeyframes();
var hasExpressions = this.searchExpressions();
this.kf = isKeyframed || hasExpressions;
return this.kf;
};
TextProperty.prototype.searchExpressions = searchExpressions;
}());
|
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
/**
* Created by khjan on 2017-03-04.
*/
var core_1 = require('@angular/core'); //주요 요소의 Decorator, Core Module
var platform_browser_1 = require('@angular/platform-browser'); //브라우져 모듈
var forms_1 = require('@angular/forms'); //폼관련 모듈
var http_1 = require('@angular/http');
var app_routing_module_1 = require('./app-routing.module');
var angular_in_memory_web_api_1 = require('angular-in-memory-web-api');
var in_memory_data_service_1 = require('./in-memory-data.service');
var app_component_1 = require('./app.component');
var hero_detail_component_1 = require('./hero-detail.component');
var heroes_component_1 = require('./heroes.component');
var dashboard_component_1 = require('./dashboard.component');
var hero_search_component_1 = require('./hero-search.component');
var hero_service_1 = require('./hero.service');
//Application 전역으로 사용하는 모듈이나 최상의 컴퍼넌트 모듈이나 최상위 컴퍼넌트를 등록함
var AppModule = (function () {
function AppModule() {
}
AppModule = __decorate([
core_1.NgModule({
//
imports: [
platform_browser_1.BrowserModule,
forms_1.FormsModule,
http_1.HttpModule,
angular_in_memory_web_api_1.InMemoryWebApiModule.forRoot(in_memory_data_service_1.InMememoryDataSerive),
app_routing_module_1.AppRoutingModule
],
declarations: [app_component_1.AppComponent, dashboard_component_1.DashboardComponent, hero_detail_component_1.HeroDetailComponent,
heroes_component_1.HeroesComponent, hero_search_component_1.HeroSearchComponent],
bootstrap: [app_component_1.AppComponent],
providers: [hero_service_1.HeroService]
}),
__metadata('design:paramtypes', [])
], AppModule);
return AppModule;
}());
exports.AppModule = AppModule;
//# sourceMappingURL=app.module.js.map |
'use strict'
// "ready","paused","onGround","crashed","sts","ts","pitch","roll","yaw","airspeed","altitude","vspeed","ilsDeviation.loc","ilsDeviation.gs","onTrack","status","lng","lat","weather.wind.heading","weather.wind.speed","weather.temp","weather.turbulance","collectorId","runId"
var color = require('cli-color');
var cli = require('commander');
var net = require('net');
var _ = require('lodash');
var AWS = require('aws-sdk');
var json2csv = require('json2csv');
const uuid = require('uuid/v4');
var totalRecordCount = 0
var intervalRecordCount = 0
var firstRecord = true
const collectorId = uuid();
const runId = uuid();
let runCounter = 0
let runDataCount = 0;
let incrementRun = true;
const FLOAT_ACCURACY = 5;
// flight state constants
const ON_GROUND_CRASHED = -1;
const FLYING = 0;
const ON_GROUND_LANDED = 1;
const ILS_LOST = 2;
AWS.config = {
region: 'us-east-1'
// other service API versions
}
var kinesis = new AWS.Firehose();
var kinesisPartition = 0;
const partitionCount = 3;
var dynamodb = new AWS.DynamoDB();
function getPartition() {
if (kinesisPartition < partitionCount) {
return kinesisPartition.toString();
}
kinesisPartition++;
}
cli.version('1.0.0')
.usage('[options]')
.option(
'-h, --host <name or IP>', 'IP or name of the server', '192.168.2.2')
.option('-p, --port <port>', 'TCP Port', '8081')
.option('-s, --streamName <name>', 'Kinesis stream name', 'simTrain')
.option('-f, --format [csv,json]', 'Output type (csv or json)', 'csv')
.option('-k, --kinesis [true, false]', 'Send to kinesis', true)
.option('-d, --dynamo [true, false', 'Send tracking data to dynamo', true)
.parse(process.argv)
console.log(color.green(
`Starting training data collection for ${cli.host} port ${cli.port}`));
console.log(color.green(`collector id ${collectorId}`));
var dataStream = net.createConnection(cli.port, cli.host);
dataStream
.on('error',
function(error) {
console.log(color.red(`${error}`));
})
.on('connect',
function() {
console.log(color.green(`Connected to ${cli.host}:${cli.port}`))
setInterval(function(a) {
console.log(color.yellow(
`Processing: ${intervalRecordCount}/${totalRecordCount}`));
intervalRecordCount = 0;
}, 5000);
})
.on('data', function(data) {
var jsonData = JSON.parse(data.toString());
if (firstRecord) {
// console.log(color.yellow(`Receiving data`));
}
if (jsonData.data.ready == false || jsonData.data.paused == true) {
if (incrementRun)
console.log(color.red(`Skipping while sim resetting...`));
incrementRun = false;
return;
} else {
incrementRun = true;
}
jsonData['data']['collectorId'] = collectorId;
jsonData['data']['runId'] = `${runId}_${runCounter}`;
jsonData['data']['pitch'] =
jsonData['data']['pitch'].toFixed(FLOAT_ACCURACY);
jsonData['data']['roll'] =
jsonData['data']['roll'].toFixed(FLOAT_ACCURACY);
jsonData['data']['yaw'] = jsonData['data']['yaw'].toFixed(FLOAT_ACCURACY);
jsonData['data']['airspeed'] =
jsonData['data']['airspeed'].toFixed(FLOAT_ACCURACY);
jsonData['data']['altitude'] =
jsonData['data']['altitude'].toFixed(FLOAT_ACCURACY);
jsonData['data']['vspeed'] =
jsonData['data']['vspeed'].toFixed(FLOAT_ACCURACY);
if (typeof jsonData['data']['ilsDeviation']['loc'] != 'string')
jsonData['data']['ilsDeviation']['loc'] =
jsonData['data']['ilsDeviation']['loc'].toFixed(FLOAT_ACCURACY);
else
jsonData['data']['ilsDeviation']['loc'] = -2.5;
if (typeof jsonData['data']['ilsDeviation']['gs'] != 'string')
jsonData['data']['ilsDeviation']['gs'] =
jsonData['data']['ilsDeviation']['gs'].toFixed(FLOAT_ACCURACY);
else
jsonData['data']['ilsDeviation']['gs'] = -2.5;
jsonData['data']['weather']['wind']['heading'] =
jsonData['data']['weather']['wind']['heading'].toFixed(
FLOAT_ACCURACY);
jsonData['data']['weather']['temp'] =
jsonData['data']['weather']['temp'].toFixed(FLOAT_ACCURACY);
// console.dir(jsonData, {depth: null});
if (jsonData.data.status == ON_GROUND_CRASHED ||
jsonData.data.status == ON_GROUND_LANDED ||
jsonData.data.status == ILS_LOST && incrementRun) {
console.log(color.yellow(`run ${runCounter}/${runDataCount} rows`));
var params = {
Item: {
'sts': {S: jsonData.data.sts},
'collectorId': {S: collectorId},
'runNumber': {S: runCounter.toString()},
'rowCount': {S: runDataCount.toString()}
},
ReturnConsumedCapacity: 'TOTAL',
TableName: 'simTrainer'
};
if (runDataCount > 1 && cli.dynamo)
dynamodb.putItem(params, function(err, data) {
if (err)
console.log(err, err.stack); // an error occurred
else
console.log(data);
});
incrementRun = false;
runCounter++
runDataCount = 0
console.log(color.yellow(` - New run: ${runCounter}`))
}
if (cli.kinesis) {
var output = ''
if (cli.format == 'csv') {
output = json2csv({
data: jsonData.data,
hasCSVColumnTitle: false,
flatten: true,
newLine: '\r\n'
});
output += '\n';
// console.log(output);
}
else {
output = JSON.stringify(jsonData);
}
// console.log(output);
var params = {
Record: {Data: output},
DeliveryStreamName: cli.streamName
};
kinesis.putRecord(params, function(err, data) {
if (err) {
console.log(err.message);
} // an error occurred
else {
console.log(color.green(` - written to kinesis`))
}
})
}
totalRecordCount++
runDataCount++
intervalRecordCount++
firstRecord = false
})
|
Polymer({
is: 'krisinfo-footer',
});
|
/**
* @license Copyright (c) 2013, Viet Trinh All Rights Reserved.
* Available via MIT license.
*/
/**
* A controller implementation of the set routes of the collection page.
*/
define([ 'framework/controller/base_controller',
'framework/core/utils/clazz',
'../collection_set_add_client_request',
'../collection_set_view_client_request',
'../collection_set_view_buy_client_request',
'../collection_set_view_historical_client_request',
'../collection_set_change_owned_client_request',
'../collection_set_update_all_client_request' ],
function(BaseController,
ClazzUtils,
CollectionSetAddClientRequest,
CollectionSetViewClientRequest,
CollectionSetViewBuyClientRequest,
CollectionSetViewHistoricalClientRequest,
CollectionSetChangeOwnedClientRequest,
CollectionSetUpdateAllClientRequest)
{
var CollectionSetController = function()
{
BaseController.call(this);
this._baseRoute = 'set';
return this;
}
CollectionSetController.prototype = new BaseController();
ClazzUtils.generateProperties(CollectionSetController);
// @override
CollectionSetController.prototype.init = function()
{
this._registerSwapRoute('/add', 'set/form');
this._registerPostRoute('/add', 'redirect:', CollectionSetAddClientRequest);
this._registerGetRoute('/{id}', 'set/view', CollectionSetViewClientRequest);
this._registerGetRoute('/{id}/buy', 'set/view/buy', CollectionSetViewBuyClientRequest);
this._registerGetRoute('/{id}/historical', 'set/view/historical', CollectionSetViewHistoricalClientRequest);
this._registerPostRoute('/change/owned', null, CollectionSetChangeOwnedClientRequest);
this._registerGetRoute('/update/all/{format}', 'set/update/all', CollectionSetUpdateAllClientRequest);
};
return CollectionSetController;
}); |
System.config({
"transpiler": "babel",
"babelOptions": {
"optional": [
"runtime",
"es7.decorators"
]
},
"paths": {
"*": "*.js",
"github:*": "jspm_packages/github/*.js",
"aurelia-loader/*": "dist/*.js",
"npm:*": "jspm_packages/npm/*.js"
}
});
System.config({
"map": {
"aurelia-html-template-element": "github:aurelia/html-template-element@0.2.0",
"aurelia-metadata": "github:aurelia/metadata@0.7.3",
"aurelia-path": "github:aurelia/path@0.8.1",
"babel": "npm:babel-core@5.1.13",
"babel-runtime": "npm:babel-runtime@5.1.13",
"core-js": "npm:core-js@0.9.18",
"github:aurelia/metadata@0.7.3": {
"core-js": "npm:core-js@0.9.18"
},
"github:jspm/nodelibs-process@0.1.1": {
"process": "npm:process@0.10.1"
},
"npm:core-js@0.9.18": {
"fs": "github:jspm/nodelibs-fs@0.1.2",
"process": "github:jspm/nodelibs-process@0.1.1",
"systemjs-json": "github:systemjs/plugin-json@0.1.0"
}
}
});
|
describe('{} aegis.core', function() {
var ensure = require('noire').ensure
var sinon = require('sinon')
var _ = require('../src/core')
var folders = require('../src/folders')
describe('{} Stream', function() {
function S(xs){ return _.Stream.make(xs) }
function number_p(x, n) { n(typeof x == 'number') }
function low_p(x, n) { n(x < 3) }
function string_p(x, n) { n(typeof x == 'string') }
function big_p(x, n) { n(x > 2) }
var xs, ys, noop
beforeEach(function() {
xs = folders.sequence([1, 2, 3, 4])
ys = folders.map({ a: 1, b: 2, c: 3, d: 4 })
noop = sinon.spy()
})
describe('λ end', function() {
it('Should wrap the value into a final value for a fold.', function() {
ensure(_.Stream.end(1)).satisfy(_.internal.finished_p)
})
it('Should hold the value as the `value` property.', function() {
ensure(_.Stream.end(1)).property('value').same(1)
})
})
describe('λ fold', function() {
it('Should return the original Stream.', function() {
var s = S(xs)
ensure(s.fold(noop, noop, noop)).same(s)
})
it('Should invoke the Foldable\'s fold.', function() {
var mock = sinon.mock(xs)
var spy = sinon.spy()
mock.expects('fold').once()
.callsArgWith(1, 1, noop)
S(xs).fold(0, spy, noop)
ensure(spy).property('called').ok()
mock.verify()
})
it('Should finish as soon as it hits a final result for the fold.', function() {
var mock = sinon.mock(xs)
var step = sinon.spy(function(i){ step(i) })
mock.expects('fold').callsArgWith(1, _.Stream.end(1), 2, step)
S(xs).fold(0, step, noop)
ensure(noop).property('calledOnce').ok()
mock.verify()
})
it('Should continue folding until the Stream is consumed.', function() {
var i = 0
var mock = sinon.mock(xs)
var step = sinon.spy(function(x, k, n){ i < 4? step(++i) : noop() })
mock.expects('fold').callsArgWith(1, i, 1, step)
S(xs).fold(i, step, noop)
ensure(step).property('callCount').same(5)
ensure(noop).property('calledOnce').ok()
mock.verify()
})
})
describe('λ as-array', function() {
it('Should aggregate all items of a Stream in an array.', function() {
var s = S(xs), x = 0
s.fold = function(r, step, d) {
x < 4? step(r, ++x, function(r) { s.fold(r, step, d) })
: d(r) }
s.as_array(noop)
ensure(noop).property('calledOnce').ok()
ensure(noop.args[0][0]).equals([1, 2, 3, 4])
})
})
describe('λ value', function() {
it('Should return the final result of a Stream.', function() {
var s = S(xs), x = 0
s.fold = function(r,step,d) {
x < 4? step(++x, x, function(r){ s.fold(r, step, d) })
: d(x) }
s.value(0, noop)
ensure(noop).property('calledOnce').ok()
ensure(noop.args[0][0]).equals(4)
})
})
describe('λ map', function() {
it('Should yield a new Stream.', function() {
var s = S(xs)
ensure(s.map(noop)).not().same(s)
})
it('Should map all items in a stream through a mapping function.', function() {
var ones = sinon.stub().callsArgWith(1, 1)
S(xs).map(ones).as_array(noop)
S(ys).map(ones).as_array(noop)
ensure(noop).property('calledTwice').ok()
ensure(noop.args[0][0]).equals([1, 1, 1, 1])
ensure(noop.args[1][0]).equals([1, 1, 1, 1])
})
it('Should not modify the items in the original Stream.', function() {
var s = S(xs), ones = sinon.stub().callsArgWith(1, 1)
s.map(ones).as_array(noop)
s.as_array(noop)
ensure(noop).property('calledTwice').ok()
ensure(noop.args[0][0]).equals([1, 1, 1, 1])
ensure(noop.args[1][0]).equals([1, 2, 3, 4])
})
})
describe('λ filter', function() {
function even(x, n){ n(x % 2 == 0) }
it('Should yield a new Stream.', function() {
var s = S(xs)
ensure(s.filter(noop)).not().same(s)
})
it('Should keep only items that pass the predicate.', function() {
S(xs).filter(even).as_array(noop)
ensure(noop).property('calledOnce').ok()
ensure(noop.args[0][0]).equals([2, 4])
})
it('Should not modify the items in the original Stream.', function() {
var s = S(xs)
s.filter(even).as_array(noop)
s.as_array(noop)
ensure(noop).property('calledTwice').ok()
ensure(noop.args[0][0]).equals([2, 4])
ensure(noop.args[1][0]).equals([1, 2, 3, 4])
})
})
describe('λ every', function() {
it('Should yield a new Stream.', function() {
var s = S(xs)
ensure(s.every(noop)).not().same(s)
})
it('Should fold to true if all items pass the predicate.', function() {
S(xs).every(number_p).value(true, noop)
ensure(noop).property('calledOnce').ok()
ensure(noop.args[0][0]).equals(true)
})
it('Should fold to false immediately if any item fails.', function() {
var s = S(xs)
var spy = sinon.spy(low_p)
s.every(spy).value(true, noop)
ensure(spy).property('callCount').same(3)
ensure(noop).property('calledOnce').ok()
ensure(noop.args[0][0]).equals(false)
})
it('Should not modify the items in the original Stream.', function() {
var s = S(xs)
s.every(number_p).value(true, noop)
s.as_array(noop)
ensure(noop).property('calledTwice').ok()
ensure(noop.args[0][0]).equals(true)
ensure(noop.args[1][0]).equals([1, 2, 3, 4])
})
})
describe('λ any', function() {
it('Should yield a new Stream.', function() {
var s = S(xs)
ensure(s.any(noop)).not().same(s)
})
it('Should fold to false if none of the items pass the predicate.', function() {
S(xs).any(string_p).value(false, noop)
ensure(noop).property('calledOnce').ok()
ensure(noop.args[0][0]).equals(false)
})
it('Should fold to true immediately if any of the items pass the predicate.', function() {
var s = S(xs)
var spy = sinon.spy(big_p)
s.any(spy).value(false, noop)
ensure(spy).property('callCount').same(3)
ensure(noop).property('calledOnce').ok()
ensure(noop.args[0][0]).equals(true)
})
it('Should not modify the items in the original Stream.', function() {
var s = S(xs)
s.any(string_p).value(false, noop)
s.as_array(noop)
ensure(noop).property('calledTwice').ok()
ensure(noop.args[0][0]).equals(false)
ensure(noop.args[1][0]).equals([1, 2, 3, 4])
})
})
})
}) |
var app = angular.module('app', ['ngTouch', 'ui.grid', 'ui.grid.edit', 'ui.grid.cellNav', 'ui.grid.pinning', 'ui.grid.filldown']);
app.controller('MainCtrl', ['$scope', function ($scope) {
$scope.filldownOptions = {
additionalField: 'value'
};
$scope.gridOptions = {
enableSorting: true,
columnDefs: [
{ name:'firstName', field: 'first-name' },
{ name:'1stFriend', field: 'friends[0]' },
{ name:'city', field: 'address.city'},
{ name:'getZip', field: 'getZip()', enableCellEdit:false}
],
data : [
{
"first-name": "Cox2",
"friends": ["friend0"],
"address": {street:"301 Dove Ave", city:"Laurel", zip:"39565"},
"getZip" : function() {return this.address.zip;}
},
{
"first-name": "Cox3",
"friends": ["friend0"],
"address": {street:"301 Dove Ave", city:"Laurel", zip:"39565"},
"getZip" : function() {return this.address.zip;}
},
{
"first-name": "Cox4",
"friends": ["friend0"],
"address": {street:"301 Dove Ave", city:"Laurel", zip:"39565"},
"getZip" : function() {return this.address.zip;}
},
{
"first-name": "Cox5",
"friends": ["friend0"],
"address": {street:"301 Dove Ave", city:"Laurel", zip:"39565"},
"getZip" : function() {return this.address.zip;}
},
{
"first-name": "Cox6",
"friends": ["friend0"],
"address": {street:"301 Dove Ave", city:"Laurel", zip:"39565"},
"getZip" : function() {return this.address.zip;}
},
{
"first-name": "Cox",
"friends": ["friend0"],
"address": {street:"301 Dove Ave", city:"Laurel", zip:"39565"},
"getZip" : function() {return this.address.zip;}
}
]
};
}]); |
var iot_peer = require("../../iot-peer.js");
iot_peer.login("sensor1",function(data){
console.log("starting to send data");
setInterval(
function(){
iot_peer.send_data(50);
}
,1000
);
});
|
var React = require('react');
var Link = require('./components/link.js');
var Resource = require('./components/resource.js');
export {
Link,
Resource
}; |
var angular = angular || {};
angular.module('app.router', [])
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('basic', {
url: '/',
templateUrl:'views/basic.html',
controller: 'BasicCtrl'
})
///redirect to default.
$urlRouterProvider.otherwise('/');
})
|
'use strict';
var respond = require('./utils').respond;
module.exports = function(models) {
var getAll = function(req, res, next) {
models.Team.findAll({
include: [
models.Player
]
}).then(function(team) {
respond(res, 200, true, null, team);
}).catch(function(err) {
respond(res, 500, false, err.message);
});
};
var getById = function(req, res, next) {
models.Team.findOne({
where: {
id: req.params.team_id
},
include: [
models.Player
]
}).then(function(team) {
respond(res, 200, true, null, team);
}).catch(function(err) {
respond(res, 500, false, err.message);
});
};
var createTeam = function(req, res, next) {
models.Team.create({
Name: req.body.Name
}).then(function(team) {
respond(res, 200, true, null, team);
}).catch(function(err) {
respond(res, 500, false, err.message);
});
};
var updateTeam = function(req, res, next) {
models.Team.update({
Name: req.body.Name
}, {
where: {
id: req.params.team_id
}
}).then(function(team) {
respond(res, 200, true, null, team);
}).catch(function(err) {
respond(res, 500, false, err.message);
});
};
var deleteTeam = function(req, res, next) {
models.Team.destroy({
where: {
id: req.params.team_id
}
}).then(function(team) {
respond(res, 200, true, null, team);
}).catch(function(err) {
respond(res, 500, false, err.message);
});
};
return {
getAll: getAll, // GET /api/teams
getById: getById, // GET /api/team/:team_id
createTeam: createTeam, // POST /api/team/create
updateTeam: updateTeam, // PUT /api/team/update/:team_id
deleteTeam: deleteTeam, // DELETE /api/team/:team_id
};
};
|
import FlexberryDatepicker from 'ember-flexberry/components/flexberry-datepicker';
export default FlexberryDatepicker;
|
export const USER_SIGNIN = 'USER_SIGININ';
export const USER_SIGNOUT = 'USER_SIGNOUT';
export const USER_REG = 'USER_REG';
export const SHOW_PROGRESS = "SHOW_PROGRESS";
export const HEAD_LINE = 'HEAD_LINE' |
/*
Copyright (c) 2015 NAVER Corp.
name: @egjs/infinitegrid
license: MIT
author: NAVER Corp.
repository: https://github.com/naver/egjs-infinitegrid
version: 4.2.0-beta.5
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = global || self, global.InfiniteGrid = factory());
}(this, (function () { 'use strict';
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise */
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf || {
__proto__: []
} instanceof Array && function (d, b) {
d.__proto__ = b;
} || function (d, b) {
for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p];
};
return extendStatics(d, b);
};
function __extends(d, b) {
if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() {
this.constructor = d;
}
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign = function () {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
function __rest(s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
}
return t;
}
function __decorate(decorators, target, key, desc) {
var c = arguments.length,
r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc,
d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
}
/** @deprecated */
function __spreadArrays() {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++) for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) r[k] = a[j];
return r;
}
/*
Copyright (c) NAVER Corp.
name: @egjs/component
license: MIT
author: NAVER Corp.
repository: https://github.com/naver/egjs-component
version: 3.0.1
*/
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
function __values(o) {
var s = typeof Symbol === "function" && Symbol.iterator,
m = s && o[s],
i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return {
value: o && o[i++],
done: !o
};
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __read(o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o),
r,
ar = [],
e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
} catch (error) {
e = {
error: error
};
} finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
} finally {
if (e) throw e.error;
}
}
return ar;
}
function __spread() {
for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));
return ar;
}
/*
* Copyright (c) 2015 NAVER Corp.
* egjs projects are licensed under the MIT license
*/
var isUndefined = function (value) {
return typeof value === "undefined";
};
/**
* Event class to provide additional properties
* @ko Component에서 추가적인 프로퍼티를 제공하는 이벤트 클래스
*/
var ComponentEvent =
/*#__PURE__*/
function () {
/**
* Create a new instance of ComponentEvent.
* @ko ComponentEvent의 새로운 인스턴스를 생성한다.
* @param eventType The name of the event.<ko>이벤트 이름.</ko>
* @param props An object that contains additional event properties.<ko>추가적인 이벤트 프로퍼티 오브젝트.</ko>
*/
function ComponentEvent(eventType, props) {
var e_1, _a;
this.eventType = eventType;
this._canceled = false;
if (!props) return;
try {
for (var _b = __values(Object.keys(props)), _c = _b.next(); !_c.done; _c = _b.next()) {
var key = _c.value; // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
this[key] = props[key];
}
} catch (e_1_1) {
e_1 = {
error: e_1_1
};
} finally {
try {
if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
} finally {
if (e_1) throw e_1.error;
}
}
}
/**
* Stop the event. {@link ComponentEvent#isCanceled} will return `true` after.
* @ko 이벤트를 중단한다. 이후 {@link ComponentEvent#isCanceled}가 `true`를 반환한다.
*/
var __proto = ComponentEvent.prototype;
__proto.stop = function () {
this._canceled = true;
};
/**
* Returns a boolean value that indicates whether {@link ComponentEvent#stop} is called before.
* @ko {@link ComponentEvent#stop}이 호출되었는지 여부를 반환한다.
* @return {boolean} A boolean value that indicates whether {@link ComponentEvent#stop} is called before.<ko>이전에 {@link ComponentEvent#stop}이 불려졌는지 여부를 반환한다.</ko>
*/
__proto.isCanceled = function () {
return this._canceled;
};
return ComponentEvent;
}();
/**
* A class used to manage events in a component
* @ko 컴포넌트의 이벤트을 관리할 수 있게 하는 클래스
*/
var Component =
/*#__PURE__*/
function () {
/**
* @support {"ie": "7+", "ch" : "latest", "ff" : "latest", "sf" : "latest", "edge" : "latest", "ios" : "7+", "an" : "2.1+ (except 3.x)"}
*/
function Component() {
this._eventHandler = {};
}
/**
* Trigger a custom event.
* @ko 커스텀 이벤트를 발생시킨다
* @param {string | ComponentEvent} event The name of the custom event to be triggered or an instance of the ComponentEvent<ko>발생할 커스텀 이벤트의 이름 또는 ComponentEvent의 인스턴스</ko>
* @param {any[]} params Event data to be sent when triggering a custom event <ko>커스텀 이벤트가 발생할 때 전달할 데이터</ko>
* @return An instance of the component itself<ko>컴포넌트 자신의 인스턴스</ko>
* @example
* ```ts
* import Component, { ComponentEvent } from "@egjs/component";
*
* class Some extends Component<{
* beforeHi: ComponentEvent<{ foo: number; bar: string }>;
* hi: { foo: { a: number; b: boolean } };
* someEvent: (foo: number, bar: string) => void;
* someOtherEvent: void; // When there's no event argument
* }> {
* some(){
* if(this.trigger("beforeHi")){ // When event call to stop return false.
* this.trigger("hi");// fire hi event.
* }
* }
* }
*
* const some = new Some();
* some.on("beforeHi", e => {
* if(condition){
* e.stop(); // When event call to stop, `hi` event not call.
* }
* // `currentTarget` is component instance.
* console.log(some === e.currentTarget); // true
*
* typeof e.foo; // number
* typeof e.bar; // string
* });
* some.on("hi", e => {
* typeof e.foo.b; // boolean
* });
* // If you want to more know event design. You can see article.
* // https://github.com/naver/egjs-component/wiki/How-to-make-Component-event-design%3F
* ```
*/
var __proto = Component.prototype;
__proto.trigger = function (event) {
var params = [];
for (var _i = 1; _i < arguments.length; _i++) {
params[_i - 1] = arguments[_i];
}
var eventName = event instanceof ComponentEvent ? event.eventType : event;
var handlers = __spread(this._eventHandler[eventName] || []);
if (handlers.length <= 0) {
return this;
}
if (event instanceof ComponentEvent) {
event.currentTarget = this;
handlers.forEach(function (handler) {
handler(event);
});
} else {
handlers.forEach(function (handler) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
handler.apply(void 0, __spread(params));
});
}
return this;
};
/**
* Executed event just one time.
* @ko 이벤트가 한번만 실행된다.
* @param {string} eventName The name of the event to be attached or an event name - event handler mapped object.<ko>등록할 이벤트의 이름 또는 이벤트 이름-핸들러 오브젝트</ko>
* @param {function} handlerToAttach The handler function of the event to be attached <ko>등록할 이벤트의 핸들러 함수</ko>
* @return An instance of the component itself<ko>컴포넌트 자신의 인스턴스</ko>
* @example
* ```ts
* import Component, { ComponentEvent } from "@egjs/component";
*
* class Some extends Component<{
* hi: ComponentEvent;
* }> {
* hi() {
* alert("hi");
* }
* thing() {
* this.once("hi", this.hi);
* }
* }
*
* var some = new Some();
* some.thing();
* some.trigger(new ComponentEvent("hi"));
* // fire alert("hi");
* some.trigger(new ComponentEvent("hi"));
* // Nothing happens
* ```
*/
__proto.once = function (eventName, handlerToAttach) {
var _this = this;
if (typeof eventName === "object" && isUndefined(handlerToAttach)) {
var eventHash = eventName;
for (var key in eventHash) {
this.once(key, eventHash[key]);
}
return this;
} else if (typeof eventName === "string" && typeof handlerToAttach === "function") {
var listener_1 = function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
} // eslint-disable-next-line @typescript-eslint/no-unsafe-call
handlerToAttach.apply(void 0, __spread(args));
_this.off(eventName, listener_1);
};
this.on(eventName, listener_1);
}
return this;
};
/**
* Checks whether an event has been attached to a component.
* @ko 컴포넌트에 이벤트가 등록됐는지 확인한다.
* @param {string} eventName The name of the event to be attached <ko>등록 여부를 확인할 이벤트의 이름</ko>
* @return {boolean} Indicates whether the event is attached. <ko>이벤트 등록 여부</ko>
* @example
* ```ts
* import Component from "@egjs/component";
*
* class Some extends Component<{
* hi: void;
* }> {
* some() {
* this.hasOn("hi");// check hi event.
* }
* }
* ```
*/
__proto.hasOn = function (eventName) {
return !!this._eventHandler[eventName];
};
/**
* Attaches an event to a component.
* @ko 컴포넌트에 이벤트를 등록한다.
* @param {string} eventName The name of the event to be attached or an event name - event handler mapped object.<ko>등록할 이벤트의 이름 또는 이벤트 이름-핸들러 오브젝트</ko>
* @param {function} handlerToAttach The handler function of the event to be attached <ko>등록할 이벤트의 핸들러 함수</ko>
* @return An instance of a component itself<ko>컴포넌트 자신의 인스턴스</ko>
* @example
* ```ts
* import Component, { ComponentEvent } from "@egjs/component";
*
* class Some extends Component<{
* hi: void;
* }> {
* hi() {
* console.log("hi");
* }
* some() {
* this.on("hi",this.hi); //attach event
* }
* }
* ```
*/
__proto.on = function (eventName, handlerToAttach) {
if (typeof eventName === "object" && isUndefined(handlerToAttach)) {
var eventHash = eventName;
for (var name in eventHash) {
this.on(name, eventHash[name]);
}
return this;
} else if (typeof eventName === "string" && typeof handlerToAttach === "function") {
var handlerList = this._eventHandler[eventName];
if (isUndefined(handlerList)) {
this._eventHandler[eventName] = [];
handlerList = this._eventHandler[eventName];
}
handlerList.push(handlerToAttach);
}
return this;
};
/**
* Detaches an event from the component.<br/>If the `eventName` is not given this will detach all event handlers attached.<br/>If the `handlerToDetach` is not given, this will detach all event handlers for `eventName`.
* @ko 컴포넌트에 등록된 이벤트를 해제한다.<br/>`eventName`이 주어지지 않았을 경우 모든 이벤트 핸들러를 제거한다.<br/>`handlerToAttach`가 주어지지 않았을 경우 `eventName`에 해당하는 모든 이벤트 핸들러를 제거한다.
* @param {string?} eventName The name of the event to be detached <ko>해제할 이벤트의 이름</ko>
* @param {function?} handlerToDetach The handler function of the event to be detached <ko>해제할 이벤트의 핸들러 함수</ko>
* @return An instance of a component itself <ko>컴포넌트 자신의 인스턴스</ko>
* @example
* ```ts
* import Component, { ComponentEvent } from "@egjs/component";
*
* class Some extends Component<{
* hi: void;
* }> {
* hi() {
* console.log("hi");
* }
* some() {
* this.off("hi",this.hi); //detach event
* }
* }
* ```
*/
__proto.off = function (eventName, handlerToDetach) {
var e_1, _a; // Detach all event handlers.
if (isUndefined(eventName)) {
this._eventHandler = {};
return this;
} // Detach all handlers for eventname or detach event handlers by object.
if (isUndefined(handlerToDetach)) {
if (typeof eventName === "string") {
delete this._eventHandler[eventName];
return this;
} else {
var eventHash = eventName;
for (var name in eventHash) {
this.off(name, eventHash[name]);
}
return this;
}
} // Detach single event handler
var handlerList = this._eventHandler[eventName];
if (handlerList) {
var idx = 0;
try {
for (var handlerList_1 = __values(handlerList), handlerList_1_1 = handlerList_1.next(); !handlerList_1_1.done; handlerList_1_1 = handlerList_1.next()) {
var handlerFunction = handlerList_1_1.value;
if (handlerFunction === handlerToDetach) {
handlerList.splice(idx, 1);
if (handlerList.length <= 0) {
delete this._eventHandler[eventName];
}
break;
}
idx++;
}
} catch (e_1_1) {
e_1 = {
error: e_1_1
};
} finally {
try {
if (handlerList_1_1 && !handlerList_1_1.done && (_a = handlerList_1.return)) _a.call(handlerList_1);
} finally {
if (e_1) throw e_1.error;
}
}
}
return this;
};
/**
* Version info string
* @ko 버전정보 문자열
* @name VERSION
* @static
* @example
* Component.VERSION; // ex) 3.0.0
* @memberof Component
*/
Component.VERSION = "3.0.1";
return Component;
}();
/*
* Copyright (c) 2015 NAVER Corp.
* egjs projects are licensed under the MIT license
*/
var ComponentEvent$1 = ComponentEvent;
/*
Copyright (c) 2020-present NAVER Corp.
name: @egjs/imready
license: MIT
author: NAVER Corp.
repository: https://github.com/naver/egjs-imready
version: 1.3.0
*/
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise */
var extendStatics$1 = function (d, b) {
extendStatics$1 = Object.setPrototypeOf || {
__proto__: []
} instanceof Array && function (d, b) {
d.__proto__ = b;
} || function (d, b) {
for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p];
};
return extendStatics$1(d, b);
};
function __extends$1(d, b) {
extendStatics$1(d, b);
function __() {
this.constructor = d;
}
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign$1 = function () {
__assign$1 = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
};
return __assign$1.apply(this, arguments);
};
function __spreadArrays$1() {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++) for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) r[k] = a[j];
return r;
}
/*
egjs-imready
Copyright (c) 2020-present NAVER Corp.
MIT license
*/
var isWindow = typeof window !== "undefined";
var ua = isWindow ? window.navigator.userAgent : "";
var SUPPORT_COMPUTEDSTYLE = isWindow ? !!("getComputedStyle" in window) : false;
var IS_IE = /MSIE|Trident|Windows Phone|Edge/.test(ua);
var SUPPORT_ADDEVENTLISTENER = isWindow ? !!("addEventListener" in document) : false;
var WIDTH = "width";
var HEIGHT = "height";
function getAttribute(el, name) {
return el.getAttribute(name) || "";
}
function toArray(arr) {
return [].slice.call(arr);
}
function hasSizeAttribute(target, prefix) {
if (prefix === void 0) {
prefix = "data-";
}
return !!target.getAttribute(prefix + "width");
}
function hasLoadingAttribute(target, prefix) {
if (prefix === void 0) {
prefix = "data-";
}
return "loading" in target && target.getAttribute("loading") === "lazy" || !!target.getAttribute(prefix + "lazy");
}
function hasSkipAttribute(target, prefix) {
if (prefix === void 0) {
prefix = "data-";
}
return !!target.getAttribute(prefix + "skip");
}
function addEvent(element, type, handler) {
if (SUPPORT_ADDEVENTLISTENER) {
element.addEventListener(type, handler, false);
} else if (element.attachEvent) {
element.attachEvent("on" + type, handler);
} else {
element["on" + type] = handler;
}
}
function removeEvent(element, type, handler) {
if (element.removeEventListener) {
element.removeEventListener(type, handler, false);
} else if (element.detachEvent) {
element.detachEvent("on" + type, handler);
} else {
element["on" + type] = null;
}
}
function innerWidth(el) {
return getSize(el, "Width");
}
function innerHeight(el) {
return getSize(el, "Height");
}
function getStyles(el) {
return (SUPPORT_COMPUTEDSTYLE ? window.getComputedStyle(el) : el.currentStyle) || {};
}
function getSize(el, name) {
var size = el["client" + name] || el["offset" + name];
return parseFloat(size || getStyles(el)[name.toLowerCase()]) || 0;
}
function getContentElements(element, tags, prefix) {
var skipElements = toArray(element.querySelectorAll(__spreadArrays$1(["[" + prefix + "skip] [" + prefix + "width]"], tags.map(function (tag) {
return ["[" + prefix + "skip] " + tag, tag + "[" + prefix + "skip]", "[" + prefix + "width] " + tag].join(", ");
})).join(", ")));
return toArray(element.querySelectorAll("[" + prefix + "width], " + tags.join(", "))).filter(function (el) {
return skipElements.indexOf(el) === -1;
});
}
/*
egjs-imready
Copyright (c) 2020-present NAVER Corp.
MIT license
*/
var elements = [];
function addAutoSizer(element, prefix) {
!elements.length && addEvent(window, "resize", resizeAllAutoSizers);
element.__PREFIX__ = prefix;
elements.push(element);
resize(element);
}
function removeAutoSizer(element, prefix) {
var index = elements.indexOf(element);
if (index < 0) {
return;
}
var fixed = getAttribute(element, prefix + "fixed");
delete element.__PREFIX__;
element.style[fixed === HEIGHT ? WIDTH : HEIGHT] = "";
elements.splice(index, 1);
!elements.length && removeEvent(window, "resize", resizeAllAutoSizers);
}
function resize(element, prefix) {
if (prefix === void 0) {
prefix = "data-";
}
var elementPrefix = element.__PREFIX__ || prefix;
var dataWidth = parseInt(getAttribute(element, "" + elementPrefix + WIDTH), 10) || 0;
var dataHeight = parseInt(getAttribute(element, "" + elementPrefix + HEIGHT), 10) || 0;
var fixed = getAttribute(element, elementPrefix + "fixed");
if (fixed === HEIGHT) {
var size = innerHeight(element) || dataHeight;
element.style[WIDTH] = dataWidth / dataHeight * size + "px";
} else {
var size = innerWidth(element) || dataWidth;
element.style[HEIGHT] = dataHeight / dataWidth * size + "px";
}
}
function resizeAllAutoSizers() {
elements.forEach(function (element) {
resize(element);
});
}
var Loader =
/*#__PURE__*/
function (_super) {
__extends$1(Loader, _super);
function Loader(element, options) {
if (options === void 0) {
options = {};
}
var _this = _super.call(this) || this;
_this.isReady = false;
_this.isPreReady = false;
_this.hasDataSize = false;
_this.hasLoading = false;
_this.isSkip = false;
_this.onCheck = function (e) {
_this.clear();
if (e && e.type === "error") {
_this.onError(_this.element);
}
if (_this.hasLoading && _this.checkElement()) {
// I'm not ready
return;
} // I'm pre-ready and ready!
var withPreReady = !_this.hasDataSize && !_this.hasLoading;
_this.onReady(withPreReady);
};
_this.options = __assign$1({
prefix: "data-"
}, options);
_this.element = element;
var prefix = _this.options.prefix;
_this.hasDataSize = hasSizeAttribute(element, prefix);
_this.isSkip = hasSkipAttribute(element, prefix);
_this.hasLoading = hasLoadingAttribute(element, prefix);
return _this;
}
var __proto = Loader.prototype;
__proto.check = function () {
if (this.isSkip || !this.checkElement()) {
// I'm Ready
this.onAlreadyReady(true);
return false;
}
if (this.hasDataSize) {
addAutoSizer(this.element, this.options.prefix);
}
if (this.hasDataSize || this.hasLoading) {
// I'm Pre Ready
this.onAlreadyPreReady();
} // Wati Pre Ready, Ready
return true;
};
__proto.addEvents = function () {
var _this = this;
var element = this.element;
this.constructor.EVENTS.forEach(function (name) {
addEvent(element, name, _this.onCheck);
});
};
__proto.clear = function () {
var _this = this;
var element = this.element;
this.constructor.EVENTS.forEach(function (name) {
removeEvent(element, name, _this.onCheck);
});
this.removeAutoSizer();
};
__proto.destroy = function () {
this.clear();
this.off();
};
__proto.removeAutoSizer = function () {
if (this.hasDataSize) {
// I'm already ready.
var prefix = this.options.prefix;
removeAutoSizer(this.element, prefix);
}
};
__proto.onError = function (target) {
this.trigger("error", {
element: this.element,
target: target
});
};
__proto.onPreReady = function () {
if (this.isPreReady) {
return;
}
this.isPreReady = true;
this.trigger("preReady", {
element: this.element,
hasLoading: this.hasLoading,
isSkip: this.isSkip
});
};
__proto.onReady = function (withPreReady) {
if (this.isReady) {
return;
}
withPreReady = !this.isPreReady && withPreReady;
if (withPreReady) {
this.isPreReady = true;
}
this.removeAutoSizer();
this.isReady = true;
this.trigger("ready", {
element: this.element,
withPreReady: withPreReady,
hasLoading: this.hasLoading,
isSkip: this.isSkip
});
};
__proto.onAlreadyError = function (target) {
var _this = this;
setTimeout(function () {
_this.onError(target);
});
};
__proto.onAlreadyPreReady = function () {
var _this = this;
setTimeout(function () {
_this.onPreReady();
});
};
__proto.onAlreadyReady = function (withPreReady) {
var _this = this;
setTimeout(function () {
_this.onReady(withPreReady);
});
};
Loader.EVENTS = [];
return Loader;
}(Component);
var ElementLoader =
/*#__PURE__*/
function (_super) {
__extends$1(ElementLoader, _super);
function ElementLoader() {
return _super !== null && _super.apply(this, arguments) || this;
}
var __proto = ElementLoader.prototype;
__proto.setHasLoading = function (hasLoading) {
this.hasLoading = hasLoading;
};
__proto.check = function () {
if (this.isSkip) {
// I'm Ready
this.onAlreadyReady(true);
return false;
}
if (this.hasDataSize) {
addAutoSizer(this.element, this.options.prefix);
this.onAlreadyPreReady();
} else {
// has not data size
this.trigger("requestChildren");
}
return true;
};
__proto.checkElement = function () {
return true;
};
__proto.destroy = function () {
this.clear();
this.trigger("requestDestroy");
this.off();
};
__proto.onAlreadyPreReady = function () {
// has data size
_super.prototype.onAlreadyPreReady.call(this);
this.trigger("reqeustReadyChildren");
};
ElementLoader.EVENTS = [];
return ElementLoader;
}(Loader);
/**
* @alias eg.ImReady
* @extends eg.Component
*/
var ImReadyManager =
/*#__PURE__*/
function (_super) {
__extends$1(ImReadyManager, _super);
/**
* @param - ImReady's options
*/
function ImReadyManager(options) {
if (options === void 0) {
options = {};
}
var _this = _super.call(this) || this;
_this.readyCount = 0;
_this.preReadyCount = 0;
_this.totalCount = 0;
_this.totalErrorCount = 0;
_this.isPreReadyOver = true;
_this.elementInfos = [];
_this.options = __assign$1({
loaders: {},
prefix: "data-"
}, options);
return _this;
}
/**
* Checks whether elements are in the ready state.
* @ko 엘리먼트가 준비 상태인지 체크한다.
* @elements - Elements to check ready status. <ko> 준비 상태를 체크할 엘리먼트들.</ko>
* @example
* ```html
* <div>
* <img src="./1.jpg" data-width="1280" data-height="853" style="width:100%"/>
* <img src="./2.jpg" data-width="1280" data-height="853"/>
* <img src="ERR" data-width="1280" data-height="853"/>
* </div>
* ```
* ## Javascript
* ```js
* import ImReady from "@egjs/imready";
*
* const im = new ImReady(); // umd: eg.ImReady
* im.check(document.querySelectorAll("img")).on({
* preReadyElement: e => {
* // 1, 3
* // 2, 3
* // 3, 3
* console.log(e.preReadyCount, e.totalCount),
* },
* });
* ```
*/
var __proto = ImReadyManager.prototype;
__proto.check = function (elements) {
var _this = this;
var prefix = this.options.prefix;
this.clear();
this.elementInfos = toArray(elements).map(function (element, index) {
var loader = _this.getLoader(element, {
prefix: prefix
});
loader.check();
loader.on("error", function (e) {
_this.onError(index, e.target);
}).on("preReady", function (e) {
var info = _this.elementInfos[index];
info.hasLoading = e.hasLoading;
info.isSkip = e.isSkip;
var isPreReady = _this.checkPreReady(index);
_this.onPreReadyElement(index);
isPreReady && _this.onPreReady();
}).on("ready", function (_a) {
var withPreReady = _a.withPreReady,
hasLoading = _a.hasLoading,
isSkip = _a.isSkip;
var info = _this.elementInfos[index];
info.hasLoading = hasLoading;
info.isSkip = isSkip;
var isPreReady = withPreReady && _this.checkPreReady(index);
var isReady = _this.checkReady(index); // Pre-ready and ready occur simultaneously
withPreReady && _this.onPreReadyElement(index);
_this.onReadyElement(index);
isPreReady && _this.onPreReady();
isReady && _this.onReady();
});
return {
loader: loader,
element: element,
hasLoading: false,
hasError: false,
isPreReady: false,
isReady: false,
isSkip: false
};
});
var length = this.elementInfos.length;
this.totalCount = length;
if (!length) {
setTimeout(function () {
_this.onPreReady();
_this.onReady();
});
}
return this;
};
/**
* Gets the total count of elements to be checked.
* @ko 체크하는 element의 총 개수를 가져온다.
*/
__proto.getTotalCount = function () {
return this.totalCount;
};
/**
* Whether the elements are all pre-ready. (all sizes are known)
* @ko 엘리먼트들이 모두 사전 준비가 됐는지 (사이즈를 전부 알 수 있는지) 여부.
*/
__proto.isPreReady = function () {
return this.elementInfos.every(function (info) {
return info.isPreReady;
});
};
/**
* Whether the elements are all ready.
* @ko 엘리먼트들이 모두 준비가 됐는지 여부.
*/
__proto.isReady = function () {
return this.elementInfos.every(function (info) {
return info.isReady;
});
};
/**
* Whether an error has occurred in the elements in the current state.
* @ko 현재 상태에서 엘리먼트들이 에러가 발생했는지 여부.
*/
__proto.hasError = function () {
return this.totalErrorCount > 0;
};
/**
* Clears events of elements being checked.
* @ko 체크 중인 엘리먼트들의 이벤트를 해제 한다.
*/
__proto.clear = function () {
this.isPreReadyOver = false;
this.totalCount = 0;
this.preReadyCount = 0;
this.readyCount = 0;
this.totalErrorCount = 0;
this.elementInfos.forEach(function (info) {
if (!info.isReady && info.loader) {
info.loader.destroy();
}
});
this.elementInfos = [];
};
/**
* Destory all events.
* @ko 모든 이벤트를 해제 한다.
*/
__proto.destroy = function () {
this.clear();
this.off();
};
__proto.getLoader = function (element, options) {
var _this = this;
var tagName = element.tagName.toLowerCase();
var loaders = this.options.loaders;
var prefix = options.prefix;
var tags = Object.keys(loaders);
if (loaders[tagName]) {
return new loaders[tagName](element, options);
}
var loader = new ElementLoader(element, options);
var children = toArray(element.querySelectorAll(tags.join(", ")));
loader.setHasLoading(children.some(function (el) {
return hasLoadingAttribute(el, prefix);
}));
var withPreReady = false;
var childrenImReady = this.clone().on("error", function (e) {
loader.onError(e.target);
}).on("ready", function () {
loader.onReady(withPreReady);
});
loader.on("requestChildren", function () {
// has not data size
var contentElements = getContentElements(element, tags, _this.options.prefix);
childrenImReady.check(contentElements).on("preReady", function (e) {
withPreReady = e.isReady;
if (!withPreReady) {
loader.onPreReady();
}
});
}).on("reqeustReadyChildren", function () {
// has data size
// loader call preReady
// check only video, image elements
childrenImReady.check(children);
}).on("requestDestroy", function () {
childrenImReady.destroy();
});
return loader;
};
__proto.clone = function () {
return new ImReadyManager(__assign$1({}, this.options));
};
__proto.checkPreReady = function (index) {
this.elementInfos[index].isPreReady = true;
++this.preReadyCount;
if (this.preReadyCount < this.totalCount) {
return false;
}
return true;
};
__proto.checkReady = function (index) {
this.elementInfos[index].isReady = true;
++this.readyCount;
if (this.readyCount < this.totalCount) {
return false;
}
return true;
};
__proto.onError = function (index, target) {
var info = this.elementInfos[index];
info.hasError = true;
/**
* An event occurs if the image, video fails to load.
* @ko 이미지, 비디오가 로딩에 실패하면 이벤트가 발생한다.
* @event eg.ImReady#error
* @param {eg.ImReady.OnError} e - The object of data to be sent to an event <ko>이벤트에 전달되는 데이터 객체</ko>
* @example
* ```html
* <div>
* <img src="./1.jpg" data-width="1280" data-height="853" style="width:100%"/>
* <img src="./2.jpg"/>
* <img src="ERR"/>
* </div>
* ```
* ## Javascript
* ```js
* import ImReady from "@egjs/imready";
*
* const im = new ImReady(); // umd: eg.ImReady
* im.check([document.querySelector("div")]).on({
* error: e => {
* // <div>...</div>, 0, <img src="ERR"/>
* console.log(e.element, e.index, e.target),
* },
* });
* ```
*/
this.trigger(new ComponentEvent$1("error", {
element: info.element,
index: index,
target: target,
errorCount: this.getErrorCount(),
totalErrorCount: ++this.totalErrorCount
}));
};
__proto.onPreReadyElement = function (index) {
var info = this.elementInfos[index];
/**
* An event occurs when the element is pre-ready (when the loading attribute is applied or the size is known)
* @ko 해당 엘리먼트가 사전 준비되었을 때(loading 속성이 적용되었거나 사이즈를 알 수 있을 때) 이벤트가 발생한다.
* @event eg.ImReady#preReadyElement
* @param {eg.ImReady.OnPreReadyElement} e - The object of data to be sent to an event <ko>이벤트에 전달되는 데이터 객체</ko>
* @example
* ```html
* <div>
* <img src="./1.jpg" data-width="1280" data-height="853" style="width:100%"/>
* <img src="./2.jpg" data-width="1280" data-height="853"/>
* <img src="ERR" data-width="1280" data-height="853"/>
* </div>
* ```
* ## Javascript
* ```js
* import ImReady from "@egjs/imready";
*
* const im = new ImReady(); // umd: eg.ImReady
* im.check(document.querySelectorAll("img")).on({
* preReadyElement: e => {
* // 1, 3
* // 2, 3
* // 3, 3
* console.log(e.preReadyCount, e.totalCount),
* },
* });
* ```
*/
this.trigger(new ComponentEvent$1("preReadyElement", {
element: info.element,
index: index,
preReadyCount: this.preReadyCount,
readyCount: this.readyCount,
totalCount: this.totalCount,
isPreReady: this.isPreReady(),
isReady: this.isReady(),
hasLoading: info.hasLoading,
isSkip: info.isSkip
}));
};
__proto.onPreReady = function () {
this.isPreReadyOver = true;
/**
* An event occurs when all element are pre-ready (When all elements have the loading attribute applied or the size is known)
* @ko 모든 엘리먼트들이 사전 준비된 경우 (모든 엘리먼트들이 loading 속성이 적용되었거나 사이즈를 알 수 있는 경우) 이벤트가 발생한다.
* @event eg.ImReady#preReady
* @param {eg.ImReady.OnPreReady} e - The object of data to be sent to an event <ko>이벤트에 전달되는 데이터 객체</ko>
* @example
* ```html
* <div>
* <img src="./1.jpg" data-width="1280" data-height="853" style="width:100%"/>
* <img src="./2.jpg" data-width="1280" data-height="853"/>
* <img src="ERR" data-width="1280" data-height="853"/>
* </div>
* ```
* ## Javascript
* ```js
* import ImReady from "@egjs/imready";
*
* const im = new ImReady(); // umd: eg.ImReady
* im.check(document.querySelectorAll("img")).on({
* preReady: e => {
* // 0, 3
* console.log(e.readyCount, e.totalCount),
* },
* });
* ```
*/
this.trigger(new ComponentEvent$1("preReady", {
readyCount: this.readyCount,
totalCount: this.totalCount,
isReady: this.isReady(),
hasLoading: this.hasLoading()
}));
};
__proto.onReadyElement = function (index) {
var info = this.elementInfos[index];
/**
* An event occurs when the element is ready
* @ko 해당 엘리먼트가 준비가 되었을 때 이벤트가 발생한다.
* @event eg.ImReady#readyElement
* @param {eg.ImReady.OnReadyElement} e - The object of data to be sent to an event <ko>이벤트에 전달되는 데이터 객체</ko>
* @example
* ```html
* <div>
* <img src="./1.jpg" data-width="1280" data-height="853" style="width:100%"/>
* <img src="./2.jpg" data-width="1280" data-height="853"/>
* <img src="ERR" data-width="1280" data-height="853"/>
* </div>
* ```
* ## Javascript
* ```js
* import ImReady from "@egjs/imready";
*
* const im = new ImReady(); // umd: eg.ImReady
* im.check(document.querySelectorAll("img")).on({
* readyElement: e => {
* // 1, 0, false, 3
* // 2, 1, false, 3
* // 3, 2, true, 3
* console.log(e.readyCount, e.index, e.hasError, e.totalCount),
* },
* });
* ```
*/
this.trigger(new ComponentEvent$1("readyElement", {
index: index,
element: info.element,
hasError: info.hasError,
errorCount: this.getErrorCount(),
totalErrorCount: this.totalErrorCount,
preReadyCount: this.preReadyCount,
readyCount: this.readyCount,
totalCount: this.totalCount,
isPreReady: this.isPreReady(),
isReady: this.isReady(),
hasLoading: info.hasLoading,
isPreReadyOver: this.isPreReadyOver,
isSkip: info.isSkip
}));
};
__proto.onReady = function () {
/**
* An event occurs when all element are ready
* @ko 모든 엘리먼트들이 준비된 경우 이벤트가 발생한다.
* @event eg.ImReady#ready
* @param {eg.ImReady.OnReady} e - The object of data to be sent to an event <ko>이벤트에 전달되는 데이터 객체</ko>
* @example
* ```html
* <div>
* <img src="./1.jpg" data-width="1280" data-height="853" style="width:100%"/>
* <img src="./2.jpg" data-width="1280" data-height="853"/>
* <img src="ERR" data-width="1280" data-height="853"/>
* </div>
* ```
* ## Javascript
* ```js
* import ImReady from "@egjs/imready";
*
* const im = new ImReady(); // umd: eg.ImReady
* im.check(document.querySelectorAll("img")).on({
* preReady: e => {
* // 0, 3
* console.log(e.readyCount, e.totalCount),
* },
* ready: e => {
* // 1, 3
* console.log(e.errorCount, e.totalCount),
* },
* });
* ```
*/
this.trigger(new ComponentEvent$1("ready", {
errorCount: this.getErrorCount(),
totalErrorCount: this.totalErrorCount,
totalCount: this.totalCount
}));
};
__proto.getErrorCount = function () {
return this.elementInfos.filter(function (info) {
return info.hasError;
}).length;
};
__proto.hasLoading = function () {
return this.elementInfos.some(function (info) {
return info.hasLoading;
});
};
return ImReadyManager;
}(Component);
var ImageLoader =
/*#__PURE__*/
function (_super) {
__extends$1(ImageLoader, _super);
function ImageLoader() {
return _super !== null && _super.apply(this, arguments) || this;
}
var __proto = ImageLoader.prototype;
__proto.checkElement = function () {
var element = this.element;
var src = element.getAttribute("src");
if (element.complete) {
if (src) {
// complete
if (!element.naturalWidth) {
this.onAlreadyError(element);
}
return false;
} else {
// Using an external lazy loading module
this.onAlreadyPreReady();
}
}
this.addEvents();
IS_IE && element.setAttribute("src", src);
return true;
};
ImageLoader.EVENTS = ["load", "error"];
return ImageLoader;
}(Loader);
var VideoLoader =
/*#__PURE__*/
function (_super) {
__extends$1(VideoLoader, _super);
function VideoLoader() {
return _super !== null && _super.apply(this, arguments) || this;
}
var __proto = VideoLoader.prototype;
__proto.checkElement = function () {
var element = this.element; // HAVE_NOTHING: 0, no information whether or not the audio/video is ready
// HAVE_METADATA: 1, HAVE_METADATA - metadata for the audio/video is ready
// HAVE_CURRENT_DATA: 2, data for the current playback position is available, but not enough data to play next frame/millisecond
// HAVE_FUTURE_DATA: 3, data for the current and at least the next frame is available
// HAVE_ENOUGH_DATA: 4, enough data available to start playing
if (element.readyState >= 1) {
return false;
}
if (element.error) {
this.onAlreadyError(element);
return false;
}
this.addEvents();
return true;
};
VideoLoader.EVENTS = ["loadedmetadata", "error"];
return VideoLoader;
}(Loader);
var ImReady =
/*#__PURE__*/
function (_super) {
__extends$1(ImReady, _super);
function ImReady(options) {
if (options === void 0) {
options = {};
}
return _super.call(this, __assign$1({
loaders: {
img: ImageLoader,
video: VideoLoader
}
}, options)) || this;
}
return ImReady;
}(ImReadyManager);
/*
Copyright (c) 2019-present NAVER Corp.
name: @egjs/list-differ
license: MIT
author: NAVER Corp.
repository: https://github.com/naver/egjs-list-differ
version: 1.0.0
*/
/*
egjs-list-differ
Copyright (c) 2019-present NAVER Corp.
MIT license
*/
var PolyMap =
/*#__PURE__*/
function () {
function PolyMap() {
this.keys = [];
this.values = [];
}
var __proto = PolyMap.prototype;
__proto.get = function (key) {
return this.values[this.keys.indexOf(key)];
};
__proto.set = function (key, value) {
var keys = this.keys;
var values = this.values;
var prevIndex = keys.indexOf(key);
var index = prevIndex === -1 ? keys.length : prevIndex;
keys[index] = key;
values[index] = value;
};
return PolyMap;
}();
/*
egjs-list-differ
Copyright (c) 2019-present NAVER Corp.
MIT license
*/
var HashMap =
/*#__PURE__*/
function () {
function HashMap() {
this.object = {};
}
var __proto = HashMap.prototype;
__proto.get = function (key) {
return this.object[key];
};
__proto.set = function (key, value) {
this.object[key] = value;
};
return HashMap;
}();
/*
egjs-list-differ
Copyright (c) 2019-present NAVER Corp.
MIT license
*/
var SUPPORT_MAP = typeof Map === "function";
/*
egjs-list-differ
Copyright (c) 2019-present NAVER Corp.
MIT license
*/
var Link =
/*#__PURE__*/
function () {
function Link() {}
var __proto = Link.prototype;
__proto.connect = function (prevLink, nextLink) {
this.prev = prevLink;
this.next = nextLink;
prevLink && (prevLink.next = this);
nextLink && (nextLink.prev = this);
};
__proto.disconnect = function () {
// In double linked list, diconnect the interconnected relationship.
var prevLink = this.prev;
var nextLink = this.next;
prevLink && (prevLink.next = nextLink);
nextLink && (nextLink.prev = prevLink);
};
__proto.getIndex = function () {
var link = this;
var index = -1;
while (link) {
link = link.prev;
++index;
}
return index;
};
return Link;
}();
/*
egjs-list-differ
Copyright (c) 2019-present NAVER Corp.
MIT license
*/
function orderChanged(changed, fixed) {
// It is roughly in the order of these examples.
// 4, 6, 0, 2, 1, 3, 5, 7
var fromLinks = []; // 0, 1, 2, 3, 4, 5, 6, 7
var toLinks = [];
changed.forEach(function (_a) {
var from = _a[0],
to = _a[1];
var link = new Link();
fromLinks[from] = link;
toLinks[to] = link;
}); // `fromLinks` are connected to each other by double linked list.
fromLinks.forEach(function (link, i) {
link.connect(fromLinks[i - 1]);
});
return changed.filter(function (_, i) {
return !fixed[i];
}).map(function (_a, i) {
var from = _a[0],
to = _a[1];
if (from === to) {
return [0, 0];
}
var fromLink = fromLinks[from];
var toLink = toLinks[to - 1];
var fromIndex = fromLink.getIndex(); // Disconnect the link connected to `fromLink`.
fromLink.disconnect(); // Connect `fromLink` to the right of `toLink`.
if (!toLink) {
fromLink.connect(undefined, fromLinks[0]);
} else {
fromLink.connect(toLink, toLink.next);
}
var toIndex = fromLink.getIndex();
return [fromIndex, toIndex];
});
}
var Result =
/*#__PURE__*/
function () {
function Result(prevList, list, added, removed, changed, maintained, changedBeforeAdded, fixed) {
this.prevList = prevList;
this.list = list;
this.added = added;
this.removed = removed;
this.changed = changed;
this.maintained = maintained;
this.changedBeforeAdded = changedBeforeAdded;
this.fixed = fixed;
}
var __proto = Result.prototype;
Object.defineProperty(__proto, "ordered", {
get: function () {
if (!this.cacheOrdered) {
this.caculateOrdered();
}
return this.cacheOrdered;
},
enumerable: true,
configurable: true
});
Object.defineProperty(__proto, "pureChanged", {
get: function () {
if (!this.cachePureChanged) {
this.caculateOrdered();
}
return this.cachePureChanged;
},
enumerable: true,
configurable: true
});
__proto.caculateOrdered = function () {
var ordered = orderChanged(this.changedBeforeAdded, this.fixed);
var changed = this.changed;
var pureChanged = [];
this.cacheOrdered = ordered.filter(function (_a, i) {
var from = _a[0],
to = _a[1];
var _b = changed[i],
fromBefore = _b[0],
toBefore = _b[1];
if (from !== to) {
pureChanged.push([fromBefore, toBefore]);
return true;
}
});
this.cachePureChanged = pureChanged;
};
return Result;
}();
/**
*
* @memberof eg.ListDiffer
* @static
* @function
* @param - Previous List <ko> 이전 목록 </ko>
* @param - List to Update <ko> 업데이트 할 목록 </ko>
* @param - This callback function returns the key of the item. <ko> 아이템의 키를 반환하는 콜백 함수입니다.</ko>
* @return - Returns the diff between `prevList` and `list` <ko> `prevList`와 `list`의 다른 점을 반환한다.</ko>
* @example
* import { diff } from "@egjs/list-differ";
* // script => eg.ListDiffer.diff
* const result = diff([0, 1, 2, 3, 4, 5], [7, 8, 0, 4, 3, 6, 2, 1], e => e);
* // List before update
* // [1, 2, 3, 4, 5]
* console.log(result.prevList);
* // Updated list
* // [4, 3, 6, 2, 1]
* console.log(result.list);
* // Index array of values added to `list`
* // [0, 1, 5]
* console.log(result.added);
* // Index array of values removed in `prevList`
* // [5]
* console.log(result.removed);
* // An array of index pairs of `prevList` and `list` with different indexes from `prevList` and `list`
* // [[0, 2], [4, 3], [3, 4], [2, 6], [1, 7]]
* console.log(result.changed);
* // The subset of `changed` and an array of index pairs that moved data directly. Indicate an array of absolute index pairs of `ordered`.(Formatted by: Array<[index of prevList, index of list]>)
* // [[4, 3], [3, 4], [2, 6]]
* console.log(result.pureChanged);
* // An array of index pairs to be `ordered` that can synchronize `list` before adding data. (Formatted by: Array<[prevIndex, nextIndex]>)
* // [[4, 1], [4, 2], [4, 3]]
* console.log(result.ordered);
* // An array of index pairs of `prevList` and `list` that have not been added/removed so data is preserved
* // [[0, 2], [4, 3], [3, 4], [2, 6], [1, 7]]
* console.log(result.maintained);
*/
function diff(prevList, list, findKeyCallback) {
var mapClass = SUPPORT_MAP ? Map : findKeyCallback ? HashMap : PolyMap;
var callback = findKeyCallback || function (e) {
return e;
};
var added = [];
var removed = [];
var maintained = [];
var prevKeys = prevList.map(callback);
var keys = list.map(callback);
var prevKeyMap = new mapClass();
var keyMap = new mapClass();
var changedBeforeAdded = [];
var fixed = [];
var removedMap = {};
var changed = [];
var addedCount = 0;
var removedCount = 0; // Add prevKeys and keys to the hashmap.
prevKeys.forEach(function (key, prevListIndex) {
prevKeyMap.set(key, prevListIndex);
});
keys.forEach(function (key, listIndex) {
keyMap.set(key, listIndex);
}); // Compare `prevKeys` and `keys` and add them to `removed` if they are not in `keys`.
prevKeys.forEach(function (key, prevListIndex) {
var listIndex = keyMap.get(key); // In prevList, but not in list, it is removed.
if (typeof listIndex === "undefined") {
++removedCount;
removed.push(prevListIndex);
} else {
removedMap[listIndex] = removedCount;
}
}); // Compare `prevKeys` and `keys` and add them to `added` if they are not in `prevKeys`.
keys.forEach(function (key, listIndex) {
var prevListIndex = prevKeyMap.get(key); // In list, but not in prevList, it is added.
if (typeof prevListIndex === "undefined") {
added.push(listIndex);
++addedCount;
} else {
maintained.push([prevListIndex, listIndex]);
removedCount = removedMap[listIndex] || 0;
changedBeforeAdded.push([prevListIndex - removedCount, listIndex - addedCount]);
fixed.push(listIndex === prevListIndex);
if (prevListIndex !== listIndex) {
changed.push([prevListIndex, listIndex]);
}
}
}); // Sort by ascending order of 'to(list's index).
removed.reverse();
return new Result(prevList, list, added, removed, changed, maintained, changedBeforeAdded, fixed);
}
/*
Copyright (c) 2019-present NAVER Corp.
name: @egjs/children-differ
license: MIT
author: NAVER Corp.
repository: https://github.com/naver/egjs-children-differ
version: 1.0.1
*/
/*
egjs-children-differ
Copyright (c) 2019-present NAVER Corp.
MIT license
*/
var findKeyCallback = typeof Map === "function" ? undefined : function () {
var childrenCount = 0;
return function (el) {
return el.__DIFF_KEY__ || (el.__DIFF_KEY__ = ++childrenCount);
};
}();
/*
egjs-children-differ
Copyright (c) 2019-present NAVER Corp.
MIT license
*/
/**
*
* @memberof eg.ChildrenDiffer
* @static
* @function
* @param - Previous List <ko> 이전 목록 </ko>
* @param - List to Update <ko> 업데이트 할 목록 </ko>
* @return - Returns the diff between `prevList` and `list` <ko> `prevList`와 `list`의 다른 점을 반환한다.</ko>
* @example
* import { diff } from "@egjs/children-differ";
* // script => eg.ChildrenDiffer.diff
* const result = diff([0, 1, 2, 3, 4, 5], [7, 8, 0, 4, 3, 6, 2, 1]);
* // List before update
* // [1, 2, 3, 4, 5]
* console.log(result.prevList);
* // Updated list
* // [4, 3, 6, 2, 1]
* console.log(result.list);
* // Index array of values added to `list`
* // [0, 1, 5]
* console.log(result.added);
* // Index array of values removed in `prevList`
* // [5]
* console.log(result.removed);
* // An array of index pairs of `prevList` and `list` with different indexes from `prevList` and `list`
* // [[0, 2], [4, 3], [3, 4], [2, 6], [1, 7]]
* console.log(result.changed);
* // The subset of `changed` and an array of index pairs that moved data directly. Indicate an array of absolute index pairs of `ordered`.(Formatted by: Array<[index of prevList, index of list]>)
* // [[4, 3], [3, 4], [2, 6]]
* console.log(result.pureChanged);
* // An array of index pairs to be `ordered` that can synchronize `list` before adding data. (Formatted by: Array<[prevIndex, nextIndex]>)
* // [[4, 1], [4, 2], [4, 3]]
* console.log(result.ordered);
* // An array of index pairs of `prevList` and `list` that have not been added/removed so data is preserved
* // [[0, 2], [4, 3], [3, 4], [2, 6], [1, 7]]
* console.log(result.maintained);
*/
function diff$1(prevList, list) {
return diff(prevList, list, findKeyCallback);
}
/*
Copyright (c) 2021-present NAVER Corp.
name: @egjs/grid
license: MIT
author: NAVER Corp.
repository: https://github.com/naver/egjs-grid
version: 1.9.0-beta.2
*/
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise */
var extendStatics$2 = function (d, b) {
extendStatics$2 = Object.setPrototypeOf || {
__proto__: []
} instanceof Array && function (d, b) {
d.__proto__ = b;
} || function (d, b) {
for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p];
};
return extendStatics$2(d, b);
};
function __extends$2(d, b) {
if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics$2(d, b);
function __() {
this.constructor = d;
}
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign$2 = function () {
__assign$2 = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
};
return __assign$2.apply(this, arguments);
};
function __decorate$1(decorators, target, key, desc) {
var c = arguments.length,
r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc,
d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
}
function __spreadArray(to, from) {
for (var i = 0, il = from.length, j = to.length; i < il; i++, j++) to[j] = from[i];
return to;
}
var DEFAULT_GRID_OPTIONS = {
horizontal: false,
useTransform: false,
percentage: false,
isEqualSize: false,
isConstantSize: false,
gap: 0,
attributePrefix: "data-grid-",
resizeDebounce: 100,
maxResizeDebounce: 0,
autoResize: true,
preserveUIOnDestroy: false,
defaultDirection: "end",
externalContainerManager: null,
externalItemRenderer: null,
renderOnPropertyChange: true,
useFit: true,
outlineLength: 0,
outlineSize: 0,
useRoundedSize: true,
useResizeObserver: false
};
var PROPERTY_TYPE;
(function (PROPERTY_TYPE) {
PROPERTY_TYPE[PROPERTY_TYPE["PROPERTY"] = 1] = "PROPERTY";
PROPERTY_TYPE[PROPERTY_TYPE["RENDER_PROPERTY"] = 2] = "RENDER_PROPERTY";
})(PROPERTY_TYPE || (PROPERTY_TYPE = {}));
var MOUNT_STATE;
(function (MOUNT_STATE) {
MOUNT_STATE[MOUNT_STATE["UNCHECKED"] = 1] = "UNCHECKED";
MOUNT_STATE[MOUNT_STATE["UNMOUNTED"] = 2] = "UNMOUNTED";
MOUNT_STATE[MOUNT_STATE["MOUNTED"] = 3] = "MOUNTED";
})(MOUNT_STATE || (MOUNT_STATE = {}));
var UPDATE_STATE;
(function (UPDATE_STATE) {
UPDATE_STATE[UPDATE_STATE["NEED_UPDATE"] = 1] = "NEED_UPDATE";
UPDATE_STATE[UPDATE_STATE["WAIT_LOADING"] = 2] = "WAIT_LOADING";
UPDATE_STATE[UPDATE_STATE["UPDATED"] = 3] = "UPDATED";
})(UPDATE_STATE || (UPDATE_STATE = {}));
var GRID_PROPERTY_TYPES = {
gap: PROPERTY_TYPE.RENDER_PROPERTY,
defaultDirection: PROPERTY_TYPE.PROPERTY,
renderOnPropertyChange: PROPERTY_TYPE.PROPERTY,
preserveUIOnDestroy: PROPERTY_TYPE.PROPERTY,
useFit: PROPERTY_TYPE.PROPERTY,
outlineSize: PROPERTY_TYPE.RENDER_PROPERTY,
outlineLength: PROPERTY_TYPE.RENDER_PROPERTY
};
var RECT_NAMES = {
horizontal: {
inlinePos: "top",
contentPos: "left",
inlineSize: "height",
contentSize: "width"
},
vertical: {
inlinePos: "left",
contentPos: "top",
inlineSize: "width",
contentSize: "height"
}
};
var ContainerManager =
/*#__PURE__*/
function (_super) {
__extends$2(ContainerManager, _super);
function ContainerManager(container, options) {
var _this = _super.call(this) || this;
_this.container = container;
_this._onResize = function () {
_this.trigger("resize");
};
_this.options = __assign$2({
horizontal: DEFAULT_GRID_OPTIONS.horizontal,
autoResize: DEFAULT_GRID_OPTIONS.autoResize,
resizeDebounce: DEFAULT_GRID_OPTIONS.resizeDebounce,
maxResizeDebounce: DEFAULT_GRID_OPTIONS.maxResizeDebounce,
useResizeObserver: DEFAULT_GRID_OPTIONS.useResizeObserver
}, options);
_this._init();
return _this;
}
var __proto = ContainerManager.prototype;
__proto.resize = function () {
var container = this.container;
this.setRect({
width: container.clientWidth,
height: container.clientHeight
});
};
__proto.getRect = function () {
return this._watcher.getRect();
};
__proto.setRect = function (rect) {
this._watcher.setRect(rect);
};
__proto.getInlineSize = function () {
return this.getRect()[this._names.inlineSize];
};
__proto.getContentSize = function () {
return this.getRect()[this._names.contentSize];
};
__proto.getStatus = function () {
return {
rect: this._watcher.getRect()
};
};
__proto.setStatus = function (status) {
this.setRect(status.rect);
this.setContentSize(this.getContentSize());
};
__proto.setContentSize = function (size) {
var _a;
var sizeName = this.options.horizontal ? "width" : "height";
this.setRect(__assign$2(__assign$2({}, this.getRect()), (_a = {}, _a[sizeName] = size, _a)));
this.container.style[sizeName] = size + "px";
};
__proto.destroy = function (options) {
if (options === void 0) {
options = {};
}
this._watcher.destroy();
if (!options.preserveUI) {
this.container.style.cssText = this.orgCSSText;
}
};
__proto._init = function () {
var container = this.container;
var style = window.getComputedStyle(container);
this.orgCSSText = container.style.cssText;
if (style.position === "static") {
container.style.position = "relative";
}
var options = this.options;
this._watcher = new ResizeWatcher(container, {
useWindowResize: options.autoResize,
useResizeObserver: options.useResizeObserver,
resizeDebounce: options.resizeDebounce,
maxResizeDebounce: options.maxResizeDebounce,
watchDirection: options.useResizeObserver ? this._names.inlineSize : false
}).listen(this._onResize);
};
Object.defineProperty(__proto, "_names", {
get: function () {
return RECT_NAMES[this.options.horizontal ? "horizontal" : "vertical"];
},
enumerable: false,
configurable: true
});
return ContainerManager;
}(Component);
function getKeys(obj) {
return Object.keys(obj);
}
function isString(val) {
return typeof val === "string";
}
function isObject(val) {
return typeof val === "object";
}
function isNumber(val) {
return typeof val === "number";
}
function camelize(str) {
return str.replace(/[\s-_]([a-z])/g, function (all, letter) {
return letter.toUpperCase();
});
}
function getDataAttributes(element, attributePrefix) {
var dataAttributes = {};
var attributes = element.attributes;
var length = attributes.length;
for (var i = 0; i < length; ++i) {
var attribute = attributes[i];
var name = attribute.name,
value = attribute.value;
if (name.indexOf(attributePrefix) === -1) {
continue;
}
dataAttributes[camelize(name.replace(attributePrefix, ""))] = value;
}
return dataAttributes;
}
/* Class Decorator */
function GetterSetter(component) {
var prototype = component.prototype,
propertyTypes = component.propertyTypes;
var _loop_1 = function (name) {
var shouldRender = propertyTypes[name] === PROPERTY_TYPE.RENDER_PROPERTY;
var descriptor = Object.getOwnPropertyDescriptor(prototype, name) || {};
var getter = descriptor.get || function get() {
return this.options[name];
};
var setter = descriptor.set || function set(value) {
var options = this.options;
var prevValue = options[name];
if (prevValue === value) {
return;
}
options[name] = value;
if (shouldRender && options.renderOnPropertyChange) {
this.scheduleRender();
}
};
var attributes = {
enumerable: true,
configurable: true,
get: getter,
set: setter
};
Object.defineProperty(prototype, name, attributes);
};
for (var name in propertyTypes) {
_loop_1(name);
}
}
function withMethods(methods) {
return function (prototype, memberName) {
methods.forEach(function (name) {
if (name in prototype) {
return;
}
prototype[name] = function () {
var _a;
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
var result = (_a = this[memberName])[name].apply(_a, args); // fix `this` type to return your own `class` instance to the instance using the decorator.
if (result === this[memberName]) {
return this;
} else {
return result;
}
};
});
};
}
function range(length) {
var arr = [];
for (var i = 0; i < length; ++i) {
arr.push(i);
}
return arr;
}
function getRangeCost(value, valueRange) {
return Math.max(value - valueRange[1], valueRange[0] - value, 0) + 1;
}
var ItemRenderer =
/*#__PURE__*/
function () {
function ItemRenderer(options) {
this.initialRect = null;
this.sizePercetage = false;
this.posPercetage = false;
this.options = __assign$2({
attributePrefix: DEFAULT_GRID_OPTIONS.attributePrefix,
useTransform: DEFAULT_GRID_OPTIONS.useTransform,
horizontal: DEFAULT_GRID_OPTIONS.horizontal,
percentage: DEFAULT_GRID_OPTIONS.percentage,
isEqualSize: DEFAULT_GRID_OPTIONS.isEqualSize,
isConstantSize: DEFAULT_GRID_OPTIONS.isConstantSize,
useRoundedSize: DEFAULT_GRID_OPTIONS.useRoundedSize
}, options);
this._init();
}
var __proto = ItemRenderer.prototype;
__proto.resize = function () {
this.initialRect = null;
};
__proto.renderItems = function (items) {
var _this = this;
items.forEach(function (item) {
_this._renderItem(item);
});
};
__proto.getInlineSize = function () {
return this.containerRect[this.options.horizontal ? "height" : "width"];
};
__proto.setContainerRect = function (rect) {
this.containerRect = rect;
};
__proto.updateItems = function (items) {
var _this = this;
items.forEach(function (item) {
_this._updateItem(item);
});
};
__proto.getStatus = function () {
return {
initialRect: this.initialRect
};
};
__proto.setStatus = function (status) {
this.initialRect = status.initialRect;
};
__proto._init = function () {
var percentage = this.options.percentage;
var sizePercentage = false;
var posPercentage = false;
if (percentage === true) {
sizePercentage = true;
posPercentage = true;
} else if (percentage) {
if (percentage.indexOf("position") > -1) {
posPercentage = true;
}
if (percentage.indexOf("size") > -1) {
sizePercentage = true;
}
}
this.posPercetage = posPercentage;
this.sizePercetage = sizePercentage;
};
__proto._updateItem = function (item) {
var _a = this.options,
isEqualSize = _a.isEqualSize,
isConstantSize = _a.isConstantSize,
useRoundedSize = _a.useRoundedSize;
var initialRect = this.initialRect;
var orgRect = item.orgRect,
element = item.element;
var isLoading = item.updateState === UPDATE_STATE.WAIT_LOADING;
var hasOrgSize = orgRect && orgRect.width && orgRect.height;
var rect;
if (isEqualSize && initialRect) {
rect = initialRect;
} else if (isConstantSize && hasOrgSize && !isLoading) {
rect = orgRect;
} else if (!element) {
return;
} else {
rect = {
left: element.offsetLeft,
top: element.offsetTop,
width: 0,
height: 0
};
if (useRoundedSize) {
rect.width = element.offsetWidth;
rect.height = element.offsetHeight;
} else {
var clientRect = element.getBoundingClientRect();
rect.width = clientRect.width;
rect.height = clientRect.height;
}
}
if (!item.isFirstUpdate || !hasOrgSize) {
item.orgRect = __assign$2({}, rect);
}
item.rect = __assign$2({}, rect);
if (item.element) {
item.mountState = MOUNT_STATE.MOUNTED;
}
if (item.updateState === UPDATE_STATE.NEED_UPDATE) {
item.updateState = UPDATE_STATE.UPDATED;
item.isFirstUpdate = true;
}
item.attributes = element ? getDataAttributes(element, this.options.attributePrefix) : {};
if (!isLoading) {
this.initialRect = __assign$2({}, rect);
}
return rect;
};
__proto._renderItem = function (item) {
var element = item.element;
var cssRect = item.cssRect;
if (!element || !cssRect) {
return;
}
var _a = this.options,
horizontal = _a.horizontal,
useTransform = _a.useTransform;
var posPercentage = this.posPercetage;
var sizePercentage = this.sizePercetage;
var cssTexts = ["position: absolute;"];
var _b = RECT_NAMES[horizontal ? "horizontal" : "vertical"],
sizeName = _b.inlineSize,
posName = _b.inlinePos;
var inlineSize = this.getInlineSize();
var keys = getKeys(cssRect);
if (useTransform) {
keys = keys.filter(function (key) {
return key !== "top" && key !== "left";
});
cssTexts.push("transform: " + ("translate(" + (cssRect.left || 0) + "px, " + (cssRect.top || 0) + "px);"));
}
cssTexts.push.apply(cssTexts, keys.map(function (name) {
var value = cssRect[name];
if (name === sizeName && sizePercentage || name === posName && posPercentage) {
return name + ": " + value / inlineSize * 100 + "%;";
}
return name + ": " + value + "px;";
}));
element.style.cssText += cssTexts.join("");
};
return ItemRenderer;
}();
/**
* @memberof Grid
* @implements Grid.GridItem.GridItemStatus
*/
var GridItem =
/*#__PURE__*/
function () {
/**
* @constructor
* @param horizontal - Direction of the scroll movement. (true: horizontal, false: vertical) <ko>스크롤 이동 방향. (true: 가로방향, false: 세로방향)</ko>
* @param itemStatus - Default status object of GridItem module. <ko>GridItem 모듈의 기본 status 객체.</ko>
*/
function GridItem(horizontal, itemStatus) {
if (itemStatus === void 0) {
itemStatus = {};
}
var _a;
this.horizontal = horizontal;
this.isUpdate = false;
this.hasTransition = false;
this.transitionDuration = "";
var element = itemStatus.element;
var status = __assign$2({
key: "",
orgRect: {
left: 0,
top: 0,
width: 0,
height: 0
},
rect: {
left: 0,
top: 0,
width: 0,
height: 0
},
cssRect: {},
attributes: {},
data: {},
isFirstUpdate: false,
mountState: MOUNT_STATE.UNCHECKED,
updateState: UPDATE_STATE.NEED_UPDATE,
element: element || null,
orgCSSText: (_a = element === null || element === void 0 ? void 0 : element.style.cssText) !== null && _a !== void 0 ? _a : "",
gridData: {}
}, itemStatus);
for (var name in status) {
this[name] = status[name];
}
}
var __proto = GridItem.prototype;
Object.defineProperty(__proto, "orgInlineSize", {
/**
* The size in inline direction before first rendering. "width" if horizontal is false, "height" otherwise.
* @ko 첫 렌더링 되기 전의 inline 방향의 사이즈. horizontal이 false면 "width", 아니면 "height".
* @member Grid.GridItem#orgInlineSize
*/
get: function () {
var name = this._names.inlineSize;
return this.orgRect[name] || this.rect[name];
},
enumerable: false,
configurable: true
});
Object.defineProperty(__proto, "orgContentSize", {
/**
* The size in content direction before first rendering. "height" if horizontal is false, "width" otherwise.
* @ko 첫 렌더링 되기 전의 content 방향의 사이즈. horizontal이 false면 "height", 아니면 "width".
* @member Grid.GridItem#orgContentSize
*/
get: function () {
var name = this._names.contentSize;
return this.orgRect[name] || this.rect[name];
},
enumerable: false,
configurable: true
});
Object.defineProperty(__proto, "inlineSize", {
/**
* The size in inline direction. "width" if horizontal is false, "height" otherwise.
* @ko inline 방향의 사이즈. horizontal이 false면 "width", 아니면 "height".
* @member Grid.GridItem#inlineSize
*/
get: function () {
return this.rect[this._names.inlineSize];
},
enumerable: false,
configurable: true
});
Object.defineProperty(__proto, "contentSize", {
/**
* The size in content direction. "height" if horizontal is false, "width" otherwise.
* @ko content 방향의 사이즈. horizontal이 false면 "height", 아니면 "width".
* @member Grid.GridItem#contentSize
*/
get: function () {
return this.rect[this._names.contentSize];
},
enumerable: false,
configurable: true
});
Object.defineProperty(__proto, "cssInlineSize", {
/**
* The CSS size in inline direction applied to the Grid. "width" if horizontal is false, "height" otherwise.
* @ko Grid에 적용된 inline 방향의 CSS 사이즈. horizontal이 false면 "width", 아니면 "height".
* @member Grid.GridItem#cssInlineSize
*/
get: function () {
return this.cssRect[this._names.inlineSize];
},
set: function (inlineSize) {
this.cssRect[this._names.inlineSize] = inlineSize;
},
enumerable: false,
configurable: true
});
Object.defineProperty(__proto, "cssContentSize", {
/**
* The CSS size in content direction applied to the Grid. "height" if horizontal is false, "width" otherwise.
* @ko Grid에 적용된 content 방향의 CSS 사이즈. horizontal이 false면 "height", 아니면 "width".
* @member Grid.GridItem#cssContentSize
*/
get: function () {
return this.cssRect[this._names.contentSize];
},
set: function (contentSize) {
this.cssRect[this._names.contentSize] = contentSize;
},
enumerable: false,
configurable: true
});
Object.defineProperty(__proto, "cssInlinePos", {
/**
* The CSS pos in inline direction applied to the Grid. "left" if horizontal is false, "top" otherwise.
* @ko Grid에 적용된 inline 방향의 CSS 포지션. horizontal이 false면 "left", 아니면 "top".
* @member Grid.GridItem#cssInlinePos
*/
get: function () {
return this.cssRect[this._names.inlinePos];
},
set: function (inlinePos) {
this.cssRect[this._names.inlinePos] = inlinePos;
},
enumerable: false,
configurable: true
});
Object.defineProperty(__proto, "cssContentPos", {
/**
* The CSS pos in content direction applied to the Grid. "top" if horizontal is false, "left" otherwise.
* @ko Grid에 적용된 content 방향의 CSS 포지션. horizontal이 false면 "top", 아니면 "left".
* @member Grid.GridItem#cssContentPos
*/
get: function () {
return this.cssRect[this._names.contentPos];
},
set: function (contentPos) {
this.cssRect[this._names.contentPos] = contentPos;
},
enumerable: false,
configurable: true
});
Object.defineProperty(__proto, "computedInlineSize", {
/**
* Calculated size in the direction of the inline applied to the grid. "width" if horizontal is false, "height" otherwise.
* @ko Grid에 적용된 inline 방향의 계산된 사이즈. horizontal이 false면 "width", 아니면 "height".
* @member Grid.GridItem#computedInlineSize
*/
get: function () {
var name = this._names.inlineSize;
return this.cssRect[name] || this.rect[name] || this.orgRect[name];
},
enumerable: false,
configurable: true
});
Object.defineProperty(__proto, "computedContentSize", {
/**
* Calculated size in the direction of the content applied to the grid. "height" if horizontal is false, "width" otherwise.
* @ko Grid에 적용된 content 방향의 계산된 사이즈. horizontal이 false면 "height", 아니면 "width".
* @member Grid.GridItem#computedContentSize
*/
get: function () {
var name = this._names.contentSize;
return this.cssRect[name] || this.rect[name] || this.orgRect[name];
},
enumerable: false,
configurable: true
});
Object.defineProperty(__proto, "computedInlinePos", {
/**
* Calculated position in the direction of the inline applied to the grid. "left" if horizontal is false, "top" otherwise.
* @ko Grid에 적용된 content 방향의 계산된 포지션. horizontal이 false면 "left", 아니면 "top".
* @member Grid.GridItem#computedInlinePos
*/
get: function () {
var _a;
var name = this._names.inlinePos;
return (_a = this.cssRect[name]) !== null && _a !== void 0 ? _a : this.rect[name];
},
enumerable: false,
configurable: true
});
Object.defineProperty(__proto, "computedContentPos", {
/**
* Calculated position in the direction of the content applied to the grid. "top" if horizontal is false, "left" otherwise.
* @ko Grid에 적용된 content 방향의 계산된 포지션. horizontal이 false면 "top", 아니면 "left".
* @member Grid.GridItem#computedContentPos
*/
get: function () {
var _a;
var name = this._names.contentPos;
return (_a = this.cssRect[name]) !== null && _a !== void 0 ? _a : this.rect[name];
},
enumerable: false,
configurable: true
});
/**
* Set CSS Rect through GridRect.
* @ko GridRect을 통해 CSS Rect를 설정한다.
* @param - The style for setting CSS rect. <ko>CSS rect를 설정하기 위한 스타일.</ko>
*/
__proto.setCSSGridRect = function (gridRect) {
var names = RECT_NAMES[this.horizontal ? "horizontal" : "vertical"];
var rect = {};
for (var name in gridRect) {
rect[names[name]] = gridRect[name];
}
this.cssRect = rect;
};
/**
* Returns the status of the item.
* @ko 아이템의 상태를 반환한다.
*/
__proto.getStatus = function () {
return {
mountState: this.mountState,
updateState: this.updateState,
attributes: this.attributes,
orgCSSText: this.orgCSSText,
isFirstUpdate: this.isFirstUpdate,
element: null,
key: this.key,
orgRect: this.orgRect,
rect: this.rect,
cssRect: this.cssRect,
gridData: this.gridData,
data: this.data
};
};
/**
* Returns minimized status of the item.
* @ko 아이템의 간소화된 상태를 반환한다.
*/
__proto.getMinimizedStatus = function () {
var status = {
orgRect: this.orgRect,
rect: this.rect,
cssRect: this.cssRect,
attributes: this.attributes,
gridData: this.gridData
};
var _a = this,
key = _a.key,
mountState = _a.mountState,
updateState = _a.updateState,
isFirstUpdate = _a.isFirstUpdate,
orgCSSText = _a.orgCSSText;
if (typeof key !== "undefined") {
status.key = key;
}
if (mountState !== MOUNT_STATE.UNCHECKED) {
status.mountState = mountState;
}
if (updateState !== UPDATE_STATE.NEED_UPDATE) {
status.updateState = updateState;
}
if (isFirstUpdate) {
status.isFirstUpdate = true;
}
if (orgCSSText) {
status.orgCSSText = orgCSSText;
}
return status;
};
Object.defineProperty(__proto, "_names", {
get: function () {
return this.horizontal ? RECT_NAMES.horizontal : RECT_NAMES.vertical;
},
enumerable: false,
configurable: true
});
return GridItem;
}();
/**
* @extends eg.Component
*/
var Grid =
/*#__PURE__*/
function (_super) {
__extends$2(Grid, _super);
/**
* @param - A base element for a module <ko>모듈을 적용할 기준 엘리먼트</ko>
* @param - The option object of the Grid module <ko>Grid 모듈의 옵션 객체</ko>
*/
function Grid(containerElement, options) {
if (options === void 0) {
options = {};
}
var _this = _super.call(this) || this;
_this.items = [];
_this.outlines = {
start: [],
end: []
};
_this._renderTimer = 0;
_this._onResize = function () {
_this._renderItems({
useResize: true
}, true);
};
_this.options = __assign$2(__assign$2({}, _this.constructor.defaultOptions), options);
_this.containerElement = isString(containerElement) ? document.querySelector(containerElement) : containerElement;
var _a = _this.options,
isEqualSize = _a.isEqualSize,
isConstantSize = _a.isConstantSize,
useTransform = _a.useTransform,
horizontal = _a.horizontal,
percentage = _a.percentage,
externalContainerManager = _a.externalContainerManager,
externalItemRenderer = _a.externalItemRenderer,
resizeDebounce = _a.resizeDebounce,
maxResizeDebounce = _a.maxResizeDebounce,
autoResize = _a.autoResize,
useRoundedSize = _a.useRoundedSize,
useResizeObserver = _a.useResizeObserver; // TODO: 테스트용 설정
_this.containerManager = externalContainerManager || new ContainerManager(_this.containerElement, {
horizontal: horizontal,
resizeDebounce: resizeDebounce,
maxResizeDebounce: maxResizeDebounce,
autoResize: autoResize,
useResizeObserver: useResizeObserver
}).on("resize", _this._onResize);
_this.itemRenderer = externalItemRenderer || new ItemRenderer({
useTransform: useTransform,
isEqualSize: isEqualSize,
isConstantSize: isConstantSize,
percentage: percentage,
useRoundedSize: useRoundedSize
});
_this._init();
return _this;
}
var __proto = Grid.prototype;
Grid_1 = Grid;
/**
* Return Container Element.
* @ko 컨테이너 엘리먼트를 반환한다.
*/
__proto.getContainerElement = function () {
return this.containerElement;
};
/**
* Return items.
* @ko 아이템들을 반환한다.
*/
__proto.getItems = function () {
return this.items;
};
/**
* Returns the children of the container element.
* @ko 컨테이너 엘리먼트의 children을 반환한다.
*/
__proto.getChildren = function () {
return [].slice.call(this.containerElement.children);
};
/**
* Set items.
* @ko 아이템들을 설정한다.
* @param items - The items to set. <ko>설정할 아이템들</ko>
*/
__proto.setItems = function (items) {
this.items = items;
return this;
};
/**
* Gets the container's inline size. ("width" if horizontal is false, otherwise "height")
* @ko container의 inline 사이즈를 가져온다. (horizontal이 false면 "width", 아니면 "height")
*/
__proto.getContainerInlineSize = function () {
return this.containerManager.getInlineSize();
};
/**
* Returns the outlines of the start and end of the Grid.
* @ko Grid의 처음과 끝의 outline을 반환한다.
*/
__proto.getOutlines = function () {
return this.outlines;
};
/**
* Set outlines.
* @ko 아웃라인을 설정한다.
* @param outlines - The outlines to set. <ko>설정할 아웃라인.</ko>
*/
__proto.setOutlines = function (outlines) {
this.outlines = outlines;
return this;
};
/**
* When elements change, it synchronizes and renders items.
* @ko elements가 바뀐 경우 동기화를 하고 렌더링을 한다.
* @param - Options for rendering. <ko>렌더링을 하기 위한 옵션.</ko>
*/
__proto.syncElements = function (options) {
if (options === void 0) {
options = {};
}
var items = this.items;
var horizontal = this.options.horizontal;
var elements = this.getChildren();
var _a = diff$1(this.items.map(function (item) {
return item.element;
}), elements),
added = _a.added,
maintained = _a.maintained,
changed = _a.changed,
removed = _a.removed;
var nextItems = [];
maintained.forEach(function (_a) {
var beforeIndex = _a[0],
afterIndex = _a[1];
nextItems[afterIndex] = items[beforeIndex];
});
added.forEach(function (index) {
nextItems[index] = new GridItem(horizontal, {
element: elements[index]
});
});
this.setItems(nextItems);
if (added.length || removed.length || changed.length) {
this.renderItems(options);
}
return this;
};
/**
* Update the size of the items and render them.
* @ko 아이템들의 사이즈를 업데이트하고 렌더링을 한다.
* @param - Items to be updated. <ko>업데이트할 아이템들.</ko>
* @param - Options for rendering. <ko>렌더링을 하기 위한 옵션.</ko>
*/
__proto.updateItems = function (items, options) {
if (items === void 0) {
items = this.items;
}
if (options === void 0) {
options = {};
}
var useOrgResize = options.useOrgResize;
items.forEach(function (item) {
if (useOrgResize) {
var orgRect = item.orgRect;
orgRect.width = 0;
orgRect.height = 0;
}
item.updateState = UPDATE_STATE.NEED_UPDATE;
});
this.checkReady(options);
return this;
};
/**
* Rearrange items to fit the grid and render them. When rearrange is complete, the `renderComplete` event is fired.
* @ko grid에 맞게 아이템을 재배치하고 렌더링을 한다. 배치가 완료되면 `renderComplete` 이벤트가 발생한다.
* @param - Options for rendering. <ko>렌더링을 하기 위한 옵션.</ko>
* @example
* ```js
* import { MasonryGrid } from "@egjs/grid";
* const grid = new MasonryGrid();
*
* grid.on("renderComplete", e => {
* console.log(e);
* });
* grid.renderItems();
* ```
*/
__proto.renderItems = function (options) {
if (options === void 0) {
options = {};
}
this._renderItems(options);
return this;
};
/**
* Returns current status such as item's position, size. The returned status can be restored with the setStatus() method.
* @ko 아이템의 위치, 사이즈 등 현재 상태를 반환한다. 반환한 상태는 setStatus() 메서드로 복원할 수 있다.
* @param - Whether to minimize the status of the item. (default: false) <ko>item의 status를 최소화할지 여부. (default: false)</ko>
*/
__proto.getStatus = function (minimize) {
return {
outlines: this.outlines,
items: this.items.map(function (item) {
return minimize ? item.getMinimizedStatus() : item.getStatus();
}),
containerManager: this.containerManager.getStatus(),
itemRenderer: this.itemRenderer.getStatus()
};
};
/**
* Set status of the Grid module with the status returned through a call to the getStatus() method.
* @ko getStatus() 메서드에 대한 호출을 통해 반환된 상태로 Grid 모듈의 상태를 설정한다.
*/
__proto.setStatus = function (status) {
var _this = this;
var horizontal = this.options.horizontal;
var containerManager = this.containerManager;
var prevInlineSize = containerManager.getInlineSize();
var children = this.getChildren();
this.itemRenderer.setStatus(status.itemRenderer);
containerManager.setStatus(status.containerManager);
this.outlines = status.outlines;
this.items = status.items.map(function (item, i) {
return new GridItem(horizontal, __assign$2(__assign$2({}, item), {
element: children[i]
}));
});
this.itemRenderer.renderItems(this.items);
if (prevInlineSize !== containerManager.getInlineSize()) {
this.renderItems({
useResize: true
});
} else {
window.setTimeout(function () {
_this._renderComplete({
direction: _this.defaultDirection,
mounted: _this.items,
updated: [],
isResize: false
});
});
}
return this;
};
/**
* Get the inline size corresponding to outline.
* @ko outline에 해당하는 inline 사이즈를 구한다.
* @param items - Items to get outline size. <ko>outline 사이즈를 구하기 위한 아이템들.</ko>
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
__proto.getComputedOutlineSize = function (items) {
if (items === void 0) {
items = this.items;
}
return this.options.outlineSize || this.getContainerInlineSize();
};
/**
* Get the length corresponding to outline.
* @ko outline에 해당하는 length를 가져온다.
* @param items - Items to get outline length. <ko>outline length를 구하기 위한 아이템들.</ko>
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
__proto.getComputedOutlineLength = function (items) {
if (items === void 0) {
items = this.items;
}
return this.options.outlineLength || 1;
};
/**
* Releases the instnace and events and returns the CSS of the container and elements.
* @ko 인스턴스와 이벤트를 해제하고 컨테이너와 엘리먼트들의 CSS를 되돌린다.
* @param Options for destroy. <ko>destory()를 위한 옵션</ko>
*/
__proto.destroy = function (options) {
var _a;
if (options === void 0) {
options = {};
}
var _b = options.preserveUI,
preserveUI = _b === void 0 ? this.options.preserveUIOnDestroy : _b;
this.containerManager.destroy({
preserveUI: preserveUI
});
if (!preserveUI) {
this.items.forEach(function (_a) {
var element = _a.element,
orgCSSText = _a.orgCSSText;
if (element) {
element.style.cssText = orgCSSText;
}
});
}
(_a = this._im) === null || _a === void 0 ? void 0 : _a.destroy();
};
__proto.checkReady = function (options) {
var _this = this;
var _a;
if (options === void 0) {
options = {};
} // Grid: renderItems => checkReady => readyItems => applyGrid
var items = this.items;
var updated = items.filter(function (item) {
var _a;
return ((_a = item.element) === null || _a === void 0 ? void 0 : _a.parentNode) && item.updateState !== UPDATE_STATE.UPDATED;
});
var mounted = updated.filter(function (item) {
return item.mountState !== MOUNT_STATE.MOUNTED;
});
var moreUpdated = [];
mounted.filter(function (item) {
if (item.hasTransition) {
return true;
} else {
var element = item.element;
var transitionDuration = parseFloat(getComputedStyle(element).transitionDuration);
if (transitionDuration > 0) {
item.hasTransition = true;
item.transitionDuration = element.style.transitionDuration;
return true;
}
}
return false;
}).forEach(function (item) {
item.element.style.transitionDuration = "0s";
});
(_a = this._im) === null || _a === void 0 ? void 0 : _a.destroy();
this._im = new ImReady({
prefix: this.options.attributePrefix
}).on("preReadyElement", function (e) {
updated[e.index].updateState = UPDATE_STATE.WAIT_LOADING;
}).on("preReady", function () {
// reset org size
updated.forEach(function (item) {
var hasOrgSize = item.orgRect.width && item.orgRect.height;
var hasCSSSize = item.cssRect.width || item.cssRect.height;
if (!hasOrgSize && hasCSSSize) {
item.element.style.cssText = item.orgCSSText;
}
});
_this.itemRenderer.updateItems(updated);
_this.readyItems(mounted, updated, options);
}).on("readyElement", function (e) {
var item = updated[e.index];
item.updateState = UPDATE_STATE.NEED_UPDATE; // after preReady
if (e.isPreReadyOver) {
item.element.style.cssText = item.orgCSSText;
_this.itemRenderer.updateItems([item]);
_this.readyItems([], [item], options);
}
}).on("error", function (e) {
var item = items[e.index];
/**
* This event is fired when an error occurs in the content.
* @ko 콘텐츠 로드에 에러가 날 때 발생하는 이벤트.
* @event Grid#contentError
* @param {Grid.OnContentError} e - The object of data to be sent to an event <ko>이벤트에 전달되는 데이터 객체</ko>
* @example
* ```js
* grid.on("contentError", e => {
* e.update();
* });
* ```
*/
_this.trigger("contentError", {
element: e.element,
target: e.target,
item: item,
update: function () {
moreUpdated.push(item);
}
});
}).on("ready", function () {
if (moreUpdated.length) {
_this.updateItems(moreUpdated);
}
}).check(updated.map(function (item) {
return item.element;
}));
};
__proto.scheduleRender = function () {
var _this = this;
this._clearRenderTimer();
this._renderTimer = window.setTimeout(function () {
_this.renderItems();
});
};
__proto.fitOutlines = function (useFit) {
if (useFit === void 0) {
useFit = this.useFit;
}
var outlines = this.outlines;
var startOutline = outlines.start;
var endOutline = outlines.end;
var outlineOffset = startOutline.length ? Math.min.apply(Math, startOutline) : 0; // If the outline is less than 0, a fit occurs forcibly.
if (!useFit && outlineOffset > 0) {
return;
}
outlines.start = startOutline.map(function (point) {
return point - outlineOffset;
});
outlines.end = endOutline.map(function (point) {
return point - outlineOffset;
});
this.items.forEach(function (item) {
var contentPos = item.cssContentPos;
if (!isNumber(contentPos)) {
return;
}
item.cssContentPos = contentPos - outlineOffset;
});
};
__proto.readyItems = function (mounted, updated, options) {
var prevOutlines = this.outlines;
var direction = options.direction || this.options.defaultDirection;
var prevOutline = options.outline || prevOutlines[direction === "end" ? "start" : "end"];
var items = this.items;
var nextOutlines = {
start: __spreadArray([], prevOutline),
end: __spreadArray([], prevOutline)
};
updated.forEach(function (item) {
item.isUpdate = true;
});
if (items.length) {
nextOutlines = this.applyGrid(this.items, direction, prevOutline);
}
updated.forEach(function (item) {
item.isUpdate = false;
});
this.setOutlines(nextOutlines);
this.fitOutlines();
this.itemRenderer.renderItems(this.items);
this._refreshContainerContentSize();
var transitionMounted = mounted.filter(function (item) {
return item.hasTransition;
});
if (transitionMounted.length) {
this.containerManager.resize();
transitionMounted.forEach(function (item) {
var element = item.element;
element.style.transitionDuration = item.transitionDuration;
});
}
this._renderComplete({
direction: direction,
mounted: mounted,
updated: updated,
isResize: !!options.useResize
});
};
__proto._renderComplete = function (e) {
/**
* This event is fired when the Grid has completed rendering.
* @ko Grid가 렌더링이 완료됐을 때 발생하는 이벤트이다.
* @event Grid#renderComplete
* @param {Grid.OnRenderComplete} e - The object of data to be sent to an event <ko>이벤트에 전달되는 데이터 객체</ko>
* @example
* ```js
* grid.on("renderComplete", e => {
* console.log(e.mounted, e.updated, e.useResize);
* });
* ```
*/
this.trigger("renderComplete", e);
};
__proto._clearRenderTimer = function () {
clearTimeout(this._renderTimer);
this._renderTimer = 0;
};
__proto._refreshContainerContentSize = function () {
var _a = this.outlines,
startOutline = _a.start,
endOutline = _a.end;
var gap = this.options.gap;
var endPoint = endOutline.length ? Math.max.apply(Math, endOutline) : 0;
var startPoint = startOutline.length ? Math.max.apply(Math, startOutline) : 0;
var contentSize = Math.max(startPoint, endPoint - gap);
this.containerManager.setContentSize(contentSize);
};
__proto._resizeContainer = function () {
this.containerManager.resize();
this.itemRenderer.setContainerRect(this.containerManager.getRect());
};
__proto._init = function () {
this._resizeContainer();
};
__proto._renderItems = function (options, isTrusted) {
if (options === void 0) {
options = {};
}
this._clearRenderTimer();
var isResize = options.useResize || options.useOrgResize;
if (isResize && !isTrusted) {
// Resize container
// isTrusted has already been resized internally.
this._resizeContainer();
}
if (!this.getItems().length && this.getChildren().length) {
this.syncElements(options);
} else if (isResize) {
// Update all items
this.updateItems(this.items, options);
} else {
// Update only items that need to be updated.
this.checkReady(options);
}
};
var Grid_1;
Grid.defaultOptions = DEFAULT_GRID_OPTIONS;
Grid.propertyTypes = GRID_PROPERTY_TYPES;
Grid = Grid_1 = __decorate$1([GetterSetter], Grid);
return Grid;
}(Component);
/**
* Gap used to create space around items.
* @ko 아이템들 사이의 공간.
* @name Grid#gap
* @type {$ts:Grid.GridOptions["gap"]}
* @default 0
* @example
* ```js
* import { MasonryGrid } from "@egjs/grid";
*
* const grid = new MasonryGrid(container, {
* gap: 0,
* });
*
* grid.gap = 5;
* ```
*/
/**
* The default direction value when direction is not set in the render option.
* @ko render옵션에서 direction을 미설정시의 기본 방향값.
* @name Grid#defaultDirection
* @type {$ts:Grid.GridOptions["defaultDirection"]}
* @default "end"
* @example
* ```js
* import { MasonryGrid } from "@egjs/grid";
*
* const grid = new MasonryGrid(container, {
* defaultDirection: "end",
* });
*
* grid.defaultDirection = "start";
* ```
*/
/**
* Whether to move the outline to 0 when the top is empty when rendering. However, if it overflows above the top, the outline is forced to 0. (default: true)
* @ko 렌더링시 상단이 비어있을 때 아웃라인을 0으로 이동시킬지 여부. 하지만 상단보다 넘치는 경우 아웃라인을 0으로 강제 이동한다. (default: true)
* @name Grid#useFit
* @type {$ts:Grid.GridOptions["useFit"]}
* @default true
* @example
* ```js
* import { MasonryGrid } from "@egjs/grid";
*
* const grid = new MasonryGrid(container, {
* useFit: true,
* });
*
* grid.useFit = false;
* ```
*/
/**
* Whether to preserve the UI of the existing container or item when destroying.
* @ko destroy 시 기존 컨테이너, 아이템의 UI를 보존할지 여부.
* @name Grid#preserveUIOnDestroy
* @type {$ts:Grid.GridOptions["preserveUIOnDestroy"]}
* @default false
* @example
* ```js
* import { MasonryGrid } from "@egjs/grid";
*
* const grid = new MasonryGrid(container, {
* preserveUIOnDestroy: false,
* });
*
* grid.preserveUIOnDestroy = true;
* ```
*/
/**
* The number of outlines. If the number of outlines is 0, it is calculated according to the type of grid.
* @ko outline의 개수. 아웃라인의 개수가 0이라면 grid의 종류에 따라 계산이 된다.
* @name Grid#outlineLength
* @type {$ts:Grid.GridOptions["outlineLength"]}
* @default 0
* @example
* ```js
* import { MasonryGrid } from "@egjs/grid";
*
* const grid = new MasonryGrid(container, {
* outlineLength: 0,
* outlineSize: 0,
* });
*
* grid.outlineLength = 3;
* ```
*/
/**
* The size of the outline. If the outline size is 0, it is calculated according to the grid type.
* @ko outline의 사이즈. 만약 outline의 사이즈가 0이면, grid의 종류에 따라 계산이 된다.
* @name Grid#outlineSize
* @type {$ts:Grid.GridOptions["outlineSize"]}
* @default 0
* @example
* ```js
* import { MasonryGrid } from "@egjs/grid";
*
* const grid = new MasonryGrid(container, {
* outlineLength: 0,
* outlineSize: 0,
* });
*
* grid.outlineSize = 300;
* ```
*/
function getColumnPoint(outline, columnIndex, columnCount, pointCaculationName) {
return Math[pointCaculationName].apply(Math, outline.slice(columnIndex, columnIndex + columnCount));
}
function getColumnIndex(outline, columnCount, nearestCalculationName) {
var length = outline.length - columnCount + 1;
var pointCaculationName = nearestCalculationName === "max" ? "min" : "max";
var indexCaculationName = nearestCalculationName === "max" ? "lastIndexOf" : "indexOf";
var points = range(length).map(function (index) {
return getColumnPoint(outline, index, columnCount, pointCaculationName);
});
return points[indexCaculationName](Math[nearestCalculationName].apply(Math, points));
}
/**
* MasonryGrid is a grid that stacks items with the same width as a stack of bricks. Adjust the width of all images to the same size, find the lowest height column, and insert a new item.
* @ko MasonryGrid는 벽돌을 쌓아 올린 모양처럼 동일한 너비를 가진 아이템를 쌓는 레이아웃이다. 모든 이미지의 너비를 동일한 크기로 조정하고, 가장 높이가 낮은 열을 찾아 새로운 이미지를 삽입한다. 따라서 배치된 아이템 사이에 빈 공간이 생기지는 않지만 배치된 레이아웃의 아래쪽은 울퉁불퉁해진다.
* @memberof Grid
* @param {HTMLElement | string} container - A base element for a module <ko>모듈을 적용할 기준 엘리먼트</ko>
* @param {Grid.MasonryGrid.MasonryGridOptions} options - The option object of the MasonryGrid module <ko>MasonryGrid 모듈의 옵션 객체</ko>
*/
var MasonryGrid =
/*#__PURE__*/
function (_super) {
__extends$2(MasonryGrid, _super);
function MasonryGrid() {
return _super !== null && _super.apply(this, arguments) || this;
}
var __proto = MasonryGrid.prototype;
__proto.applyGrid = function (items, direction, outline) {
var columnSize = this.getComputedOutlineSize(items);
var column = this.getComputedOutlineLength(items);
var _a = this.options,
gap = _a.gap,
align = _a.align,
columnSizeRatio = _a.columnSizeRatio;
var outlineLength = outline.length;
var itemsLength = items.length;
var alignPoses = this._getAlignPoses(column, columnSize);
var isEndDirection = direction === "end";
var nearestCalculationName = isEndDirection ? "min" : "max";
var pointCalculationName = isEndDirection ? "max" : "min";
var startOutline = [0];
if (outlineLength === column) {
startOutline = outline.slice();
} else {
var point_1 = outlineLength ? Math[pointCalculationName].apply(Math, outline) : 0;
startOutline = range(column).map(function () {
return point_1;
});
}
var endOutline = startOutline.slice();
var columnDist = column > 1 ? alignPoses[1] - alignPoses[0] : 0;
var isStretch = align === "stretch";
var _loop_1 = function (i) {
var item = items[isEndDirection ? i : itemsLength - 1 - i];
var columnAttribute = parseInt(item.attributes.column || "1", 10);
var maxColumnAttribute = parseInt(item.attributes.maxColumn || "1", 10);
var contentSize = item.contentSize;
var columnCount = Math.min(column, columnAttribute || Math.max(1, Math.ceil((item.inlineSize + gap) / columnDist)));
var maxColumnCount = Math.min(column, Math.max(columnCount, maxColumnAttribute));
var columnIndex = getColumnIndex(endOutline, columnCount, nearestCalculationName);
var contentPos = getColumnPoint(endOutline, columnIndex, columnCount, pointCalculationName);
while (columnCount < maxColumnCount) {
var nextEndColumnIndex = columnIndex + columnCount;
var nextColumnIndex = columnIndex - 1;
if (isEndDirection && (nextEndColumnIndex >= column || endOutline[nextEndColumnIndex] > contentPos)) {
break;
}
if (!isEndDirection && (nextColumnIndex < 0 || endOutline[nextColumnIndex]) < contentPos) {
break;
}
if (!isEndDirection) {
--columnIndex;
}
++columnCount;
}
columnIndex = Math.max(0, columnIndex);
columnCount = Math.min(column - columnIndex, columnCount); // stretch mode or data-grid-column > "1"
if (columnAttribute > 0 && columnCount > 1 || isStretch) {
item.cssInlineSize = (columnCount - 1) * columnDist + columnSize;
}
if (columnSizeRatio > 0) {
contentSize = item.computedInlineSize / columnSizeRatio;
item.cssContentSize = contentSize;
}
var inlinePos = alignPoses[columnIndex];
contentPos = isEndDirection ? contentPos : contentPos - gap - contentSize;
item.cssInlinePos = inlinePos;
item.cssContentPos = contentPos;
var nextOutlinePoint = isEndDirection ? contentPos + contentSize + gap : contentPos;
range(columnCount).forEach(function (indexOffset) {
endOutline[columnIndex + indexOffset] = nextOutlinePoint;
});
};
for (var i = 0; i < itemsLength; ++i) {
_loop_1(i);
} // if end items, startOutline is low, endOutline is high
// if start items, startOutline is high, endOutline is low
return {
start: isEndDirection ? startOutline : endOutline,
end: isEndDirection ? endOutline : startOutline
};
};
__proto.getComputedOutlineSize = function (items) {
if (items === void 0) {
items = this.items;
}
var _a = this.options,
gap = _a.gap,
align = _a.align;
var columnSizeOption = this.columnSize || this.outlineSize;
var column = this.column || this.outlineLength || 1;
var columnSize = 0;
if (align === "stretch") {
columnSize = (this.getContainerInlineSize() + gap) / (column || 1) - gap;
} else if (columnSizeOption) {
columnSize = columnSizeOption;
} else if (items.length) {
var checkedItem = items[0];
for (var _i = 0, items_1 = items; _i < items_1.length; _i++) {
var item = items_1[_i];
var attributes = item.attributes;
if (item.updateState !== UPDATE_STATE.UPDATED || !item.inlineSize || attributes.column || attributes.maxColumnCount) {
continue;
}
checkedItem = item;
break;
}
var inlineSize = checkedItem.inlineSize || 0;
columnSize = inlineSize;
} else {
columnSize = this.getContainerInlineSize();
}
return columnSize || 0;
};
__proto.getComputedOutlineLength = function (items) {
if (items === void 0) {
items = this.items;
}
var gap = this.gap;
var columnOption = this.column || this.outlineLength;
var columnCalculationThreshold = this.columnCalculationThreshold;
var column = 1;
if (columnOption) {
column = columnOption;
} else {
var columnSize = this.getComputedOutlineSize(items);
column = Math.min(items.length, Math.max(1, Math.floor((this.getContainerInlineSize() + gap) / (columnSize - columnCalculationThreshold + gap))));
}
return column;
};
__proto._getAlignPoses = function (column, columnSize) {
var _a = this.options,
align = _a.align,
gap = _a.gap;
var containerSize = this.getContainerInlineSize();
var indexes = range(column);
var offset = 0;
var dist = 0;
if (align === "justify" || align === "stretch") {
var countDist = column - 1;
dist = countDist ? Math.max((containerSize - columnSize) / countDist, columnSize + gap) : 0;
offset = Math.min(0, containerSize / 2 - (countDist * dist + columnSize) / 2);
} else {
dist = columnSize + gap;
var totalColumnSize = (column - 1) * dist + columnSize;
if (align === "center") {
offset = (containerSize - totalColumnSize) / 2;
} else if (align === "end") {
offset = containerSize - totalColumnSize;
}
}
return indexes.map(function (i) {
return offset + i * dist;
});
};
MasonryGrid.propertyTypes = __assign$2(__assign$2({}, Grid.propertyTypes), {
column: PROPERTY_TYPE.RENDER_PROPERTY,
columnSize: PROPERTY_TYPE.RENDER_PROPERTY,
columnSizeRatio: PROPERTY_TYPE.RENDER_PROPERTY,
align: PROPERTY_TYPE.RENDER_PROPERTY,
columnCalculationThreshold: PROPERTY_TYPE.RENDER_PROPERTY
});
MasonryGrid.defaultOptions = __assign$2(__assign$2({}, Grid.defaultOptions), {
align: "justify",
column: 0,
columnSize: 0,
columnSizeRatio: 0,
columnCalculationThreshold: 0.5
});
MasonryGrid = __decorate$1([GetterSetter], MasonryGrid);
return MasonryGrid;
}(Grid);
/**
* Align of the position of the items. If you want to use `stretch`, be sure to set `column` or `columnSize` option. ("start", "center", "end", "justify", "stretch")
* @ko 아이템들의 위치의 정렬. `stretch`를 사용하고 싶다면 `column` 또는 `columnSize` 옵션을 설정해라. ("start", "center", "end", "justify", "stretch")
* @name Grid.MasonryGrid#align
* @type {$ts:Grid.MasonryGrid.MasonryGridOptions["align"]}
* @default "justify"
* @example
* ```js
* import { MasonryGrid } from "@egjs/grid";
*
* const grid = new MasonryGrid(container, {
* align: "start",
* });
*
* grid.align = "justify";
* ```
*/
/**
* The number of columns. If the number of columns is 0, it is automatically calculated according to the size of the container. Can be used instead of outlineLength.
* @ko 열의 개수. 열의 개수가 0이라면, 컨테이너의 사이즈에 의해 계산이 된다. outlineLength 대신 사용할 수 있다.
* @name Grid.MasonryGrid#column
* @type {$ts:Grid.MasonryGrid.MasonryGridOptions["column"]}
* @default 0
* @example
* ```js
* import { MasonryGrid } from "@egjs/grid";
*
* const grid = new MasonryGrid(container, {
* column: 0,
* });
*
* grid.column = 4;
* ```
*/
/**
* The size of the columns. If it is 0, it is calculated as the size of the first item in items. Can be used instead of outlineSize.
* @ko 열의 사이즈. 만약 열의 사이즈가 0이면, 아이템들의 첫번째 아이템의 사이즈로 계산이 된다. outlineSize 대신 사용할 수 있다.
* @name Grid.MasonryGrid#columnSize
* @type {$ts:Grid.MasonryGrid.MasonryGridOptions["columnSize"]}
* @default 0
* @example
* ```js
* import { MasonryGrid } from "@egjs/grid";
*
* const grid = new MasonryGrid(container, {
* columnSize: 0,
* });
*
* grid.columnSize = 200;
* ```
*/
/**
* The size ratio(inlineSize / contentSize) of the columns. 0 is not set.
* @ko 열의 사이즈 비율(inlineSize / contentSize). 0은 미설정이다.
* @name Grid.MasonryGrid#columnSizeRatio
* @type {$ts:Grid.MasonryGrid.MasonryGridOptions["columnSizeRatio"]}
* @default 0
* @example
* ```js
* import { MasonryGrid } from "@egjs/grid";
*
* const grid = new MasonryGrid(container, {
* columnSizeRatio: 0,
* });
*
* grid.columnSizeRatio = 0.5;
* ```
*/
/* eslint-disable */
/******************************************************************************
* Created 2008-08-19.
*
* Dijkstra path-finding functions. Adapted from the Dijkstar Python project.
*
* Copyright (C) 2008
* Wyatt Baldwin <self@wyattbaldwin.com>
* All rights reserved
*
* Licensed under the MIT license.
*
* http://www.opensource.org/licenses/mit-license.php
*
* 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.
*****************************************************************************/
function single_source_shortest_paths(graph, s, d) {
// Predecessor map for each node that has been encountered.
// node ID => predecessor node ID
var predecessors = {}; // Costs of shortest paths from s to all nodes encountered.
// node ID => cost
var costs = {};
costs[s] = 0; // Costs of shortest paths from s to all nodes encountered; differs from
// `costs` in that it provides easy access to the node that currently has
// the known shortest path from s.
// XXX: Do we actually need both `costs` and `open`?
var open = new BinaryHeap(function (x) {
return x.cost;
});
open.push({
value: s,
cost: 0
});
var closest;
var u;
var cost_of_s_to_u;
var adjacent_nodes;
var cost_of_e;
var cost_of_s_to_u_plus_cost_of_e;
var cost_of_s_to_v;
var first_visit;
while (open.size()) {
// In the nodes remaining in graph that have a known cost from s,
// find the node, u, that currently has the shortest path from s.
closest = open.pop();
u = closest.value;
cost_of_s_to_u = closest.cost; // Get nodes adjacent to u...
adjacent_nodes = graph(u) || {}; // ...and explore the edges that connect u to those nodes, updating
// the cost of the shortest paths to any or all of those nodes as
// necessary. v is the node across the current edge from u.
for (var v in adjacent_nodes) {
// Get the cost of the edge running from u to v.
cost_of_e = adjacent_nodes[v]; // Cost of s to u plus the cost of u to v across e--this is *a*
// cost from s to v that may or may not be less than the current
// known cost to v.
cost_of_s_to_u_plus_cost_of_e = cost_of_s_to_u + cost_of_e; // If we haven't visited v yet OR if the current known cost from s to
// v is greater than the new cost we just found (cost of s to u plus
// cost of u to v across e), update v's cost in the cost list and
// update v's predecessor in the predecessor list (it's now u).
cost_of_s_to_v = costs[v];
first_visit = typeof costs[v] === "undefined";
if (first_visit || cost_of_s_to_v > cost_of_s_to_u_plus_cost_of_e) {
costs[v] = cost_of_s_to_u_plus_cost_of_e;
open.push({
value: v,
cost: cost_of_s_to_u_plus_cost_of_e
});
predecessors[v] = u;
}
}
}
if (typeof costs[d] === "undefined") {
var msg = ["Could not find a path from ", s, " to ", d, "."].join("");
throw new Error(msg);
}
return predecessors;
}
function extract_shortest_path_from_predecessor_list(predecessors, d) {
var nodes = [];
var u = d;
while (u) {
nodes.push(u);
u = predecessors[u];
}
nodes.reverse();
return nodes;
}
function find_path(graph, s, d) {
var predecessors = single_source_shortest_paths(graph, s, d);
return extract_shortest_path_from_predecessor_list(predecessors, d);
}
var BinaryHeap =
/*#__PURE__*/
function () {
function BinaryHeap(scoreFunction) {
this.content = [];
this.scoreFunction = scoreFunction;
}
var __proto = BinaryHeap.prototype;
__proto.push = function (element) {
// Add the new element to the end of the array.
this.content.push(element); // Allow it to bubble up.
this.bubbleUp(this.content.length - 1);
};
__proto.pop = function () {
// Store the first element so we can return it later.
var result = this.content[0]; // Get the element at the end of the array.
var end = this.content.pop(); // If there are any elements left, put the end element at the
// start, and let it sink down.
if (this.content.length > 0) {
this.content[0] = end;
this.sinkDown(0);
}
return result;
};
__proto.size = function () {
return this.content.length;
};
__proto.bubbleUp = function (_n) {
var n = _n; // Fetch the element that has to be moved.
var element = this.content[n]; // When at 0, an element can not go up any further.
while (n > 0) {
// Compute the parent element's index, and fetch it.
var parentN = Math.floor((n + 1) / 2) - 1;
var parent = this.content[parentN]; // Swap the elements if the parent is greater.
if (this.scoreFunction(element) < this.scoreFunction(parent)) {
this.content[parentN] = element;
this.content[n] = parent; // Update 'n' to continue at the new position.
n = parentN;
} else {
// Found a parent that is less, no need to move it further.
break;
}
}
};
__proto.sinkDown = function (n) {
// Look up the target element and its score.
var length = this.content.length;
var element = this.content[n];
var elemScore = this.scoreFunction(element);
var child1Score;
while (true) {
// Compute the indices of the child elements.
var child2N = (n + 1) * 2;
var child1N = child2N - 1; // This is used to store the new position of the element,
// if any.
var swap = null; // If the first child exists (is inside the array)...
if (child1N < length) {
// Look it up and compute its score.
var child1 = this.content[child1N];
child1Score = this.scoreFunction(child1); // If the score is less than our element's, we need to swap.
if (child1Score < elemScore) {
swap = child1N;
}
} // Do the same checks for the other child.
if (child2N < length) {
var child2 = this.content[child2N];
var child2Score = this.scoreFunction(child2);
if (child2Score < (swap == null ? elemScore : child1Score)) {
swap = child2N;
}
} // If the element needs to be moved, swap it, and continue.
if (swap !== null) {
this.content[n] = this.content[swap];
this.content[swap] = element;
n = swap;
} else {
// Otherwise, we are done.
break;
}
}
};
return BinaryHeap;
}();
function splitItems(items, path) {
var length = path.length;
var groups = [];
for (var i = 0; i < length - 1; ++i) {
var path1 = parseInt(path[i], 10);
var path2 = parseInt(path[i + 1], 10);
groups.push(items.slice(path1, path2));
}
return groups;
}
function getExpectedColumnSize(item, rowSize) {
var inlineSize = item.orgInlineSize;
var contentSize = item.orgContentSize;
if (!inlineSize || !contentSize) {
return rowSize;
}
var inlineOffset = parseFloat(item.gridData.inlineOffset) || 0;
var contentOffset = parseFloat(item.gridData.contentOffset) || 0;
var ratio = contentSize <= contentOffset ? 1 : (inlineSize - inlineOffset) / (contentSize - contentOffset);
return ratio * (rowSize - contentOffset) + inlineOffset;
}
/**
* 'justified' is a printing term with the meaning that 'it fits in one row wide'. JustifiedGrid is a grid that the item is filled up on the basis of a line given a size.
* If 'data-grid-inline-offset' or 'data-grid-content-offset' are set for item element, the ratio is maintained except for the offset value.
* If 'data-grid-maintained-target' is set for an element whose ratio is to be maintained, the item is rendered while maintaining the ratio of the element.
* @ko 'justified'는 '1행의 너비에 맞게 꼭 들어찬'이라는 의미를 가진 인쇄 용어다. JustifiedGrid는 용어의 의미대로 너비가 주어진 사이즈를 기준으로 아이템가 가득 차도록 배치하는 Grid다.
* 아이템 엘리먼트에 'data-grid-inline-offset' 또는 'data-grid-content-offset'를 설정하면 offset 값을 제외하고 비율을 유지한다.
* 비율을 유지하고 싶은 엘리먼트에 'data-grid-maintained-target'을 설정한다면 해당 엘리먼트의 비율을 유지하면서 아이템이 렌더링이 된다.
* @memberof Grid
* @param {HTMLElement | string} container - A base element for a module <ko>모듈을 적용할 기준 엘리먼트</ko>
* @param {Grid.JustifiedGrid.JustifiedGridOptions} options - The option object of the JustifiedGrid module <ko>JustifiedGrid 모듈의 옵션 객체</ko>
*/
var JustifiedGrid =
/*#__PURE__*/
function (_super) {
__extends$2(JustifiedGrid, _super);
function JustifiedGrid() {
return _super !== null && _super.apply(this, arguments) || this;
}
var __proto = JustifiedGrid.prototype;
__proto.applyGrid = function (items, direction, outline) {
var _a = this.options,
attributePrefix = _a.attributePrefix,
horizontal = _a.horizontal;
items.forEach(function (item) {
if (!item.isUpdate) {
return;
}
var element = item.element;
var attributes = item.attributes;
var gridData = item.gridData;
var inlineOffset = parseFloat(attributes.inlineOffset) || gridData.inlineOffset || 0;
var contentOffset = parseFloat(attributes.contentOffset) || gridData.contentOffset | 0;
if (element && !("inlineOffset" in attributes) && !("contentOffset" in attributes) && item.mountState === MOUNT_STATE.MOUNTED) {
var maintainedTarget = element.querySelector("[" + attributePrefix + "maintained-target]");
if (maintainedTarget) {
var widthOffset = element.offsetWidth - element.clientWidth + element.scrollWidth - maintainedTarget.clientWidth;
var heightOffset = element.offsetHeight - element.clientHeight + element.scrollHeight - maintainedTarget.clientHeight;
if (horizontal) {
inlineOffset = heightOffset;
contentOffset = widthOffset;
} else {
inlineOffset = widthOffset;
contentOffset = heightOffset;
}
}
}
gridData.inlineOffset = inlineOffset;
gridData.contentOffset = contentOffset;
});
var rowRange = this.options.rowRange;
var path = [];
if (items.length) {
path = rowRange ? this._getRowPath(items) : this._getPath(items);
}
return this._setStyle(items, path, outline, direction === "end");
};
__proto._getRowPath = function (items) {
var _a;
var columnRange = this._getColumnRange();
var rowRange = this._getRowRange();
var pathLink = this._getRowLink(items, {
path: [0],
cost: 0,
length: 0,
currentNode: 0
}, columnRange, rowRange);
return (_a = pathLink === null || pathLink === void 0 ? void 0 : pathLink.path.map(function (node) {
return "" + node;
})) !== null && _a !== void 0 ? _a : [];
};
__proto._getRowLink = function (items, currentLink, columnRange, rowRange) {
var minColumn = columnRange[0];
var minRow = rowRange[0],
maxRow = rowRange[1];
var lastNode = items.length;
var path = currentLink.path,
pathLength = currentLink.length,
cost = currentLink.cost,
currentNode = currentLink.currentNode; // not reached lastNode but path is exceed or the number of remaining nodes is less than minColumn.
if (currentNode < lastNode && (maxRow <= pathLength || currentNode + minColumn > lastNode)) {
var rangeCost = getRangeCost(lastNode - currentNode, columnRange);
var lastCost = rangeCost * Math.abs(this._getCost(items, currentNode, lastNode));
return __assign$2(__assign$2({}, currentLink), {
length: pathLength + 1,
path: __spreadArray(__spreadArray([], path), [lastNode]),
currentNode: lastNode,
cost: cost + lastCost,
isOver: true
});
} else if (currentNode >= lastNode) {
return __assign$2(__assign$2({}, currentLink), {
currentNode: lastNode,
isOver: minRow > pathLength || maxRow < pathLength
});
} else {
return this._searchRowLink(items, currentLink, lastNode, columnRange, rowRange);
}
};
__proto._searchRowLink = function (items, currentLink, lastNode, columnRange, rowRange) {
var minColumn = columnRange[0],
maxColumn = columnRange[1];
var currentNode = currentLink.currentNode,
path = currentLink.path,
pathLength = currentLink.length,
cost = currentLink.cost;
var length = Math.min(lastNode, currentNode + maxColumn);
var links = [];
for (var nextNode = currentNode + minColumn; nextNode <= length; ++nextNode) {
if (nextNode === currentNode) {
continue;
}
var nextCost = Math.abs(this._getCost(items, currentNode, nextNode));
var nextLink = this._getRowLink(items, {
path: __spreadArray(__spreadArray([], path), [nextNode]),
length: pathLength + 1,
cost: cost + nextCost,
currentNode: nextNode
}, columnRange, rowRange);
if (nextLink) {
links.push(nextLink);
}
}
links.sort(function (a, b) {
var aIsOver = a.isOver;
var bIsOver = b.isOver;
if (aIsOver !== bIsOver) {
// If it is over, the cost is high.
return aIsOver ? 1 : -1;
}
var aRangeCost = getRangeCost(a.length, rowRange);
var bRangeCost = getRangeCost(b.length, rowRange);
return aRangeCost - bRangeCost || a.cost - b.cost;
}); // It returns the lowest cost link.
return links[0];
};
__proto._getExpectedRowSize = function (items) {
var gap = this.options.gap;
var containerInlineSize = this.getContainerInlineSize() - gap * (items.length - 1);
var ratioSum = 0;
var inlineSum = 0;
items.forEach(function (item) {
var inlineSize = item.orgInlineSize;
var contentSize = item.orgContentSize;
if (!inlineSize || !contentSize) {
ratioSum += 1;
return;
} // sum((expect - offset) * ratio) = container inline size
var inlineOffset = parseFloat(item.gridData.inlineOffset) || 0;
var contentOffset = parseFloat(item.gridData.contentOffset) || 0;
var maintainedRatio = contentSize <= contentOffset ? 1 : (inlineSize - inlineOffset) / (contentSize - contentOffset);
ratioSum += maintainedRatio;
inlineSum += contentOffset * maintainedRatio;
containerInlineSize -= inlineOffset;
});
return ratioSum ? (containerInlineSize + inlineSum) / ratioSum : 0;
};
__proto._getExpectedInlineSize = function (items, rowSize) {
var gap = this.options.gap;
var size = items.reduce(function (sum, item) {
return sum + getExpectedColumnSize(item, rowSize);
}, 0);
return size ? size + gap * (items.length - 1) : 0;
};
__proto._getCost = function (items, i, j) {
var lineItems = items.slice(i, j);
var rowSize = this._getExpectedRowSize(lineItems);
var _a = this._getSizeRange(),
minSize = _a[0],
maxSize = _a[1];
if (this.isCroppedSize) {
if (minSize <= rowSize && rowSize <= maxSize) {
return 0;
}
var expectedInlineSize = this._getExpectedInlineSize(lineItems, rowSize < minSize ? minSize : maxSize);
return Math.pow(expectedInlineSize - this.getContainerInlineSize(), 2);
}
if (isFinite(maxSize)) {
// if this size is not in range, the cost increases sharply.
if (rowSize < minSize) {
return Math.pow(rowSize - minSize, 2) + Math.pow(maxSize, 2);
} else if (rowSize > maxSize) {
return Math.pow(rowSize - maxSize, 2) + Math.pow(maxSize, 2);
}
} else if (rowSize < minSize) {
return Math.max(Math.pow(minSize, 2), Math.pow(rowSize, 2)) + Math.pow(maxSize, 2);
} // if this size in range, the cost is row
return rowSize - minSize;
};
__proto._getPath = function (items) {
var _this = this;
var lastNode = items.length;
var columnRangeOption = this.options.columnRange;
var _a = isObject(columnRangeOption) ? columnRangeOption : [columnRangeOption, columnRangeOption],
minColumn = _a[0],
maxColumn = _a[1];
var graph = function (nodeKey) {
var results = {};
var currentNode = parseInt(nodeKey, 10);
for (var nextNode = Math.min(currentNode + minColumn, lastNode); nextNode <= lastNode; ++nextNode) {
if (nextNode - currentNode > maxColumn) {
break;
}
var cost = _this._getCost(items, currentNode, nextNode);
if (cost < 0 && nextNode === lastNode) {
cost = 0;
}
results["" + nextNode] = Math.pow(cost, 2);
}
return results;
}; // shortest path for items' total height.
return find_path(graph, "0", "" + lastNode);
};
__proto._setStyle = function (items, path, outline, isEndDirection) {
var _this = this;
if (outline === void 0) {
outline = [];
}
var _a = this.options,
gap = _a.gap,
isCroppedSize = _a.isCroppedSize,
displayedRow = _a.displayedRow;
var sizeRange = this._getSizeRange();
var startPoint = outline[0] || 0;
var containerInlineSize = this.getContainerInlineSize();
var groups = splitItems(items, path);
var contentPos = startPoint;
var displayedSize = 0;
groups.forEach(function (groupItems, rowIndex) {
var length = groupItems.length;
var rowSize = _this._getExpectedRowSize(groupItems);
if (isCroppedSize) {
rowSize = Math.max(sizeRange[0], Math.min(rowSize, sizeRange[1]));
}
var expectedInlineSize = _this._getExpectedInlineSize(groupItems, rowSize);
var allGap = gap * (length - 1);
var scale = (containerInlineSize - allGap) / (expectedInlineSize - allGap);
groupItems.forEach(function (item, i) {
var columnSize = getExpectedColumnSize(item, rowSize);
var prevItem = groupItems[i - 1];
var inlinePos = prevItem ? prevItem.cssInlinePos + prevItem.cssInlineSize + gap : 0;
if (isCroppedSize) {
columnSize *= scale;
}
item.setCSSGridRect({
inlinePos: inlinePos,
contentPos: contentPos,
inlineSize: columnSize,
contentSize: rowSize
});
});
contentPos += gap + rowSize;
if (displayedRow < 0 || rowIndex < displayedRow) {
displayedSize = contentPos;
}
});
if (isEndDirection) {
// previous group's end outline is current group's start outline
return {
start: [startPoint],
end: [displayedSize]
};
} // always start is lower than end.
// contentPos is endPoinnt
var height = contentPos - startPoint;
items.forEach(function (item) {
item.cssContentPos -= height;
});
return {
start: [startPoint - height],
end: [startPoint] // endPoint - height = startPoint
};
};
__proto.getComputedOutlineLength = function () {
return 1;
};
__proto.getComputedOutlineSize = function () {
return this.getContainerInlineSize();
};
__proto._getRowRange = function () {
var rowRange = this.rowRange;
return isObject(rowRange) ? rowRange : [rowRange, rowRange];
};
__proto._getColumnRange = function () {
var columnRange = this.columnRange;
return isObject(columnRange) ? columnRange : [columnRange, columnRange];
};
__proto._getSizeRange = function () {
var sizeRange = this.sizeRange;
return isObject(sizeRange) ? sizeRange : [sizeRange, sizeRange];
};
JustifiedGrid.propertyTypes = __assign$2(__assign$2({}, Grid.propertyTypes), {
columnRange: PROPERTY_TYPE.RENDER_PROPERTY,
rowRange: PROPERTY_TYPE.RENDER_PROPERTY,
sizeRange: PROPERTY_TYPE.RENDER_PROPERTY,
isCroppedSize: PROPERTY_TYPE.RENDER_PROPERTY,
displayedRow: PROPERTY_TYPE.RENDER_PROPERTY
});
JustifiedGrid.defaultOptions = __assign$2(__assign$2({}, Grid.defaultOptions), {
columnRange: [1, 8],
rowRange: 0,
sizeRange: [0, Infinity],
displayedRow: -1,
isCroppedSize: false
});
JustifiedGrid = __decorate$1([GetterSetter], JustifiedGrid);
return JustifiedGrid;
}(Grid);
/**
* The minimum and maximum number of items per line.
* @ko 한 줄에 들어가는 아이템의 최소, 최대 개수.
* @name Grid.JustifiedGrid#columnRange
* @type {$ts:Grid.JustifiedGrid.JustifiedGridOptions["columnRange"]}
* @default [1, 8]
* @example
* ```js
* import { JustifiedGrid } from "@egjs/grid";
*
* const grid = new JustifiedGrid(container, {
* columnRange: [1, 8],
* });
*
* grid.columnRange = [3, 6];
* ```
*/
/**
* The minimum and maximum number of rows in a group, 0 is not set.
* @ko 한 그룹에 들어가는 행의 최소, 최대 개수, 0은 미설정이다.
* @name Grid.JustifiedGrid#rowRange
* @type {$ts:Grid.JustifiedGrid.JustifiedGridOptions["rowRange"]}
* @default 0
* @example
* ```js
* import { JustifiedGrid } from "@egjs/grid";
*
* const grid = new JustifiedGrid(container, {
* rowRange: 0,
* });
*
* grid.rowRange = [3, 4];
* ```
*/
/**
* The minimum and maximum size by which the item is adjusted. If it is not calculated, it may deviate from the minimum and maximum sizes.
* @ko 아이템이 조정되는 최소, 최대 사이즈. 계산이 되지 않는 경우 최소, 최대 사이즈를 벗어날 수 있다.
* @name Grid.JustifiedGrid#sizeRange
* @type {$ts:Grid.JustifiedGrid.JustifiedGridOptions["sizeRange"]}
* @default [0, Infinity]
* @example
* ```js
* import { JustifiedGrid } from "@egjs/grid";
*
* const grid = new JustifiedGrid(container, {
* sizeRange: [0, Infinity],
* });
*
* grid.sizeRange = [200, 800];
* ```
*/
/**
* Maximum number of rows to be counted for container size. You can hide it on the screen by setting overflow: hidden. -1 is not set.
* @ko - 컨테이너 크기에 계산될 최대 row 개수. overflow: hidden을 설정하면 화면에 가릴 수 있다. -1은 미설정이다.
* @name Grid.JustifiedGrid#displayedRow
* @type {$ts:Grid.JustifiedGrid.JustifiedGridOptions["displayedRow"]}
* @default -1
* @example
* ```js
* import { JustifiedGrid } from "@egjs/grid";
*
* const grid = new JustifiedGrid(container, {
* displayedRow: -1,
* });
*
* grid.displayedRow = 3;
* ```
*/
/**
* Whether to crop when the row size is out of sizeRange. If set to true, this ratio can be broken.
* @ko - row 사이즈가 sizeRange에 벗어나면 크롭할지 여부. true로 설정하면 비율이 깨질 수 있다.
* @name Grid.JustifiedGrid#isCroppedSize
* @type {$ts:Grid.JustifiedGrid.JustifiedGridOptions["isCroppedSize"]}
* @default false
* @example
* ```js
* import { JustifiedGrid } from "@egjs/grid";
*
* const grid = new JustifiedGrid(container, {
* sizeRange: [200, 250],
* isCroppedSize: false,
* });
*
* grid.isCroppedSize = true;
* ```
*/
function getMaxPoint(outline) {
var maxPoint = -Infinity;
outline.forEach(function (point) {
if (isFinite(point)) {
maxPoint = Math.max(maxPoint, point);
}
});
return isFinite(maxPoint) ? maxPoint : 0;
}
function getMinPoint(outline) {
var minPoint = Infinity;
outline.forEach(function (point) {
if (isFinite(point)) {
minPoint = Math.min(minPoint, point);
}
});
return isFinite(minPoint) ? minPoint : 0;
}
function getOutlinePoint(startOutline, frameOutline, useFrameFill) {
return getMaxPoint(startOutline) + getOutlineDist(startOutline, frameOutline, useFrameFill);
}
function getOutlineDist(startOutline, endOutline, useFrameFill) {
var length = startOutline.length;
if (!length) {
return 0;
}
var minEndPoint = getMinPoint(endOutline);
var maxStartPoint = getMaxPoint(startOutline);
var frameDist = 0;
if (!useFrameFill) {
return 0;
}
for (var outlineIndex = 0; outlineIndex < length; ++outlineIndex) {
var startPoint = startOutline[outlineIndex];
var endPoint = endOutline[outlineIndex];
if (!isFinite(startPoint) || !isFinite(endPoint)) {
continue;
}
var startPos = startPoint - maxStartPoint;
var endPos = endPoint - minEndPoint; // Fill empty block.
frameDist = outlineIndex ? Math.max(frameDist, frameDist + startPos - endPos) : startPos - endPos;
}
return frameDist;
}
function fillOutlines(startOutline, endOutline, rect) {
var inlinePos = rect.inlinePos,
inlineSize = rect.inlineSize,
contentPos = rect.contentPos,
contentSize = rect.contentSize;
for (var outlineIndex = inlinePos; outlineIndex < inlinePos + inlineSize; ++outlineIndex) {
startOutline[outlineIndex] = Math.min(startOutline[outlineIndex], contentPos);
endOutline[outlineIndex] = Math.max(endOutline[outlineIndex], contentPos + contentSize);
}
}
/**
* 'Frame' is a printing term with the meaning that 'it fits in one row wide'. FrameGrid is a grid that the item is filled up on the basis of a line given a size.
* @ko 'Frame'는 '1행의 너비에 맞게 꼭 들어찬'이라는 의미를 가진 인쇄 용어다. FrameGrid는 용어의 의미대로 너비가 주어진 사이즈를 기준으로 아이템이 가득 차도록 배치하는 Grid다.
* @memberof Grid
* @param {HTMLElement | string} container - A base element for a module <ko>모듈을 적용할 기준 엘리먼트</ko>
* @param {Grid.FrameGrid.FrameGridOptions} options - The option object of the FrameGrid module <ko>FrameGrid 모듈의 옵션 객체</ko>
*/
var FrameGrid =
/*#__PURE__*/
function (_super) {
__extends$2(FrameGrid, _super);
function FrameGrid() {
return _super !== null && _super.apply(this, arguments) || this;
}
var __proto = FrameGrid.prototype;
__proto.applyGrid = function (items, direction, outline) {
var frame = this._getFrame();
var frameInlineSize = frame.inlineSize,
frameContentSize = frame.contentSize,
frameRects = frame.rects;
var _a = this.options,
gap = _a.gap,
useFrameFill = _a.useFrameFill;
var _b = this.getRectSize(frameInlineSize),
rectInlineSize = _b.inlineSize,
rectContentSize = _b.contentSize;
var itemsLength = items.length;
if (!itemsLength || !frameInlineSize || !frameContentSize) {
return {
start: outline,
end: outline
};
}
var rectsLength = frameRects.length;
var startOutline = range(frameInlineSize).map(function () {
return Infinity;
});
var endOutline = range(frameInlineSize).map(function () {
return -Infinity;
});
var frameOutline = frame.outline.map(function (point) {
return point * (rectContentSize + gap);
});
for (var startIndex = 0; startIndex < itemsLength; startIndex += rectsLength) {
// Compare group's startOutline and startOutline of rect
var startPoint = getOutlinePoint(endOutline, frameOutline, useFrameFill);
for (var rectIndex = 0; rectIndex < rectsLength && startIndex + rectIndex < itemsLength; ++rectIndex) {
var item = items[startIndex + rectIndex];
var _c = frameRects[rectIndex],
frameRectContentPos = _c.contentPos,
frameRectInlinePos = _c.inlinePos,
frameRectContentSize = _c.contentSize,
frameRectInlineSize = _c.inlineSize;
var contentPos = startPoint + frameRectContentPos * (rectContentSize + gap);
var inlinePos = frameRectInlinePos * (rectInlineSize + gap);
var contentSize = frameRectContentSize * (rectContentSize + gap) - gap;
var inlineSize = frameRectInlineSize * (rectInlineSize + gap) - gap;
fillOutlines(startOutline, endOutline, {
inlinePos: frameRectInlinePos,
inlineSize: frameRectInlineSize,
contentPos: contentPos,
contentSize: contentSize + gap
});
item.setCSSGridRect({
inlinePos: inlinePos,
contentPos: contentPos,
inlineSize: inlineSize,
contentSize: contentSize
});
}
}
var isDirectionEnd = direction === "end";
var gridOutline = outline.length ? outline : [0];
if (gridOutline.length !== frameInlineSize) {
var point_1 = isDirectionEnd ? Math.max.apply(Math, gridOutline) : Math.min.apply(Math, gridOutline);
gridOutline = range(frameInlineSize).map(function () {
return point_1;
});
}
startOutline = startOutline.map(function (point) {
return isFinite(point) ? point : 0;
});
endOutline = endOutline.map(function (point) {
return isFinite(point) ? point : 0;
});
var outlineDist = isDirectionEnd ? getOutlinePoint(gridOutline, startOutline, useFrameFill) : getOutlinePoint(endOutline, gridOutline, useFrameFill);
items.forEach(function (item) {
item.cssContentPos += outlineDist;
});
return {
start: startOutline.map(function (point) {
return point + outlineDist;
}),
end: endOutline.map(function (point) {
return point + outlineDist;
})
};
};
__proto.getComputedOutlineLength = function () {
var frame = this.options.frame;
return frame.length ? frame[0].length : 0;
};
__proto.getComputedOutlineSize = function () {
var _a = this.options,
gap = _a.gap,
rectSizeOption = _a.rectSize;
if (typeof rectSizeOption === "object") {
return rectSizeOption.inlineSize;
}
return rectSizeOption || (this.getContainerInlineSize() + gap) / this.getComputedOutlineLength() - gap;
};
__proto.getRectSize = function (frameInlineSize) {
var _a = this.options,
gap = _a.gap,
rectSizeOption = _a.rectSize;
if (typeof rectSizeOption === "object") {
return rectSizeOption;
}
var rectSizeValue = rectSizeOption ? rectSizeOption : (this.getContainerInlineSize() + gap) / frameInlineSize - gap;
return {
inlineSize: rectSizeValue,
contentSize: rectSizeValue
};
};
__proto._getFrame = function () {
var frame = this.options.frame;
var frameContentSize = frame.length;
var frameInlineSize = frameContentSize ? frame[0].length : 0;
var rects = [];
var passMap = {};
var startOutline = range(frameInlineSize).map(function () {
return Infinity;
});
var endOutline = range(frameInlineSize).map(function () {
return -Infinity;
});
for (var y1 = 0; y1 < frameContentSize; ++y1) {
for (var x1 = 0; x1 < frameInlineSize; ++x1) {
var type = frame[y1][x1];
if (!type) {
continue;
}
if (passMap[y1 + "," + x1]) {
continue;
}
var rect = this._findRect(passMap, type, y1, x1, frameInlineSize, frameContentSize);
fillOutlines(startOutline, endOutline, rect);
rects.push(rect);
}
}
rects.sort(function (a, b) {
return a.type < b.type ? -1 : 1;
});
return {
rects: rects,
inlineSize: frameInlineSize,
contentSize: frameContentSize,
outline: startOutline
};
};
__proto._findRect = function (passMap, type, y1, x1, frameInlineSize, frameContentSize) {
var frame = this.options.frame;
var contentSize = 1;
var inlineSize = 1; // find rect
for (var x2 = x1; x2 < frameInlineSize; ++x2) {
if (frame[y1][x2] === type) {
inlineSize = x2 - x1 + 1;
continue;
}
break;
}
for (var y2 = y1; y2 < frameContentSize; ++y2) {
if (frame[y2][x1] === type) {
contentSize = y2 - y1 + 1;
continue;
}
break;
} // pass rect
for (var y = y1; y < y1 + contentSize; ++y) {
for (var x = x1; x < x1 + inlineSize; ++x) {
passMap[y + "," + x] = true;
}
}
var rect = {
type: type,
inlinePos: x1,
contentPos: y1,
inlineSize: inlineSize,
contentSize: contentSize
};
return rect;
};
FrameGrid.propertyTypes = __assign$2(__assign$2({}, Grid.propertyTypes), {
frame: PROPERTY_TYPE.RENDER_PROPERTY,
useFrameFill: PROPERTY_TYPE.RENDER_PROPERTY,
rectSize: PROPERTY_TYPE.RENDER_PROPERTY
});
FrameGrid.defaultOptions = __assign$2(__assign$2({}, Grid.defaultOptions), {
frame: [],
rectSize: 0,
useFrameFill: true
});
FrameGrid = __decorate$1([GetterSetter], FrameGrid);
return FrameGrid;
}(Grid);
/**
* The shape of the grid. You can set the shape and order of items with a 2d array ([contentPos][inlinePos]). You can place items as many times as you fill the array with numbers, and zeros and spaces are empty spaces. The order of the items is arranged in ascending order of the numeric values that fill the array.
* @ko Grid의 모양. 2d 배열([contentPos][inlinePos])로 아이템의 모양과 순서를 설정할 수 있다. 숫자로 배열을 채운만큼 아이템을 배치할 수 있으며 0과 공백은 빈 공간이다. 아이템들의 순서는 배열을 채운 숫자값의 오름차순대로 배치가 된다.
* @name Grid.FrameGrid#frame
* @type {$ts:Grid.FrameGrid.FrameGridOptions["frame"]}
* @default []
* @example
* ```js
* import { FrameGrid } from "@egjs/grid";
*
* // Item 1 : 2 x 2
* // Item 2 : 1 x 1
* // Item 3 : 1 x 2
* // Item 4 : 1 x 1
* // Item 5 : 2 x 1
* const grid = new FrameGrid(container, {
* frame: [
* [1, 1, 0, 0, 2, 3],
* [1, 1, 0, 4, 5, 5],
* ],
* });
*
* // Item 1 : 2 x 2
* // Item 2 : 2 x 2
* grid.frame = [
* [1, 1, 0, 0, 2, 2],
* [1, 1, 0, 0, 2, 2],
* ];
* ```
*/
/**
* Make sure that the frame can be attached after the previous frame.
* @ko 다음 프레임이 전 프레임에 이어 붙일 수 있는지 있는지 확인한다.
* @name Grid.FrameGrid#useFrameFill
* @type {$ts:Grid.FrameGrid.FrameGridOptions["useFrameFill"]}
* @default true
* @example
* ```js
* import { FrameGrid } from "@egjs/grid";
*
* const grid = new FrameGrid(container, {
* useFrameFill: true,
* });
*
* grid.useFrameFill = false;
* ```
*/
/**
* 1x1 rect size. If it is 0, it is determined by the number of columns in the frame. (default: 0)
* @ko 1x1 직사각형 크기. 0이면 frame의 column의 개수에 의해 결정된다. (default: 0)
* @name Grid.FrameGrid#rectSize
* @type {$ts:Grid.FrameGrid.FrameGridOptions["rectSize"]}
* @example
* ```js
* import { FrameGrid } from "@egjs/grid";
*
* const grid = new FrameGrid(container, {
* rectSize: 0,
* });
*
* grid.rectSize = { inlineSize: 100, contentSize: 150 };
* ```
*/
var BoxModel =
/*#__PURE__*/
function () {
function BoxModel(status) {
var boxStatus = __assign$2({
orgInlineSize: 0,
orgContentSize: 0,
inlineSize: 0,
contentSize: 0,
inlinePos: 0,
contentPos: 0,
items: []
}, status);
for (var name in boxStatus) {
this[name] = boxStatus[name];
}
}
var __proto = BoxModel.prototype;
__proto.scaleTo = function (inlineSize, contentSize) {
var scaleX = this.inlineSize ? inlineSize / this.inlineSize : 0;
var scaleY = this.contentSize ? contentSize / this.contentSize : 0;
this.items.forEach(function (item) {
if (scaleX !== 0) {
item.inlinePos *= scaleX;
item.inlineSize *= scaleX;
}
if (scaleY !== 0) {
item.contentPos *= scaleY;
item.contentSize *= scaleY;
}
});
this.inlineSize = inlineSize;
this.contentSize = contentSize;
};
__proto.push = function (item) {
this.items.push(item);
};
__proto.getOrgSizeWeight = function () {
return this.orgInlineSize * this.orgContentSize;
};
__proto.getSize = function () {
return this.inlineSize * this.contentSize;
};
__proto.getOrgRatio = function () {
return this.orgContentSize === 0 ? 0 : this.orgInlineSize / this.orgContentSize;
};
__proto.getRatio = function () {
return this.contentSize === 0 ? 0 : this.inlineSize / this.contentSize;
};
return BoxModel;
}();
function getCost(originLength, length) {
var cost = originLength / length;
if (cost < 1) {
cost = 1 / cost;
}
return cost - 1;
}
function fitArea(item, bestFitArea, itemFitSize, containerFitSize, isContentDirection) {
item.contentSize = itemFitSize.contentSize;
item.inlineSize = itemFitSize.inlineSize;
bestFitArea.contentSize = containerFitSize.contentSize;
bestFitArea.inlineSize = containerFitSize.inlineSize;
if (isContentDirection) {
item.contentPos = bestFitArea.contentPos + bestFitArea.contentSize;
item.inlinePos = bestFitArea.inlinePos;
} else {
item.inlinePos = bestFitArea.inlinePos + bestFitArea.inlineSize;
item.contentPos = bestFitArea.contentPos;
}
}
/**
* The PackingGrid is a grid that shows the important items bigger without sacrificing the weight of the items.
* Rows and columns are separated so that items are dynamically placed within the horizontal and vertical space rather than arranged in an orderly fashion.
* If `sizeWeight` is higher than `ratioWeight`, the size of items is preserved as much as possible.
* Conversely, if `ratioWeight` is higher than `sizeWeight`, the ratio of items is preserved as much as possible.
* @ko PackingGrid는 아이템의 본래 크기에 따른 비중을 해치지 않으면서 중요한 카드는 더 크게 보여 주는 레이아웃이다.
* 행과 열이 구분돼 아이템을 정돈되게 배치하는 대신 가로세로 일정 공간 내에서 동적으로 아이템을 배치한다.
* `sizeWeight`가 `ratioWeight`보다 높으면 아이템들의 size가 최대한 보존이 된다.
* 반대로 `ratioWeight`가 `sizeWeight`보다 높으면 아이템들의 비율이 최대한 보존이 된다.
* @memberof Grid
* @param {HTMLElement | string} container - A base element for a module <ko>모듈을 적용할 기준 엘리먼트</ko>
* @param {Grid.PackingGrid.PackingGridOptions} options - The option object of the PackingGrid module <ko>PackingGrid 모듈의 옵션 객체</ko>
*/
var PackingGrid =
/*#__PURE__*/
function (_super) {
__extends$2(PackingGrid, _super);
function PackingGrid() {
return _super !== null && _super.apply(this, arguments) || this;
}
var __proto = PackingGrid.prototype;
__proto.applyGrid = function (items, direction, outline) {
var _this = this;
var _a = this.options,
aspectRatio = _a.aspectRatio,
gap = _a.gap;
var containerInlineSize = this.getContainerInlineSize();
var containerContentSize = containerInlineSize / aspectRatio;
var prevOutline = outline.length ? outline : [0];
var startPoint = direction === "end" ? Math.max.apply(Math, prevOutline) : Math.min.apply(Math, prevOutline) - containerContentSize - gap;
var endPoint = startPoint + containerContentSize + gap;
var container = new BoxModel({});
items.forEach(function (item) {
var model = new BoxModel({
inlineSize: item.orgInlineSize,
contentSize: item.orgContentSize,
orgInlineSize: item.orgInlineSize,
orgContentSize: item.orgContentSize
});
_this._findBestFitArea(container, model);
container.push(model);
container.scaleTo(containerInlineSize + gap, containerContentSize + gap);
});
items.forEach(function (item, i) {
var boxItem = container.items[i];
var inlineSize = boxItem.inlineSize - gap;
var contentSize = boxItem.contentSize - gap;
var contentPos = startPoint + boxItem.contentPos;
var inlinePos = boxItem.inlinePos;
item.setCSSGridRect({
inlinePos: inlinePos,
contentPos: contentPos,
inlineSize: inlineSize,
contentSize: contentSize
});
});
return {
start: [startPoint],
end: [endPoint]
};
};
__proto._findBestFitArea = function (container, item) {
if (container.getRatio() === 0) {
// 아이템 최초 삽입시 전체영역 지정
container.orgInlineSize = item.inlineSize;
container.orgContentSize = item.contentSize;
container.inlineSize = item.inlineSize;
container.contentSize = item.contentSize;
return;
}
var bestFitArea;
var minCost = Infinity;
var isContentDirection = false;
var itemFitSize = {
inlineSize: 0,
contentSize: 0
};
var containerFitSize = {
inlineSize: 0,
contentSize: 0
};
var sizeWeight = this._getWeight("size");
var ratioWeight = this._getWeight("ratio");
container.items.forEach(function (child) {
var containerSizeCost = getCost(child.getOrgSizeWeight(), child.getSize()) * sizeWeight;
var containerRatioCost = getCost(child.getOrgRatio(), child.getRatio()) * ratioWeight;
var inlineSize = child.inlineSize;
var contentSize = child.contentSize;
for (var i = 0; i < 2; ++i) {
var itemInlineSize = void 0;
var itemContentSize = void 0;
var containerInlineSize = void 0;
var containerContentSize = void 0;
if (i === 0) {
// add item to content pos (top, bottom)
itemInlineSize = inlineSize;
itemContentSize = contentSize * (item.contentSize / (child.orgContentSize + item.contentSize));
containerInlineSize = inlineSize;
containerContentSize = contentSize - itemContentSize;
} else {
// add item to inline pos (left, right)
itemContentSize = contentSize;
itemInlineSize = inlineSize * (item.inlineSize / (child.orgInlineSize + item.inlineSize));
containerContentSize = contentSize;
containerInlineSize = inlineSize - itemInlineSize;
}
var itemSize = itemInlineSize * itemContentSize;
var itemRatio = itemInlineSize / itemContentSize;
var containerSize = containerInlineSize * containerContentSize;
var containerRatio = containerContentSize / containerContentSize;
var cost = getCost(item.getSize(), itemSize) * sizeWeight;
cost += getCost(item.getRatio(), itemRatio) * ratioWeight;
cost += getCost(child.getOrgSizeWeight(), containerSize) * sizeWeight - containerSizeCost;
cost += getCost(child.getOrgRatio(), containerRatio) * ratioWeight - containerRatioCost;
if (cost === Math.min(cost, minCost)) {
minCost = cost;
bestFitArea = child;
isContentDirection = i === 0;
itemFitSize.inlineSize = itemInlineSize;
itemFitSize.contentSize = itemContentSize;
containerFitSize.inlineSize = containerInlineSize;
containerFitSize.contentSize = containerContentSize;
}
}
});
fitArea(item, bestFitArea, itemFitSize, containerFitSize, isContentDirection);
};
__proto.getComputedOutlineLength = function () {
return 1;
};
__proto.getComputedOutlineSize = function () {
return this.getContainerInlineSize();
};
__proto._getWeight = function (type) {
var options = this.options;
var weightPriority = options.weightPriority;
if (weightPriority === type) {
return 100;
} else if (weightPriority === "custom") {
return options[type + "Weight"];
}
return 1;
};
PackingGrid.propertyTypes = __assign$2(__assign$2({}, Grid.propertyTypes), {
aspectRatio: PROPERTY_TYPE.RENDER_PROPERTY,
sizeWeight: PROPERTY_TYPE.RENDER_PROPERTY,
ratioWeight: PROPERTY_TYPE.RENDER_PROPERTY,
weightPriority: PROPERTY_TYPE.RENDER_PROPERTY
});
PackingGrid.defaultOptions = __assign$2(__assign$2({}, Grid.defaultOptions), {
aspectRatio: 1,
sizeWeight: 1,
ratioWeight: 1,
weightPriority: "custom"
});
PackingGrid = __decorate$1([GetterSetter], PackingGrid);
return PackingGrid;
}(Grid);
/**
* The aspect ratio (inlineSize / contentSize) of the container with items.
* @ko 아이템들을 가진 컨테이너의 종횡비(inlineSize / contentSize).
* @name Grid.PackingGrid#aspectRatio
* @type {$ts:Grid.PackingGrid.PackingGridOptions["aspectRatio"]}
* @default 1
* @example
* ```js
* import { PackingGrid } from "@egjs/grid";
*
* const grid = new PackingGrid(container, {
* aspectRatio: 1,
* });
*
* grid.aspectRatio = 1.5;
* ```
*/
/**
* The priority that determines the weight of the item. "size" = (sizeWieght: 2, ratioWeight: 1), "ratio" = (sizeWeight: 1, ratioWeight; 2), "custom" = (set sizeWeight, ratioWeight)
* item's weight = item's ratio(inlineSize / contentSize) change * `ratioWeight` + size(inlineSize * contentSize) change * `sizeWeight`.
* @ko 아이템의 가중치를 결정하는 우선수치. "size" = (sizeWieght: 2, ratioWeight: 1), "ratio" = (sizeWeight: 1, ratioWeight; 2), "custom" = (set sizeWeight, ratioWeight). 아이템의 가중치 = ratio(inlineSize / contentSize)의 변화량 * `ratioWeight` + size(inlineSize * contentSize)의 변화량 * `sizeWeight`.
* @name Grid.PackingGrid#weightPriority
* @type {$ts:Grid.PackingGrid.PackingGridOptions["weightPriority"]}
* @default "custom"
* @example
* ```js
* import { PackingGrid } from "@egjs/grid";
*
* const grid = new PackingGrid(container, {
* weightPriority: "custom",
* sizeWeight: 1,
* ratioWeight: 1,
* });
*
* grid.weightPriority = "size";
* // or
* grid.weightPriority = "ratio";
* ```
*/
/**
* The size weight when placing items.
* @ko 아이템들을 배치하는데 사이즈 가중치.
* @name Grid.PackingGrid#sizeWeight
* @type {$ts:Grid.PackingGrid.PackingGridOptions["sizeWeight"]}
* @default 1
* @example
* ```js
* import { PackingGrid } from "@egjs/grid";
*
* const grid = new PackingGrid(container, {
* sizeWeight: 1,
* });
*
* grid.sizeWeight = 10;
* ```
*/
/**
* The weight to keep ratio when placing items.
* @ko 아이템들을 배치하는데 비율을 유지하는 가중치.
* @name Grid.PackingGrid#ratioWeight
* @type {$ts:Grid.PackingGrid.PackingGridOptions["ratioWeight"]}
* @default 1
* @example
* ```js
* import { PackingGrid } from "@egjs/grid";
*
* const grid = new PackingGrid(container, {
* ratioWeight: 1,
* });
*
* grid.ratioWeight = 10;
* ```
*/
var ResizeWatcher =
/*#__PURE__*/
function () {
function ResizeWatcher(container, options) {
var _this = this;
if (options === void 0) {
options = {};
}
this._resizeTimer = 0;
this._maxResizeDebounceTimer = 0;
this.rect = {
width: 0,
height: 0
};
this._onResize = function () {
clearTimeout(_this._resizeTimer);
clearTimeout(_this._maxResizeDebounceTimer);
_this._maxResizeDebounceTimer = 0;
_this._resizeTimer = 0;
var watchDirection = _this.options.watchDirection;
var prevRect = _this.rect;
_this.resize();
var rect = _this.rect;
var isWatchWidth = watchDirection === "box" || watchDirection === "width";
var isWatchHeight = watchDirection === "box" || watchDirection === "height";
var isResize = !watchDirection || isWatchWidth && prevRect.width !== rect.width || isWatchHeight && prevRect.height !== rect.height;
if (isResize) {
_this._emitter.trigger("resize", {});
}
};
this._scheduleResize = function () {
var _a = _this.options,
resizeDebounce = _a.resizeDebounce,
maxResizeDebounce = _a.maxResizeDebounce;
if (!_this._maxResizeDebounceTimer && maxResizeDebounce >= resizeDebounce) {
_this._maxResizeDebounceTimer = window.setTimeout(_this._onResize, maxResizeDebounce);
}
if (_this._resizeTimer) {
clearTimeout(_this._resizeTimer);
_this._resizeTimer = 0;
}
_this._resizeTimer = window.setTimeout(_this._onResize, resizeDebounce);
};
this.options = __assign$2({
resizeDebounce: 100,
maxResizeDebounce: 0,
useResizeObserver: false,
useWindowResize: true,
watchDirection: false,
rectBox: "content-box"
}, options);
this.container = isString(container) ? document.querySelector(container) : container;
this._init();
}
var __proto = ResizeWatcher.prototype;
__proto.getRect = function () {
return this.rect;
};
__proto.setRect = function (rect) {
this.rect = __assign$2({}, rect);
};
__proto.resize = function () {
var container = this.container;
this.setRect(this.options.rectBox === "border-box" ? {
width: container.offsetWidth,
height: container.offsetHeight
} : {
width: container.clientWidth,
height: container.clientHeight
});
};
__proto.listen = function (callback) {
this._emitter.on("resize", callback);
return this;
};
__proto.destroy = function () {
var _a;
(_a = this._observer) === null || _a === void 0 ? void 0 : _a.disconnect();
if (this.options.useWindowResize) {
window.removeEventListener("reisze", this._onResize);
}
};
__proto._init = function () {
var container = this.container;
var options = this.options;
this._emitter = new Component();
if (options.useResizeObserver && !!window.ResizeObserver) {
this._observer = new window.ResizeObserver(this._scheduleResize);
this._observer.observe(container, {
box: options.rectBox
});
}
if (options.useWindowResize) {
window.addEventListener("resize", this._scheduleResize);
}
this.resize();
};
return ResizeWatcher;
}();
var ua$1 = typeof window !== "undefined" ? window.navigator.userAgent : "";
var IS_IOS = /iPhone|iPad/.test(ua$1);
var CONTAINER_CLASS_NAME = "infinitegrid-container";
var IGNORE_PROPERITES_MAP = {
renderOnPropertyChange: true,
useFit: true,
autoResize: true
};
var INFINITEGRID_PROPERTY_TYPES = __assign({}, GRID_PROPERTY_TYPES);
var DIRECTION = {
START: "start",
END: "end",
NONE: ""
};
var INFINITEGRID_EVENTS = {
CHANGE_SCROLL: "changeScroll",
REQUEST_APPEND: "requestAppend",
REQUEST_PREPEND: "requestPrepend",
RENDER_COMPLETE: "renderComplete",
CONTENT_ERROR: "contentError"
}; // type?: ITEM_TYPE;
// groupKey?: string | number;
// key?: string | number;
// element?: HTMLElement | null;
// html?: string;
// data?: Record<string, any>;
var ITEM_INFO_PROPERTIES = {
type: true,
groupKey: true,
key: true,
element: true,
html: true,
data: true
};
var INFINITEGRID_METHODS = ["updateItems", "getItems", "getVisibleItems", "getGroups", "getVisibleGroups", "renderItems", "getContainerElement", "getScrollContainerElement", "getWrapperElement", "setStatus", "getStatus", "removePlaceholders", "prependPlaceholders", "appendPlaceholders", "getStartCursor", "getEndCursor", "setCursors"];
var GROUP_TYPE;
(function (GROUP_TYPE) {
GROUP_TYPE[GROUP_TYPE["NORMAL"] = 0] = "NORMAL";
GROUP_TYPE[GROUP_TYPE["VIRTUAL"] = 1] = "VIRTUAL";
GROUP_TYPE[GROUP_TYPE["LOADING"] = 2] = "LOADING";
})(GROUP_TYPE || (GROUP_TYPE = {}));
var ITEM_TYPE;
(function (ITEM_TYPE) {
ITEM_TYPE[ITEM_TYPE["NORMAL"] = 0] = "NORMAL";
ITEM_TYPE[ITEM_TYPE["VIRTUAL"] = 1] = "VIRTUAL";
ITEM_TYPE[ITEM_TYPE["LOADING"] = 2] = "LOADING";
})(ITEM_TYPE || (ITEM_TYPE = {}));
var STATUS_TYPE;
(function (STATUS_TYPE) {
// does not remove anything.
STATUS_TYPE[STATUS_TYPE["NOT_REMOVE"] = 0] = "NOT_REMOVE"; // Minimize information on invisible items
STATUS_TYPE[STATUS_TYPE["MINIMIZE_INVISIBLE_ITEMS"] = 1] = "MINIMIZE_INVISIBLE_ITEMS"; // Minimize information on invisible groups
STATUS_TYPE[STATUS_TYPE["MINIMIZE_INVISIBLE_GROUPS"] = 2] = "MINIMIZE_INVISIBLE_GROUPS"; // remove invisible groups
STATUS_TYPE[STATUS_TYPE["REMOVE_INVISIBLE_GROUPS"] = 3] = "REMOVE_INVISIBLE_GROUPS";
})(STATUS_TYPE || (STATUS_TYPE = {}));
var INVISIBLE_POS = -9999;
/**
* @extends Grid.GridItem
*/
var InfiniteGridItem =
/*#__PURE__*/
function (_super) {
__extends(InfiniteGridItem, _super);
function InfiniteGridItem(horizontal, itemStatus) {
var _this = _super.call(this, horizontal, __assign({
html: "",
type: ITEM_TYPE.NORMAL,
cssRect: {
top: INVISIBLE_POS,
left: INVISIBLE_POS
}
}, itemStatus)) || this;
if (_this.type === ITEM_TYPE.VIRTUAL) {
if (_this.rect.width || _this.rect.height) {
_this.mountState = MOUNT_STATE.UNMOUNTED;
}
var orgRect = _this.orgRect;
var rect = _this.rect;
var cssRect = _this.cssRect;
if (cssRect.width) {
rect.width = cssRect.width;
} else if (orgRect.width) {
rect.width = orgRect.width;
}
if (cssRect.height) {
rect.height = cssRect.height;
} else if (orgRect.height) {
rect.height = orgRect.height;
}
}
return _this;
}
var __proto = InfiniteGridItem.prototype;
__proto.getVirtualStatus = function () {
return {
type: ITEM_TYPE.VIRTUAL,
groupKey: this.groupKey,
key: this.key,
orgRect: this.orgRect,
rect: this.rect,
cssRect: this.cssRect,
attributes: this.attributes
};
};
__proto.getMinimizedStatus = function () {
var status = __assign(__assign({}, _super.prototype.getMinimizedStatus.call(this)), {
type: ITEM_TYPE.NORMAL,
groupKey: this.groupKey
});
if (this.html) {
status.html = this.html;
}
return status;
};
return InfiniteGridItem;
}(GridItem);
var LOADING_GROUP_KEY = "__INFINITEGRID__LOADING_GRID";
var LOADING_ITEM_KEY = "__INFINITEGRID__LOADING_ITEM";
var LoadingGrid =
/*#__PURE__*/
function (_super) {
__extends(LoadingGrid, _super);
function LoadingGrid() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.type = "";
return _this;
}
var __proto = LoadingGrid.prototype;
__proto.getLoadingItem = function () {
return this.items[0] || null;
};
__proto.setLoadingItem = function (item) {
if (item) {
var loadingItem = this.getLoadingItem();
if (!loadingItem) {
this.items = [new InfiniteGridItem(this.options.horizontal, __assign(__assign({}, item), {
type: ITEM_TYPE.LOADING,
key: LOADING_ITEM_KEY
}))];
} else {
for (var name in item) {
loadingItem[name] = item[name];
}
}
} else {
this.items = [];
}
};
__proto.applyGrid = function (items, direction, outline) {
if (!items.length) {
return {
start: outline,
end: outline
};
}
var nextOutline = outline.length ? __spreadArrays(outline) : [0];
var item = items[0];
var offset = item.contentSize + this.gap;
item.cssInlinePos = this.getContainerInlineSize() / 2 - item.inlineSize / 2;
if (direction === "end") {
var maxPos = Math.max.apply(Math, nextOutline);
item.cssContentPos = maxPos;
return {
start: nextOutline,
end: nextOutline.map(function (pos) {
return pos + offset;
})
};
} else {
var minPos = Math.min.apply(Math, nextOutline);
item.cssContentPos = minPos - offset;
return {
start: nextOutline.map(function (pos) {
return pos - offset;
}),
end: nextOutline
};
}
};
return LoadingGrid;
}(Grid);
function isWindow$1(el) {
return el === window;
}
function isNumber$1(val) {
return typeof val === "number";
}
function isString$1(val) {
return typeof val === "string";
}
function isObject$1(val) {
return typeof val === "object";
}
function flat(arr) {
return arr.reduce(function (prev, cur) {
return __spreadArrays(prev, cur);
}, []);
}
function splitOptions(options) {
var gridOptions = options.gridOptions,
otherOptions = __rest(options, ["gridOptions"]);
return __assign(__assign({}, splitGridOptions(gridOptions)), otherOptions);
}
function splitGridOptions(options) {
var nextOptions = {};
var gridOptions = {};
var defaultOptions = Grid.defaultOptions;
for (var name in options) {
var value = options[name];
if (!(name in IGNORE_PROPERITES_MAP)) {
gridOptions[name] = value;
}
if (name in defaultOptions) {
nextOptions[name] = value;
}
}
return __assign(__assign({}, nextOptions), {
gridOptions: gridOptions
});
}
function categorize(items) {
var groups = [];
var groupKeys = {};
var registeredGroupKeys = {};
items.filter(function (item) {
return item.groupKey != null;
}).forEach(function (_a) {
var groupKey = _a.groupKey;
registeredGroupKeys[groupKey] = true;
});
var generatedGroupKey;
var isContinuousGroupKey = false;
items.forEach(function (item) {
if (item.groupKey != null) {
isContinuousGroupKey = false;
} else {
if (!isContinuousGroupKey) {
generatedGroupKey = makeKey(registeredGroupKeys);
isContinuousGroupKey = true;
registeredGroupKeys[generatedGroupKey] = true;
}
item.groupKey = generatedGroupKey;
}
var groupKey = item.groupKey;
var group = groupKeys[groupKey];
if (!group) {
group = {
groupKey: groupKey,
items: []
};
groupKeys[groupKey] = group;
groups.push(group);
}
group.items.push(item);
});
return groups;
}
function getNextCursors(prevKeys, nextKeys, prevStartCursor, prevEndCursor) {
var result = diff(prevKeys, nextKeys, function (key) {
return key;
});
var nextStartCursor = -1;
var nextEndCursor = -1; // sync cursors
result.maintained.forEach(function (_a) {
var prevIndex = _a[0],
nextIndex = _a[1];
if (prevStartCursor <= prevIndex && prevIndex <= prevEndCursor) {
if (nextStartCursor === -1) {
nextStartCursor = nextIndex;
nextEndCursor = nextIndex;
} else {
nextStartCursor = Math.min(nextStartCursor, nextIndex);
nextEndCursor = Math.max(nextEndCursor, nextIndex);
}
}
});
return {
startCursor: nextStartCursor,
endCursor: nextEndCursor
};
}
function splitVirtualGroups(groups, direction, nextGroups) {
var virtualGroups = [];
if (direction === "start") {
var index = findIndex(groups, function (group) {
return group.type === GROUP_TYPE.NORMAL;
});
if (index === -1) {
return [];
}
virtualGroups = groups.slice(0, index);
} else {
var index = findLastIndex(groups, function (group) {
return group.type === GROUP_TYPE.NORMAL;
});
if (index === -1) {
return [];
}
virtualGroups = groups.slice(index + 1);
}
var nextVirtualGroups = diff(virtualGroups, nextGroups, function (_a) {
var groupKey = _a.groupKey;
return groupKey;
}).removed.map(function (index) {
return virtualGroups[index];
}).reverse();
return nextVirtualGroups;
}
function getFirstRenderingItems(nextItems, horizontal) {
var groups = categorize(nextItems);
if (!groups[0]) {
return [];
}
return groups[0].items.map(function (item) {
return new InfiniteGridItem(horizontal, __assign({}, item));
});
}
function getRenderingItemsByStatus(groupManagerStatus, nextItems, usePlaceholder, horizontal) {
var prevGroups = groupManagerStatus.groups;
var groups = categorize(nextItems);
var startVirtualGroups = splitVirtualGroups(prevGroups, "start", groups);
var endVirtualGroups = splitVirtualGroups(prevGroups, "end", groups);
var nextGroups = __spreadArrays(startVirtualGroups, groups, endVirtualGroups);
var _a = getNextCursors(prevGroups.map(function (group) {
return group.groupKey;
}), nextGroups.map(function (group) {
return group.groupKey;
}), groupManagerStatus.cursors[0], groupManagerStatus.cursors[1]),
startCursor = _a.startCursor,
endCursor = _a.endCursor;
var nextVisibleItems = flat(nextGroups.slice(startCursor, endCursor + 1).map(function (group) {
return group.items.map(function (item) {
return new InfiniteGridItem(horizontal, __assign({}, item));
});
}));
if (!usePlaceholder) {
nextVisibleItems = nextVisibleItems.filter(function (item) {
return item.type !== ITEM_TYPE.VIRTUAL;
});
}
return nextVisibleItems;
}
function mountRenderingItems(items, options) {
var grid = options.grid,
usePlaceholder = options.usePlaceholder,
useLoading = options.useLoading,
useFirstRender = options.useFirstRender,
status = options.status;
if (!grid) {
return;
}
if (usePlaceholder) {
grid.setPlaceholder({});
}
if (useLoading) {
grid.setLoading({});
}
if (status) {
grid.setStatus(status, true);
}
grid.syncItems(items);
if (useFirstRender && !status && grid.getGroups().length) {
grid.setCursors(0, 0, true);
}
}
function getRenderingItems(items, options) {
var status = options.status,
usePlaceholder = options.usePlaceholder,
useLoading = options.useLoading,
horizontal = options.horizontal,
useFirstRender = options.useFirstRender,
grid = options.grid;
var visibleItems = [];
if (grid) {
grid.setPlaceholder(usePlaceholder ? {} : null);
grid.setLoading(useLoading ? {} : null);
grid.syncItems(items);
visibleItems = grid.getRenderingItems();
} else if (status) {
visibleItems = getRenderingItemsByStatus(status.groupManager, items, !!usePlaceholder, !!horizontal);
} else if (useFirstRender) {
visibleItems = getFirstRenderingItems(items, !!horizontal);
}
return visibleItems;
}
/* Class Decorator */
function InfiniteGridGetterSetter(component) {
var prototype = component.prototype,
propertyTypes = component.propertyTypes;
var _loop_1 = function (name) {
var attributes = {
enumerable: true,
configurable: true,
get: function () {
var options = this.groupManager.options;
if (name in options) {
return options[name];
} else {
return options.gridOptions[name];
}
},
set: function (value) {
var _a;
var prevValue = this.groupManager[name];
if (prevValue === value) {
return;
}
this.groupManager.gridOptions = (_a = {}, _a[name] = value, _a);
}
};
Object.defineProperty(prototype, name, attributes);
};
for (var name in propertyTypes) {
_loop_1(name);
}
}
function makeKey(registeredKeys) {
var index = 0; // eslint-disable-next-line no-constant-condition
while (true) {
var key = "infinitegrid_" + index++;
if (!(key in registeredKeys)) {
return key;
}
}
}
function convertHTMLtoElement(html) {
var dummy = document.createElement("div");
dummy.innerHTML = html;
return toArray$1(dummy.children);
}
function convertInsertedItems(items, groupKey) {
var insertedItems;
if (isString$1(items)) {
insertedItems = convertHTMLtoElement(items);
} else {
insertedItems = items;
}
return insertedItems.map(function (item) {
var element;
var html = "";
var key;
if (isString$1(item)) {
html = item;
} else if ("parentNode" in item) {
element = item;
html = item.outerHTML;
} else {
return __assign({
groupKey: groupKey
}, item);
}
return {
key: key,
groupKey: groupKey,
html: html,
element: element
};
});
}
function toArray$1(nodes) {
var array = [];
if (nodes) {
var length = nodes.length;
for (var i = 0; i < length; i++) {
array.push(nodes[i]);
}
}
return array;
}
function findIndex(arr, callback) {
var length = arr.length;
for (var i = 0; i < length; ++i) {
if (callback(arr[i], i)) {
return i;
}
}
return -1;
}
function findLastIndex(arr, callback) {
var length = arr.length;
for (var i = length - 1; i >= 0; --i) {
if (callback(arr[i], i)) {
return i;
}
}
return -1;
}
function getItemInfo(info) {
var nextInfo = {};
for (var name in info) {
if (name in ITEM_INFO_PROPERTIES) {
nextInfo[name] = info[name];
}
}
return nextInfo;
}
function setPlaceholder(item, info) {
for (var name in info) {
var value = info[name];
if (isObject$1(value)) {
item[name] = __assign(__assign({}, item[name]), value);
} else {
item[name] = info[name];
}
}
}
function isFlatOutline(start, end) {
return start.length === end.length && start.every(function (pos, i) {
return end[i] === pos;
});
}
function range$1(length) {
var arr = [];
for (var i = 0; i < length; ++i) {
arr.push(i);
}
return arr;
}
function flatGroups(groups) {
return flat(groups.map(function (_a) {
var grid = _a.grid;
return grid.getItems();
}));
}
function filterVirtuals(items, includePlaceholders) {
if (includePlaceholders) {
return items;
} else {
return items.filter(function (item) {
return item.type !== ITEM_TYPE.VIRTUAL;
});
}
}
/**
* Decorator that makes the method of InfiniteGrid available in the framework.
* @ko 프레임워크에서 InfiniteGrid의 메소드를 사용할 수 있게 하는 데코레이터.
* @private
* @example
* ```js
* import { withInfiniteGridMethods } from "@egjs/infinitegrid";
*
* class Grid extends React.Component<Partial<InfiniteGridProps & InfiniteGridOptions>> {
* @withInfiniteGridMethods
* private grid: NativeGrid;
* }
* ```
*/
var withInfiniteGridMethods = withMethods(INFINITEGRID_METHODS);
var GroupManager =
/*#__PURE__*/
function (_super) {
__extends(GroupManager, _super);
function GroupManager(container, options) {
var _this = _super.call(this, container, splitOptions(options)) || this;
_this.groupItems = [];
_this.groups = [];
_this.itemKeys = {};
_this.groupKeys = {};
_this.startCursor = 0;
_this.endCursor = 0;
_this._placeholder = null;
_this._loadingGrid = new LoadingGrid(container, {
externalContainerManager: _this.containerManager,
useFit: false,
autoResize: false,
renderOnPropertyChange: false,
gap: _this.gap
});
_this._mainGrid = _this._makeGrid();
return _this;
}
var __proto = GroupManager.prototype;
Object.defineProperty(__proto, "gridOptions", {
set: function (options) {
var _a = splitGridOptions(options),
gridOptions = _a.gridOptions,
otherOptions = __rest(_a, ["gridOptions"]);
var shouldRender = this._checkShouldRender(options);
this.options.gridOptions = __assign(__assign({}, this.options.gridOptions), gridOptions);
__spreadArrays([this._mainGrid], this.groups.map(function (_a) {
var grid = _a.grid;
return grid;
})).forEach(function (grid) {
for (var name in options) {
grid[name] = options[name];
}
});
for (var name in otherOptions) {
this[name] = otherOptions[name];
}
this._loadingGrid.gap = this.gap;
if (shouldRender) {
this.scheduleRender();
}
},
enumerable: false,
configurable: true
});
__proto.getItemByKey = function (key) {
return this.itemKeys[key] || null;
};
__proto.getGroupItems = function (includePlaceholders) {
return filterVirtuals(this.groupItems, includePlaceholders);
};
__proto.getVisibleItems = function (includePlaceholders) {
return filterVirtuals(this.items, includePlaceholders);
};
__proto.getRenderingItems = function () {
if (this.hasPlaceholder()) {
return this.items;
} else {
return this.items.filter(function (item) {
return item.type !== ITEM_TYPE.VIRTUAL;
});
}
};
__proto.getGroups = function (includePlaceholders) {
return filterVirtuals(this.groups, includePlaceholders);
};
__proto.hasVisibleVirtualGroups = function () {
return this.getVisibleGroups(true).some(function (group) {
return group.type === GROUP_TYPE.VIRTUAL;
});
};
__proto.hasPlaceholder = function () {
return !!this._placeholder;
};
__proto.hasLoadingItem = function () {
return !!this._getLoadingItem();
};
__proto.setPlaceholder = function (placeholder) {
this._placeholder = placeholder;
this._updatePlaceholder();
};
__proto.getLoadingType = function () {
return this._loadingGrid.type;
};
__proto.startLoading = function (type) {
this._loadingGrid.type = type;
this.items = this._getRenderingItems();
return true;
};
__proto.endLoading = function () {
var prevType = this._loadingGrid.type;
this._loadingGrid.type = "";
this.items = this._getRenderingItems();
return !!prevType;
};
__proto.setLoading = function (loading) {
this._loadingGrid.setLoadingItem(loading);
this.items = this._getRenderingItems();
};
__proto.getVisibleGroups = function (includePlaceholders) {
var groups = this.groups.slice(this.startCursor, this.endCursor + 1);
return filterVirtuals(groups, includePlaceholders);
};
__proto.getComputedOutlineLength = function (items) {
if (items === void 0) {
items = this.items;
}
return this._mainGrid.getComputedOutlineLength(items);
};
__proto.getComputedOutlineSize = function (items) {
if (items === void 0) {
items = this.items;
}
return this._mainGrid.getComputedOutlineSize(items);
};
__proto.applyGrid = function (items, direction, outline) {
var _this = this;
items.forEach(function (item) {
item.mountState = MOUNT_STATE.MOUNTED;
});
var renderingGroups = this.groups.slice();
if (!renderingGroups.length) {
return {
start: [],
end: []
};
}
var loadingGrid = this._loadingGrid;
if (loadingGrid.getLoadingItem()) {
if (loadingGrid.type === "start") {
renderingGroups.unshift(this._getLoadingGroup());
} else if (loadingGrid.type === "end") {
renderingGroups.push(this._getLoadingGroup());
}
}
var groups = renderingGroups.slice();
var nextOutline = outline;
if (direction === "start") {
groups.reverse();
}
var outlineLength = this.getComputedOutlineLength(items);
var outlineSize = this.getComputedOutlineSize(items);
groups.forEach(function (group) {
var grid = group.grid;
var gridItems = grid.getItems();
var isVirtual = group.type === GROUP_TYPE.VIRTUAL && !gridItems[0];
var appliedItems = gridItems.filter(function (item) {
return item.mountState !== MOUNT_STATE.UNCHECKED && item.rect.width;
});
var gridOutlines;
grid.outlineLength = outlineLength;
grid.outlineSize = outlineSize;
if (isVirtual) {
gridOutlines = _this._applyVirtualGrid(grid, direction, nextOutline);
} else if (appliedItems.length) {
gridOutlines = grid.applyGrid(appliedItems, direction, nextOutline);
} else {
gridOutlines = {
start: __spreadArrays(nextOutline),
end: __spreadArrays(nextOutline)
};
}
grid.setOutlines(gridOutlines);
nextOutline = gridOutlines[direction];
});
return {
start: renderingGroups[0].grid.getOutlines().start,
end: renderingGroups[renderingGroups.length - 1].grid.getOutlines().end
};
};
__proto.syncItems = function (nextItemInfos) {
var _this = this;
var prevItemKeys = this.itemKeys;
this.itemKeys = {};
var nextItems = this._syncItemInfos(nextItemInfos.map(function (info) {
return getItemInfo(info);
}), prevItemKeys);
var prevGroupKeys = this.groupKeys;
var nextManagerGroups = categorize(nextItems);
var startVirtualGroups = this._splitVirtualGroups("start", nextManagerGroups);
var endVirtualGroups = this._splitVirtualGroups("end", nextManagerGroups);
nextManagerGroups = __spreadArrays(startVirtualGroups, this._mergeVirtualGroups(nextManagerGroups), endVirtualGroups);
var nextGroups = nextManagerGroups.map(function (_a) {
var _b, _c;
var groupKey = _a.groupKey,
items = _a.items;
var isVirtual = !items[0] || items[0].type === ITEM_TYPE.VIRTUAL;
var grid = (_c = (_b = prevGroupKeys[groupKey]) === null || _b === void 0 ? void 0 : _b.grid) !== null && _c !== void 0 ? _c : _this._makeGrid();
var gridItems = isVirtual ? items : items.filter(function (_a) {
var type = _a.type;
return type === ITEM_TYPE.NORMAL;
});
grid.setItems(gridItems);
return {
type: isVirtual ? GROUP_TYPE.VIRTUAL : GROUP_TYPE.NORMAL,
groupKey: groupKey,
grid: grid,
items: gridItems,
renderItems: items
};
});
this._registerGroups(nextGroups);
};
__proto.renderItems = function (options) {
if (options === void 0) {
options = {};
}
if (options.useResize) {
this.groupItems.forEach(function (item) {
item.updateState = UPDATE_STATE.NEED_UPDATE;
});
var loadingItem = this._getLoadingItem();
if (loadingItem) {
loadingItem.updateState = UPDATE_STATE.NEED_UPDATE;
}
}
return _super.prototype.renderItems.call(this, options);
};
__proto.setCursors = function (startCursor, endCursor) {
this.startCursor = startCursor;
this.endCursor = endCursor;
this.items = this._getRenderingItems();
};
__proto.getStartCursor = function () {
return this.startCursor;
};
__proto.getEndCursor = function () {
return this.endCursor;
};
__proto.getGroupStatus = function (type) {
var orgStartCursor = this.startCursor;
var orgEndCursor = this.endCursor;
var orgGroups = this.groups;
var startCursor = orgStartCursor;
var endCursor = orgEndCursor;
var isMinimizeItems = type === STATUS_TYPE.MINIMIZE_INVISIBLE_ITEMS;
var isMinimizeGroups = type === STATUS_TYPE.MINIMIZE_INVISIBLE_GROUPS;
var groups;
if (type === STATUS_TYPE.REMOVE_INVISIBLE_GROUPS) {
groups = this.getVisibleGroups();
endCursor -= startCursor;
startCursor = 0;
} else {
groups = this.getGroups();
}
var groupStatus = groups.map(function (_a, i) {
var grid = _a.grid,
groupKey = _a.groupKey;
var isOutsideCursor = i < startCursor || endCursor < i;
var isVirtualItems = isMinimizeItems && isOutsideCursor;
var isVirtualGroup = isMinimizeGroups && isOutsideCursor;
var gridItems = grid.getItems();
var items = isVirtualGroup ? [] : gridItems.map(function (item) {
return isVirtualItems ? item.getVirtualStatus() : item.getMinimizedStatus();
});
return {
type: isVirtualGroup || isVirtualItems ? GROUP_TYPE.VIRTUAL : GROUP_TYPE.NORMAL,
groupKey: groupKey,
outlines: grid.getOutlines(),
items: items
};
});
var startGroup = orgGroups[orgStartCursor];
var endGroup = orgGroups[orgEndCursor];
var totalItems = this.getGroupItems();
var itemStartCursor = totalItems.indexOf(startGroup === null || startGroup === void 0 ? void 0 : startGroup.items[0]);
var itemEndCursor = totalItems.indexOf(endGroup === null || endGroup === void 0 ? void 0 : endGroup.items.slice().reverse()[0]);
return {
cursors: [startCursor, endCursor],
orgCursors: [orgStartCursor, orgEndCursor],
itemCursors: [itemStartCursor, itemEndCursor],
startGroupKey: startGroup === null || startGroup === void 0 ? void 0 : startGroup.groupKey,
endGroupKey: endGroup === null || endGroup === void 0 ? void 0 : endGroup.groupKey,
groups: groupStatus,
outlines: this.outlines
};
};
__proto.setGroupStatus = function (status) {
var _this = this;
this.itemKeys = {};
this.groupItems = [];
this.items = [];
var prevGroupKeys = this.groupKeys;
var nextGroups = status.groups.map(function (_a) {
var _b, _c;
var type = _a.type,
groupKey = _a.groupKey,
items = _a.items,
outlines = _a.outlines;
var nextItems = _this._syncItemInfos(items);
var grid = (_c = (_b = prevGroupKeys[groupKey]) === null || _b === void 0 ? void 0 : _b.grid) !== null && _c !== void 0 ? _c : _this._makeGrid();
grid.setOutlines(outlines);
grid.setItems(nextItems);
return {
type: type,
groupKey: groupKey,
grid: grid,
items: nextItems,
renderItems: nextItems
};
});
this.setOutlines(status.outlines);
this._registerGroups(nextGroups);
this._updatePlaceholder();
this.setCursors(status.cursors[0], status.cursors[1]);
};
__proto.appendPlaceholders = function (items, groupKey) {
return this.insertPlaceholders("end", items, groupKey);
};
__proto.prependPlaceholders = function (items, groupKey) {
return this.insertPlaceholders("start", items, groupKey);
};
__proto.removePlaceholders = function (type) {
var groups = this.groups;
var length = groups.length;
if (type === "start") {
var index = findIndex(groups, function (group) {
return group.type === GROUP_TYPE.NORMAL;
});
groups.splice(0, index);
} else if (type === "end") {
var index = findLastIndex(groups, function (group) {
return group.type === GROUP_TYPE.NORMAL;
});
groups.splice(index + 1, length - index - 1);
} else {
var groupKey_1 = type.groupKey;
var index = findIndex(groups, function (group) {
return group.groupKey === groupKey_1;
});
if (index > -1) {
groups.splice(index, 1);
}
}
this.syncItems(flatGroups(this.getGroups()));
};
__proto.insertPlaceholders = function (direction, items, groupKey) {
var _a, _b;
if (groupKey === void 0) {
groupKey = makeKey(this.groupKeys);
}
var infos = [];
if (isNumber$1(items)) {
infos = range$1(items).map(function () {
return {
type: ITEM_TYPE.VIRTUAL,
groupKey: groupKey
};
});
} else if (Array.isArray(items)) {
infos = items.map(function (status) {
return __assign(__assign({
groupKey: groupKey
}, status), {
type: ITEM_TYPE.VIRTUAL
});
});
}
var grid = this._makeGrid();
var nextItems = this._syncItemInfos(infos, this.itemKeys);
this._updatePlaceholder(nextItems);
grid.setItems(nextItems);
var group = {
type: GROUP_TYPE.VIRTUAL,
groupKey: groupKey,
grid: grid,
items: nextItems,
renderItems: nextItems
};
this.groupKeys[groupKey] = group;
if (direction === "end") {
this.groups.push(group);
(_a = this.groupItems).push.apply(_a, nextItems);
} else {
this.groups.splice(0, 0, group);
(_b = this.groupItems).splice.apply(_b, __spreadArrays([0, 0], nextItems));
if (this.startCursor > -1) {
++this.startCursor;
++this.endCursor;
}
}
return {
group: group,
items: nextItems
};
};
__proto.shouldRerenderItems = function () {
var isRerender = false;
this.getVisibleGroups().forEach(function (group) {
var items = group.items;
if (items.length === group.renderItems.length || items.every(function (item) {
return item.mountState === MOUNT_STATE.UNCHECKED;
})) {
return;
}
isRerender = true;
group.renderItems = __spreadArrays(items);
});
if (isRerender) {
this.items = this._getRenderingItems();
}
return isRerender;
};
__proto._getGroupItems = function () {
return flatGroups(this.getGroups(true));
};
__proto._getRenderingItems = function () {
var items = flat(this.getVisibleGroups(true).map(function (item) {
return item.renderItems;
}));
var loadingGrid = this._loadingGrid;
var loadingItem = loadingGrid.getLoadingItem();
if (loadingItem) {
if (loadingGrid.type === "end") {
items.push(loadingItem);
} else if (loadingGrid.type === "start") {
items.unshift(loadingItem);
}
}
return items;
};
__proto._checkShouldRender = function (options) {
var GridConstructor = this.options.gridConstructor;
var prevOptions = this.gridOptions;
var propertyTypes = GridConstructor.propertyTypes;
for (var name in prevOptions) {
if (!(name in options) && propertyTypes[name] === PROPERTY_TYPE.RENDER_PROPERTY) {
return true;
}
}
for (var name in options) {
if (prevOptions[name] !== options[name] && propertyTypes[name] === PROPERTY_TYPE.RENDER_PROPERTY) {
return true;
}
}
return false;
};
__proto._applyVirtualGrid = function (grid, direction, outline) {
var startOutline = outline.length ? __spreadArrays(outline) : [0];
var prevOutlines = grid.getOutlines();
var prevOutline = prevOutlines[direction === "end" ? "start" : "end"];
if (prevOutline.length !== startOutline.length || prevOutline.some(function (value, i) {
return value !== startOutline[i];
})) {
return {
start: __spreadArrays(startOutline),
end: __spreadArrays(startOutline)
};
}
return prevOutlines;
};
__proto._syncItemInfos = function (nextItemInfos, prevItemKeys) {
if (prevItemKeys === void 0) {
prevItemKeys = {};
}
var horizontal = this.options.horizontal;
var nextItemKeys = this.itemKeys;
nextItemInfos.filter(function (info) {
return info.key != null;
}).forEach(function (info) {
var key = info.key;
var prevItem = prevItemKeys[key];
if (!prevItem) {
nextItemKeys[key] = new InfiniteGridItem(horizontal, __assign({}, info));
} else if (prevItem.type === ITEM_TYPE.VIRTUAL && info.type !== ITEM_TYPE.VIRTUAL) {
nextItemKeys[key] = new InfiniteGridItem(horizontal, __assign({
orgRect: prevItem.orgRect,
rect: prevItem.rect
}, info));
} else {
if (info.data) {
prevItem.data = info.data;
}
nextItemKeys[key] = prevItem;
}
});
var nextItems = nextItemInfos.map(function (info) {
var key = info.key;
if (info.key == null) {
key = makeKey(nextItemKeys);
}
var item = nextItemKeys[key];
if (!item) {
var prevItem = prevItemKeys[key];
if (prevItem) {
item = prevItem;
if (info.data) {
item.data = info.data;
}
} else {
item = new InfiniteGridItem(horizontal, __assign(__assign({}, info), {
key: key
}));
}
nextItemKeys[key] = item;
}
return item;
});
return nextItems;
};
__proto._registerGroups = function (groups) {
var nextGroupKeys = {};
groups.forEach(function (group) {
nextGroupKeys[group.groupKey] = group;
});
this.groups = groups;
this.groupKeys = nextGroupKeys;
this.groupItems = this._getGroupItems();
};
__proto._splitVirtualGroups = function (direction, nextGroups) {
var groups = splitVirtualGroups(this.groups, direction, nextGroups);
var itemKeys = this.itemKeys;
groups.forEach(function (_a) {
var renderItems = _a.renderItems;
renderItems.forEach(function (item) {
itemKeys[item.key] = item;
});
});
return groups;
};
__proto._mergeVirtualGroups = function (groups) {
var itemKeys = this.itemKeys;
var groupKeys = this.groupKeys;
groups.forEach(function (group) {
var prevGroup = groupKeys[group.groupKey];
if (!prevGroup) {
return;
}
var items = group.items;
if (items.every(function (item) {
return item.mountState === MOUNT_STATE.UNCHECKED;
})) {
prevGroup.renderItems.forEach(function (item) {
if (item.type === ITEM_TYPE.VIRTUAL && !itemKeys[item.key]) {
items.push(item);
itemKeys[item.key] = item;
}
});
}
});
return groups;
};
__proto._updatePlaceholder = function (items) {
if (items === void 0) {
items = this.groupItems;
}
var placeholder = this._placeholder;
if (!placeholder) {
return;
}
items.filter(function (item) {
return item.type === ITEM_TYPE.VIRTUAL;
}).forEach(function (item) {
setPlaceholder(item, placeholder);
});
};
__proto._makeGrid = function () {
var GridConstructor = this.options.gridConstructor;
var gridOptions = this.gridOptions;
var container = this.containerElement;
return new GridConstructor(container, __assign(__assign({}, gridOptions), {
useFit: false,
autoResize: false,
renderOnPropertyChange: false,
externalContainerManager: this.containerManager,
externalItemRenderer: this.itemRenderer
}));
};
__proto._getLoadingGroup = function () {
var loadingGrid = this._loadingGrid;
var items = loadingGrid.getItems();
return {
groupKey: LOADING_GROUP_KEY,
type: GROUP_TYPE.NORMAL,
grid: loadingGrid,
items: items,
renderItems: items
};
};
__proto._getLoadingItem = function () {
return this._loadingGrid.getLoadingItem();
};
GroupManager.defaultOptions = __assign(__assign({}, Grid.defaultOptions), {
gridConstructor: null,
gridOptions: {}
});
GroupManager.propertyTypes = __assign(__assign({}, Grid.propertyTypes), {
gridConstructor: PROPERTY_TYPE.PROPERTY,
gridOptions: PROPERTY_TYPE.PROPERTY
});
GroupManager = __decorate([GetterSetter], GroupManager);
return GroupManager;
}(Grid);
var Infinite =
/*#__PURE__*/
function (_super) {
__extends(Infinite, _super);
function Infinite(options) {
var _this = _super.call(this) || this;
_this.startCursor = -1;
_this.endCursor = -1;
_this.size = 0;
_this.items = [];
_this.itemKeys = {};
_this.options = __assign({
threshold: 0,
useRecycle: true,
defaultDirection: "end"
}, options);
return _this;
}
var __proto = Infinite.prototype;
__proto.scroll = function (scrollPos) {
var prevStartCursor = this.startCursor;
var prevEndCursor = this.endCursor;
var items = this.items;
var length = items.length;
var size = this.size;
var _a = this.options,
defaultDirection = _a.defaultDirection,
threshold = _a.threshold,
useRecycle = _a.useRecycle;
var isDirectionEnd = defaultDirection === "end";
if (!length) {
this.trigger(isDirectionEnd ? "requestAppend" : "requestPrepend", {
key: undefined,
isVirtual: false
});
return;
} else if (prevStartCursor === -1 || prevEndCursor === -1) {
var nextCursor = isDirectionEnd ? 0 : length - 1;
this.trigger("change", {
prevStartCursor: prevStartCursor,
prevEndCursor: prevEndCursor,
nextStartCursor: nextCursor,
nextEndCursor: nextCursor
});
return;
}
var endScrollPos = scrollPos + size;
var startEdgePos = Math.max.apply(Math, items[prevStartCursor].startOutline);
var endEdgePos = Math.min.apply(Math, items[prevEndCursor].endOutline);
var visibles = items.map(function (item) {
var startOutline = item.startOutline,
endOutline = item.endOutline;
if (!startOutline.length || !endOutline.length) {
return false;
}
var startPos = Math.min.apply(Math, startOutline);
var endPos = Math.max.apply(Math, endOutline);
if (startPos - threshold <= endScrollPos && scrollPos <= endPos + threshold) {
return true;
}
return false;
});
var hasStartItems = 0 < prevStartCursor;
var hasEndItems = prevEndCursor < length - 1;
var isStart = scrollPos <= startEdgePos + threshold;
var isEnd = endScrollPos >= endEdgePos - threshold;
var nextStartCursor = visibles.indexOf(true);
var nextEndCursor = visibles.lastIndexOf(true);
if (nextStartCursor === -1) {
nextStartCursor = prevStartCursor;
nextEndCursor = prevEndCursor;
}
if (!useRecycle) {
nextStartCursor = Math.min(nextStartCursor, prevStartCursor);
nextEndCursor = Math.max(nextEndCursor, prevEndCursor);
}
if (nextStartCursor === prevStartCursor && hasStartItems && isStart) {
nextStartCursor -= 1;
}
if (nextEndCursor === prevEndCursor && hasEndItems && isEnd) {
nextEndCursor += 1;
}
if (prevStartCursor !== nextStartCursor || prevEndCursor !== nextEndCursor) {
this.trigger("change", {
prevStartCursor: prevStartCursor,
prevEndCursor: prevEndCursor,
nextStartCursor: nextStartCursor,
nextEndCursor: nextEndCursor
});
return;
} else if (this._requestVirtualItems()) {
return;
} else if ((!isDirectionEnd || !isEnd) && isStart) {
this.trigger("requestPrepend", {
key: items[prevStartCursor].key,
isVirtual: false
});
} else if ((isDirectionEnd || !isStart) && isEnd) {
this.trigger("requestAppend", {
key: items[prevEndCursor].key,
isVirtual: false
});
}
};
/**
* @private
* Call the requestAppend or requestPrepend event to fill the virtual items.
* @ko virtual item을 채우기 위해 requestAppend 또는 requestPrepend 이벤트를 호출합니다.
* @return - Whether the event is called. <ko>이벤트를 호출했는지 여부.</ko>
*/
__proto._requestVirtualItems = function () {
var isDirectionEnd = this.options.defaultDirection === "end";
var items = this.items;
var totalVisibleItems = this.getVisibleItems();
var visibleItems = totalVisibleItems.filter(function (item) {
return !item.isVirtual;
});
var totalVisibleLength = totalVisibleItems.length;
var visibleLength = visibleItems.length;
var startCursor = this.getStartCursor();
var endCursor = this.getEndCursor();
if (visibleLength === totalVisibleLength) {
return false;
} else if (visibleLength) {
var startKey_1 = visibleItems[0].key;
var endKey_1 = visibleItems[visibleLength - 1].key;
var startIndex = findIndex(items, function (item) {
return item.key === startKey_1;
}) - 1;
var endIndex = findIndex(items, function (item) {
return item.key === endKey_1;
}) + 1;
var isEnd = endIndex <= endCursor;
var isStart = startIndex >= startCursor; // Fill the placeholder with the original item.
if ((isDirectionEnd || !isStart) && isEnd) {
this.trigger("requestAppend", {
key: endKey_1,
nextKey: items[endIndex].key,
isVirtual: true
});
return true;
} else if ((!isDirectionEnd || !isEnd) && isStart) {
this.trigger("requestPrepend", {
key: startKey_1,
nextKey: items[startIndex].key,
isVirtual: true
});
return true;
}
} else if (totalVisibleLength) {
var lastItem = totalVisibleItems[totalVisibleLength - 1];
if (isDirectionEnd) {
this.trigger("requestAppend", {
nextKey: totalVisibleItems[0].key,
isVirtual: true
});
} else {
this.trigger("requestPrepend", {
nextKey: lastItem.key,
isVirtual: true
});
}
return true;
}
return false;
};
__proto.setCursors = function (startCursor, endCursor) {
this.startCursor = startCursor;
this.endCursor = endCursor;
};
__proto.setSize = function (size) {
this.size = size;
};
__proto.getStartCursor = function () {
return this.startCursor;
};
__proto.getEndCursor = function () {
return this.endCursor;
};
__proto.isLoading = function (direction) {
var startCursor = this.startCursor;
var endCursor = this.endCursor;
var items = this.items;
var firstItem = items[startCursor];
var lastItem = items[endCursor];
var length = items.length;
if (direction === DIRECTION.END && endCursor > -1 && endCursor < length - 1 && !lastItem.isVirtual && !isFlatOutline(lastItem.startOutline, lastItem.endOutline)) {
return false;
}
if (direction === DIRECTION.START && startCursor > 0 && !firstItem.isVirtual && !isFlatOutline(firstItem.startOutline, firstItem.endOutline)) {
return false;
}
return true;
};
__proto.setItems = function (nextItems) {
this.items = nextItems;
var itemKeys = {};
nextItems.forEach(function (item) {
itemKeys[item.key] = item;
});
this.itemKeys = itemKeys;
};
__proto.syncItems = function (nextItems) {
var prevItems = this.items;
var prevStartCursor = this.startCursor;
var prevEndCursor = this.endCursor;
var _a = getNextCursors(this.items.map(function (item) {
return item.key;
}), nextItems.map(function (item) {
return item.key;
}), prevStartCursor, prevEndCursor),
nextStartCursor = _a.startCursor,
nextEndCursor = _a.endCursor; // sync items between cursors
var isChange = nextEndCursor - nextStartCursor !== prevEndCursor - prevStartCursor || prevStartCursor === -1 || nextStartCursor === -1;
if (!isChange) {
var prevVisibleItems = prevItems.slice(prevStartCursor, prevEndCursor + 1);
var nextVisibleItems = nextItems.slice(nextStartCursor, nextEndCursor + 1);
var visibleResult = diff(prevVisibleItems, nextVisibleItems, function (item) {
return item.key;
});
isChange = visibleResult.added.length > 0 || visibleResult.removed.length > 0 || visibleResult.changed.length > 0;
}
this.setItems(nextItems);
this.setCursors(nextStartCursor, nextEndCursor);
return isChange;
};
__proto.getItems = function () {
return this.items;
};
__proto.getVisibleItems = function () {
var startCursor = this.startCursor;
var endCursor = this.endCursor;
if (startCursor === -1) {
return [];
}
return this.items.slice(startCursor, endCursor + 1);
};
__proto.getItemByKey = function (key) {
return this.itemKeys[key];
};
__proto.getRenderedVisibleItems = function () {
var items = this.getVisibleItems();
var rendered = items.map(function (_a) {
var startOutline = _a.startOutline,
endOutline = _a.endOutline;
var length = startOutline.length;
if (length === 0 || length !== endOutline.length) {
return false;
}
return startOutline.some(function (pos, i) {
return endOutline[i] !== pos;
});
});
var startIndex = rendered.indexOf(true);
var endIndex = rendered.lastIndexOf(true);
return endIndex === -1 ? [] : items.slice(startIndex, endIndex + 1);
};
__proto.destroy = function () {
this.off();
this.startCursor = -1;
this.endCursor = -1;
this.items = [];
this.size = 0;
};
return Infinite;
}(Component);
var Renderer =
/*#__PURE__*/
function (_super) {
__extends(Renderer, _super);
function Renderer() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.items = [];
_this.container = null;
_this.rendererKey = 0;
_this._updateTimer = 0;
_this._state = {};
_this._isItemChanged = false;
return _this;
}
var __proto = Renderer.prototype;
__proto.updateKey = function () {
this.rendererKey = Date.now();
};
__proto.getItems = function () {
return this.items;
};
__proto.setContainer = function (container) {
this.container = container;
};
__proto.render = function (nextItems, state) {
return this.syncItems(nextItems, state);
};
__proto.update = function (state) {
var _this = this;
if (state === void 0) {
state = {};
}
this._state = __assign(__assign({}, this._state), state);
this.trigger("update", {
state: state
});
clearTimeout(this._updateTimer);
this._updateTimer = window.setTimeout(function () {
_this.trigger("requestUpdate", {
state: state
});
});
};
__proto.updated = function (nextElements) {
var _a, _b;
if (nextElements === void 0) {
nextElements = (_b = (_a = this.container) === null || _a === void 0 ? void 0 : _a.children) !== null && _b !== void 0 ? _b : [];
}
var diffResult = this._diffResult;
var isChanged = !!(diffResult.added.length || diffResult.removed.length || diffResult.changed.length);
var state = this._state;
var isItemChanged = this._isItemChanged;
var nextItems = diffResult.list;
this._isItemChanged = false;
this._state = {};
this.items = nextItems;
nextItems.forEach(function (item, i) {
item.element = nextElements[i];
});
this.trigger("updated", {
items: nextItems,
elements: toArray$1(nextElements),
diffResult: this._diffResult,
state: state,
isItemChanged: isItemChanged,
isChanged: isChanged
});
return isChanged;
};
__proto.syncItems = function (items, state) {
if (state === void 0) {
state = {};
}
var rendererKey = this.rendererKey;
var prevItems = this.items;
var nextItems = items.map(function (item) {
return __assign(__assign({}, item), {
renderKey: rendererKey + "_" + item.key
});
});
var result = diff(prevItems, nextItems, function (item) {
return item.renderKey;
});
this._isItemChanged = !!result.added.length || !!result.removed.length || !!result.changed.length;
this._state = __assign(__assign({}, this._state), state);
this._diffResult = result;
return result;
};
__proto.destroy = function () {
this.off();
};
return Renderer;
}(Component);
var VanillaRenderer =
/*#__PURE__*/
function (_super) {
__extends(VanillaRenderer, _super);
function VanillaRenderer() {
return _super !== null && _super.apply(this, arguments) || this;
}
var __proto = VanillaRenderer.prototype;
__proto.render = function (nextItems, state) {
var container = this.container;
var result = _super.prototype.render.call(this, nextItems, state);
var prevList = result.prevList,
removed = result.removed,
ordered = result.ordered,
added = result.added,
list = result.list;
var diffList = __spreadArrays(prevList);
removed.forEach(function (index) {
diffList.splice(index, 1);
container.removeChild(prevList[index].element);
});
ordered.forEach(function (_a) {
var _b, _c;
var prevIndex = _a[0],
nextIndex = _a[1];
var item = diffList.splice(prevIndex, 1)[0];
diffList.splice(nextIndex, 0, item);
container.insertBefore(item.element, (_c = (_b = diffList[nextIndex + 1]) === null || _b === void 0 ? void 0 : _b.element) !== null && _c !== void 0 ? _c : null);
});
added.forEach(function (index) {
var _a, _b;
var item = list[index];
diffList.splice(index, 0, item);
container.insertBefore(item.element, (_b = (_a = diffList[index + 1]) === null || _a === void 0 ? void 0 : _a.element) !== null && _b !== void 0 ? _b : null);
});
this.updated(container.children);
return result;
};
return VanillaRenderer;
}(Renderer);
var VanillaGridRenderer =
/*#__PURE__*/
function (_super) {
__extends(VanillaGridRenderer, _super);
function VanillaGridRenderer() {
return _super !== null && _super.apply(this, arguments) || this;
}
var __proto = VanillaGridRenderer.prototype;
__proto.syncItems = function (nextItems) {
var result = _super.prototype.syncItems.call(this, nextItems);
var added = result.added,
list = result.list;
added.forEach(function (index) {
var orgItem = nextItems[index].orgItem;
if (orgItem.html && !orgItem.element) {
orgItem.element = convertHTMLtoElement(orgItem.html)[0];
}
list[index].element = orgItem.element;
});
return result;
};
return VanillaGridRenderer;
}(VanillaRenderer);
var ScrollManager =
/*#__PURE__*/
function (_super) {
__extends(ScrollManager, _super);
function ScrollManager(wrapper, options) {
var _this = _super.call(this) || this;
_this.wrapper = wrapper;
_this.prevScrollPos = null;
_this.scrollOffset = 0;
_this.contentSize = 0;
_this._isScrollIssue = IS_IOS;
_this._onCheck = function () {
var prevScrollPos = _this.getScrollPos();
var nextScrollPos = _this.getOrgScrollPos();
_this.setScrollPos(nextScrollPos);
if (prevScrollPos === null || _this._isScrollIssue && nextScrollPos === 0 || prevScrollPos === nextScrollPos) {
nextScrollPos && (_this._isScrollIssue = false);
return;
}
_this._isScrollIssue = false;
_this.trigger(new ComponentEvent$1("scroll", {
direction: prevScrollPos < nextScrollPos ? "end" : "start",
scrollPos: nextScrollPos,
relativeScrollPos: _this.getRelativeScrollPos()
}));
};
_this.options = __assign({
container: false,
containerTag: "div",
horizontal: false
}, options);
_this._init();
return _this;
}
var __proto = ScrollManager.prototype;
__proto.getWrapper = function () {
return this.wrapper;
};
__proto.getContainer = function () {
return this.container;
};
__proto.getScrollContainer = function () {
return this.scrollContainer;
};
__proto.getScrollOffset = function () {
return this.scrollOffset;
};
__proto.getContentSize = function () {
return this.contentSize;
};
__proto.getRelativeScrollPos = function () {
return (this.prevScrollPos || 0) - this.scrollOffset;
};
__proto.getScrollPos = function () {
return this.prevScrollPos;
};
__proto.setScrollPos = function (pos) {
this.prevScrollPos = pos;
};
__proto.getOrgScrollPos = function () {
var eventTarget = this.eventTarget;
var horizontal = this.options.horizontal;
var prop = "scroll" + (horizontal ? "Left" : "Top");
if (isWindow$1(eventTarget)) {
return window[horizontal ? "pageXOffset" : "pageYOffset"] || document.documentElement[prop] || document.body[prop];
} else {
return eventTarget[prop];
}
};
__proto.setStatus = function (status) {
this.contentSize = status.contentSize;
this.scrollOffset = status.scrollOffset;
this.prevScrollPos = status.prevScrollPos;
this.scrollTo(this.prevScrollPos);
};
__proto.getStatus = function () {
return {
contentSize: this.contentSize,
scrollOffset: this.scrollOffset,
prevScrollPos: this.prevScrollPos
};
};
__proto.scrollTo = function (pos) {
var eventTarget = this.eventTarget;
var horizontal = this.options.horizontal;
var _a = horizontal ? [pos, 0] : [0, pos],
x = _a[0],
y = _a[1];
if (isWindow$1(eventTarget)) {
eventTarget.scroll(x, y);
} else {
eventTarget.scrollLeft = x;
eventTarget.scrollTop = y;
}
};
__proto.scrollBy = function (pos) {
if (!pos) {
return;
}
var eventTarget = this.eventTarget;
var horizontal = this.options.horizontal;
var _a = horizontal ? [pos, 0] : [0, pos],
x = _a[0],
y = _a[1];
this.prevScrollPos += pos;
if (isWindow$1(eventTarget)) {
eventTarget.scrollBy(x, y);
} else {
eventTarget.scrollLeft += x;
eventTarget.scrollTop += y;
}
};
__proto.resize = function () {
var scrollContainer = this.scrollContainer;
var horizontal = this.options.horizontal;
var scrollContainerRect = scrollContainer === document.body ? {
top: 0,
left: 0
} : scrollContainer.getBoundingClientRect();
var containerRect = this.container.getBoundingClientRect();
this.scrollOffset = (this.prevScrollPos || 0) + (horizontal ? containerRect.left - scrollContainerRect.left : containerRect.top - scrollContainerRect.top);
this.contentSize = horizontal ? scrollContainer.offsetWidth : scrollContainer.offsetHeight;
};
__proto.destroy = function () {
var container = this.container;
this.eventTarget.removeEventListener("scroll", this._onCheck);
if (this._isCreateElement) {
var scrollContainer = this.scrollContainer;
var fragment_1 = document.createDocumentFragment();
var childNodes = toArray$1(container.childNodes);
scrollContainer.removeChild(container);
childNodes.forEach(function (childNode) {
fragment_1.appendChild(childNode);
});
scrollContainer.appendChild(fragment_1);
} else if (this.options.container) {
container.style.cssText = this._orgCSSText;
}
};
__proto._init = function () {
var _a;
var _b = this.options,
containerOption = _b.container,
containerTag = _b.containerTag,
horizontal = _b.horizontal;
var wrapper = this.wrapper;
var scrollContainer = wrapper;
var container = wrapper;
var containerCSSText = "";
if (!containerOption) {
scrollContainer = document.body;
containerCSSText = container.style.cssText;
} else {
if (containerOption instanceof HTMLElement) {
// Container that already exists
container = containerOption;
} else if (containerOption === true) {
// Create Container
container = document.createElement(containerTag);
container.style.position = "relative";
container.className = CONTAINER_CLASS_NAME;
var childNodes = toArray$1(scrollContainer.childNodes);
childNodes.forEach(function (childNode) {
container.appendChild(childNode);
});
scrollContainer.appendChild(container);
this._isCreateElement = true;
} else {
// Find Container by Selector
container = scrollContainer.querySelector(containerOption);
}
containerCSSText = container.style.cssText;
var style = scrollContainer.style;
_a = horizontal ? ["scroll", "hidden"] : ["hidden", "scroll"], style.overflowX = _a[0], style.overflowY = _a[1];
if (horizontal) {
container.style.height = "100%";
}
}
var eventTarget = scrollContainer === document.body ? window : scrollContainer;
eventTarget.addEventListener("scroll", this._onCheck);
this._orgCSSText = containerCSSText;
this.container = container;
this.scrollContainer = scrollContainer;
this.eventTarget = eventTarget;
this.resize();
this.setScrollPos(this.getOrgScrollPos());
};
return ScrollManager;
}(Component);
/**
* A module used to arrange items including content infinitely according to layout type. With this module, you can implement various layouts composed of different items whose sizes vary. It guarantees performance by maintaining the number of DOMs the module is handling under any circumstance
* @ko 콘텐츠가 있는 아이템을 레이아웃 타입에 따라 무한으로 배치하는 모듈. 다양한 크기의 아이템을 다양한 레이아웃으로 배치할 수 있다. 아이템의 개수가 계속 늘어나도 모듈이 처리하는 DOM의 개수를 일정하게 유지해 최적의 성능을 보장한다
* @extends Component
* @support {"ie": "9+(with polyfill)", "ch" : "latest", "ff" : "latest", "sf" : "latest", "edge" : "latest", "ios" : "7+", "an" : "4.X+"}
* @example
```html
<ul id="grid">
<li class="card">
<div>test1</div>
</li>
<li class="card">
<div>test2</div>
</li>
<li class="card">
<div>test3</div>
</li>
<li class="card">
<div>test4</div>
</li>
<li class="card">
<div>test5</div>
</li>
<li class="card">
<div>test6</div>
</li>
</ul>
<script>
import { MasonryInfiniteGrid } from "@egjs/infinitegrid";
var some = new MasonryInfiniteGrid("#grid").on("renderComplete", function(e) {
// ...
});
// If you already have items in the container, call "layout" method.
some.renderItems();
</script>
```
*/
var InfiniteGrid =
/*#__PURE__*/
function (_super) {
__extends(InfiniteGrid, _super);
/**
* @param - A base element for a module <ko>모듈을 적용할 기준 엘리먼트</ko>
* @param - The option object of the InfiniteGrid module <ko>eg.InfiniteGrid 모듈의 옵션 객체</ko>
*/
function InfiniteGrid(wrapper, options) {
var _this = _super.call(this) || this;
_this._waitType = "";
_this._onScroll = function (_a) {
var direction = _a.direction,
scrollPos = _a.scrollPos,
relativeScrollPos = _a.relativeScrollPos;
_this._scroll();
/**
* This event is fired when scrolling.
* @ko 스크롤하면 발생하는 이벤트이다.
* @event InfiniteGrid#changeScroll
* @param {InfiniteGrid.OnChangeScroll} e - The object of data to be sent to an event <ko>이벤트에 전달되는 데이터 객체</ko>
*/
_this.trigger(new ComponentEvent$1(INFINITEGRID_EVENTS.CHANGE_SCROLL, {
direction: direction,
scrollPos: scrollPos,
relativeScrollPos: relativeScrollPos
}));
};
_this._onChange = function (e) {
_this.setCursors(e.nextStartCursor, e.nextEndCursor);
};
_this._onRendererUpdated = function (e) {
if (!e.isChanged) {
_this._checkEndLoading();
_this._scroll();
return;
}
var renderedItems = e.items;
var _a = e.diffResult,
added = _a.added,
removed = _a.removed,
prevList = _a.prevList,
list = _a.list;
removed.forEach(function (index) {
var orgItem = prevList[index].orgItem;
if (orgItem.mountState !== MOUNT_STATE.UNCHECKED) {
orgItem.mountState = MOUNT_STATE.UNMOUNTED;
}
});
renderedItems.forEach(function (item) {
// set grid element
var gridItem = item.orgItem;
gridItem.element = item.element;
});
var horizontal = _this.options.horizontal;
var addedItems = added.map(function (index) {
var gridItem = list[index].orgItem;
var element = gridItem.element;
if (gridItem.type === ITEM_TYPE.VIRTUAL) {
var cssRect = __assign({}, gridItem.cssRect);
var rect = gridItem.rect;
if (!cssRect.width && rect.width) {
cssRect.width = rect.width;
}
if (!cssRect.height && rect.height) {
cssRect.height = rect.height;
} // virtual item
return new GridItem(horizontal, {
element: element,
cssRect: cssRect
});
}
return gridItem;
});
var _b = e.state,
isRestore = _b.isRestore,
isResize = _b.isResize;
_this.itemRenderer.renderItems(addedItems);
if (isRestore) {
_this._onRenderComplete({
mounted: added.map(function (index) {
return list[index].orgItem;
}),
updated: [],
isResize: false,
direction: _this.defaultDirection
});
}
if (!isRestore || isResize || e.isItemChanged) {
_this.groupManager.renderItems();
}
};
_this._onResize = function () {
_this.containerManager.setRect(_this.watcher.getRect());
_this._renderItems({
useResize: true
}, true);
};
_this._onRequestAppend = function (e) {
/**
* The event is fired when scrolling reaches the end or when data for a virtual group is required.
* @ko 스크롤이 끝에 도달하거나 virtual 그룹에 대한 데이터가 필요한 경우 이벤트가 발생한다.
* @event InfiniteGrid#requestAppend
* @param {InfiniteGrid.OnRequestAppend} e - The object of data to be sent to an event <ko>이벤트에 전달되는 데이터 객체</ko>
*/
_this._onRequestInsert(DIRECTION.END, INFINITEGRID_EVENTS.REQUEST_APPEND, e);
};
_this._onRequestPrepend = function (e) {
/**
* The event is fired when scrolling reaches the start or when data for a virtual group is required.
* @ko 스크롤이 끝에 도달하거나 virtual 그룹에 대한 데이터가 필요한 경우 이벤트가 발생한다.
* @event InfiniteGrid#requestPrepend
* @param {InfiniteGrid.OnRequestPrepend} e - The object of data to be sent to an event <ko>이벤트에 전달되는 데이터 객체</ko>
*/
_this._onRequestInsert(DIRECTION.START, INFINITEGRID_EVENTS.REQUEST_PREPEND, e);
};
_this._onContentError = function (_a) {
var element = _a.element,
target = _a.target,
item = _a.item,
update = _a.update;
/**
* The event is fired when scrolling reaches the start or when data for a virtual group is required.
* @ko 스크롤이 끝에 도달하거나 virtual 그룹에 대한 데이터가 필요한 경우 이벤트가 발생한다.
* @event InfiniteGrid#contentError
* @param {InfiniteGrid.OnContentError} e - The object of data to be sent to an event <ko>이벤트에 전달되는 데이터 객체</ko>
*/
_this.trigger(new ComponentEvent$1(INFINITEGRID_EVENTS.CONTENT_ERROR, {
element: element,
target: target,
item: item,
update: update,
remove: function () {
_this.removeByKey(item.key);
}
}));
};
_this._onRenderComplete = function (_a) {
var isResize = _a.isResize,
mounted = _a.mounted,
updated = _a.updated,
direction = _a.direction;
var infinite = _this.infinite;
var prevRenderedGroups = infinite.getRenderedVisibleItems();
var length = prevRenderedGroups.length;
var isDirectionEnd = direction === DIRECTION.END;
_this._syncInfinite();
if (length) {
var prevStandardGroup = prevRenderedGroups[isDirectionEnd ? 0 : length - 1];
var nextStandardGroup = infinite.getItemByKey(prevStandardGroup.key);
var offset = isDirectionEnd ? Math.min.apply(Math, nextStandardGroup.startOutline) - Math.min.apply(Math, prevStandardGroup.startOutline) : Math.max.apply(Math, nextStandardGroup.endOutline) - Math.max.apply(Math, prevStandardGroup.endOutline);
_this.scrollManager.scrollBy(offset);
}
/**
* This event is fired when the InfiniteGrid has completed rendering.
* @ko InfiniteGrid가 렌더링이 완료됐을 때 이벤트가 발생한다.
* @event InfiniteGrid#renderComplete
* @param {InfiniteGrid.OnRenderComplete} e - The object of data to be sent to an event <ko>이벤트에 전달되는 데이터 객체</ko>
*/
_this.trigger(new ComponentEvent$1(INFINITEGRID_EVENTS.RENDER_COMPLETE, {
isResize: isResize,
direction: direction,
mounted: mounted.filter(function (item) {
return item.type !== ITEM_TYPE.LOADING;
}),
updated: updated.filter(function (item) {
return item.type !== ITEM_TYPE.LOADING;
}),
startCursor: _this.getStartCursor(),
endCursor: _this.getEndCursor(),
items: _this.getVisibleItems(true),
groups: _this.getVisibleGroups(true)
}));
if (_this.groupManager.shouldRerenderItems()) {
_this._update();
} else {
_this._checkEndLoading();
_this._scroll();
}
};
_this.options = __assign(__assign(__assign({}, _this.constructor.defaultOptions), {
renderer: new VanillaGridRenderer().on("requestUpdate", function () {
return _this._render();
})
}), options);
var _a = _this.options,
gridConstructor = _a.gridConstructor,
containerTag = _a.containerTag,
container = _a.container,
renderer = _a.renderer,
threshold = _a.threshold,
useRecycle = _a.useRecycle,
gridOptions = __rest(_a, ["gridConstructor", "containerTag", "container", "renderer", "threshold", "useRecycle"]); // options.container === false, wrapper = container, scrollContainer = document.body
// options.container === true, wrapper = scrollContainer, container = wrapper's child
// options.container === string,
var horizontal = gridOptions.horizontal,
attributePrefix = gridOptions.attributePrefix,
useTransform = gridOptions.useTransform,
percentage = gridOptions.percentage,
isConstantSize = gridOptions.isConstantSize,
isEqualSize = gridOptions.isEqualSize,
autoResize = gridOptions.autoResize,
useResizeObserver = gridOptions.useResizeObserver,
resizeDebounce = gridOptions.resizeDebounce,
maxResizeDebounce = gridOptions.maxResizeDebounce;
var wrapperElement = isString$1(wrapper) ? document.querySelector(wrapper) : wrapper;
var scrollManager = new ScrollManager(wrapperElement, {
container: container,
containerTag: containerTag,
horizontal: horizontal
}).on({
scroll: _this._onScroll
});
var containerElement = scrollManager.getContainer();
var containerManager = new ContainerManager(containerElement, {
horizontal: horizontal,
autoResize: false
});
var watcher = new ResizeWatcher(wrapperElement, {
resizeDebounce: resizeDebounce,
maxResizeDebounce: maxResizeDebounce,
useWindowResize: autoResize,
useResizeObserver: autoResize && useResizeObserver,
watchDirection: useResizeObserver ? horizontal ? "height" : "width" : false
}).listen(_this._onResize);
var itemRenderer = new ItemRenderer({
attributePrefix: attributePrefix,
horizontal: horizontal,
useTransform: useTransform,
percentage: percentage,
isEqualSize: isEqualSize,
isConstantSize: isConstantSize
});
var infinite = new Infinite({
useRecycle: useRecycle,
threshold: threshold
}).on({
"change": _this._onChange,
"requestAppend": _this._onRequestAppend,
"requestPrepend": _this._onRequestPrepend
});
infinite.setSize(scrollManager.getContentSize());
var groupManager = new GroupManager(containerElement, {
gridConstructor: gridConstructor,
externalItemRenderer: itemRenderer,
externalContainerManager: containerManager,
gridOptions: gridOptions
});
groupManager.on({
"renderComplete": _this._onRenderComplete,
"contentError": _this._onContentError
});
renderer.setContainer(containerElement);
renderer.on("updated", _this._onRendererUpdated);
_this.watcher = watcher;
_this.itemRenderer = itemRenderer;
_this.groupManager = groupManager;
_this.wrapperElement = wrapperElement;
_this.scrollManager = scrollManager;
_this.containerManager = containerManager;
_this.infinite = infinite;
_this.watcher.resize();
_this.containerManager.setRect(_this.watcher.getRect());
return _this;
}
var __proto = InfiniteGrid.prototype;
InfiniteGrid_1 = InfiniteGrid;
/**
* Rearrange items to fit the grid and render them. When rearrange is complete, the `renderComplete` event is fired.
* @ko grid에 맞게 아이템을 재배치하고 렌더링을 한다. 배치가 완료되면 `renderComplete` 이벤트가 발생한다.
* @param - Options for rendering. <ko>렌더링을 하기 위한 옵션.</ko>
* @example
* ```ts
* import { MasonryInfiniteGrid } from "@egjs/infinitegrid";
* const grid = new MasonryInfiniteGrid();
*
* grid.on("renderComplete", e => {
* console.log(e);
* });
* grid.renderItems();
* ```
*/
__proto.renderItems = function (options) {
if (options === void 0) {
options = {};
}
this._renderItems(options);
return this;
};
/**
* Returns the wrapper element specified by the user.
* @ko 컨테이너 엘리먼트를 반환한다.
*/
__proto.getWrapperElement = function () {
return this.scrollManager.getWrapper();
};
/**
* Returns the container element corresponding to the scroll area.
* @ko 스크롤 영역에 해당하는 컨테이너 엘리먼트를 반환한다.
*/
__proto.getScrollContainerElement = function () {
return this.scrollManager.getScrollContainer();
};
/**
* Returns the container element containing item elements.
* @ko 아이템 엘리먼트들을 담긴 컨테이너 엘리먼트를 반환한다.
*/
__proto.getContainerElement = function () {
return this.scrollManager.getContainer();
};
/**
* When items change, it synchronizes and renders items.
* @ko items가 바뀐 경우 동기화를 하고 렌더링을 한다.
* @param - Options for rendering. <ko>렌더링을 하기 위한 옵션.</ko>
*/
__proto.syncItems = function (items) {
this.groupManager.syncItems(items);
this._syncGroups();
return this;
};
/**
* Change the currently visible groups.
* @ko 현재 보이는 그룹들을 바꾼다.
* @param - first index of visible groups. <ko>보이는 그룹의 첫번째 index.</ko>
* @param - last index of visible groups. <ko>보이는 그룹의 마지막 index.</ko>
* @param - Whether the first rendering has already been done. <ko>첫 렌더링이 이미 되어있는지 여부.</ko>
*/
__proto.setCursors = function (startCursor, endCursor, useFirstRender) {
this.groupManager.setCursors(startCursor, endCursor);
this.infinite.setCursors(startCursor, endCursor);
if (useFirstRender) {
this._syncItems();
} else {
this._update();
this._checkEndLoading();
}
return this;
};
/**
* Returns the first index of visible groups.
* @ko 보이는 그룹들의 첫번째 index를 반환한다.
*/
__proto.getStartCursor = function () {
return this.infinite.getStartCursor();
};
/**
* Returns the last index of visible groups.
* @ko 보이는 그룹들의 마지막 index를 반환한다.
*/
__proto.getEndCursor = function () {
return this.infinite.getEndCursor();
};
/**
* Add items at the bottom(right) of the grid.
* @ko 아이템들을 grid 아래(오른쪽)에 추가한다.
* @param - items to be added <ko>추가할 아이템들</ko>
* @param - The group key to be configured in items. It is automatically generated by default. <ko>추가할 아이템에 설정할 그룹 키. 생략하면 값이 자동으로 생성된다.</ko>
* @return - An instance of a module itself<ko>모듈 자신의 인스턴스</ko>
* @example
* ```js
* ig.append(`<div class="item">test1</div><div class="item">test2</div>`);
* ig.append([`<div class="item">test1</div>`, `<div class="item">test2</div>`]);
* ig.append([HTMLElement1, HTMLElement2]);
* ```
*/
__proto.append = function (items, groupKey) {
return this.insert(-1, items, groupKey);
};
/**
* Add items at the top(left) of the grid.
* @ko 아이템들을 grid 위(왼쪽)에 추가한다.
* @param - items to be added <ko>추가할 아이템들</ko>
* @param - The group key to be configured in items. It is automatically generated by default. <ko>추가할 아이템에 설정할 그룹 키. 생략하면 값이 자동으로 생성된다.</ko>
* @return - An instance of a module itself<ko>모듈 자신의 인스턴스</ko>
* @example
* ```ts
* ig.prepend(`<div class="item">test1</div><div class="item">test2</div>`);
* ig.prepend([`<div class="item">test1</div>`, `<div class="item">test2</div>`]);
* ig.prepend([HTMLElement1, HTMLElement2]);
* ```
*/
__proto.prepend = function (items, groupKey) {
return this.insert(0, items, groupKey);
};
/**
* Add items to a specific index.
* @ko 아이템들을 특정 index에 추가한다.
* @param - index to add <ko>추가하기 위한 index</ko>
* @param - items to be added <ko>추가할 아이템들</ko>
* @param - The group key to be configured in items. It is automatically generated by default. <ko>추가할 아이템에 설정할 그룹 키. 생략하면 값이 자동으로 생성된다.</ko>
* @return - An instance of a module itself<ko>모듈 자신의 인스턴스</ko>
* @example
* ```ts
* ig.insert(2, `<div class="item">test1</div><div class="item">test2</div>`);
* ig.insert(3, [`<div class="item">test1</div>`, `<div class="item">test2</div>`]);
* ig.insert(4, [HTMLElement1, HTMLElement2]);
* ```
*/
__proto.insert = function (index, items, groupKey) {
var nextItemInfos = this.groupManager.getGroupItems();
var itemInfos = convertInsertedItems(items, groupKey);
if (index === -1) {
nextItemInfos.push.apply(nextItemInfos, itemInfos);
} else {
nextItemInfos.splice.apply(nextItemInfos, __spreadArrays([index, 0], itemInfos));
}
return this.syncItems(nextItemInfos);
};
/**
* Returns the current state of a module such as location information. You can use the setStatus() method to restore the information returned through a call to this method.
* @ko 아이템의 위치 정보 등 모듈의 현재 상태 정보를 반환한다. 이 메서드가 반환한 정보를 저장해 두었다가 setStatus() 메서드로 복원할 수 있다
* @param - STATUS_TYPE.NOT_REMOVE = Get all information about items. STATUS_TYPE.REMOVE_INVISIBLE_ITEMS = Get information on visible items only. STATUS_TYPE.MINIMIZE_INVISIBLE_ITEMS = Compress invisible items. You can replace it with a placeholder. STATUS_TYPE.MINIMIZE_INVISIBLE_GROUPS = Compress invisible groups. <ko> STATUS_TYPE.NOT_REMOVE = 모든 아이템들의 정보를 가져온다. STATUS_TYPE.REMOVE_INVISIBLE_ITEMS = 보이는 아이템들의 정보만 가져온다. STATUS_TYPE.MINIMIZE_INVISIBLE_ITEMS = 안보이는 아이템들을 압축한다. placeholder로 대체가 가능하다. STATUS_TYPE.MINIMIZE_INVISIBLE_GROUPS = 안보이는 그룹을 압축한다.</ko>
*/
__proto.getStatus = function (type) {
return {
containerManager: this.containerManager.getStatus(),
itemRenderer: this.itemRenderer.getStatus(),
groupManager: this.groupManager.getGroupStatus(type),
scrollManager: this.scrollManager.getStatus()
};
};
/**
* You can set placeholders to restore status or wait for items to be added.
* @ko status 복구 또는 아이템 추가 대기를 위한 placeholder를 설정할 수 있다.
* @param - The placeholder status. <ko>placeholder의 status</ko>
*/
__proto.setPlaceholder = function (info) {
this.groupManager.setPlaceholder(info);
return this;
};
/**
* You can set placeholders to restore status or wait for items to be added.
* @ko status 복구 또는 아이템 추가 대기를 위한 placeholder를 설정할 수 있다.
* @param - The placeholder status. <ko>placeholder의 status</ko>
*/
__proto.setLoading = function (info) {
this.groupManager.setLoading(info);
return this;
};
/**
* Add the placeholder at the end.
* @ko placeholder들을 마지막에 추가한다.
* @param - Items that correspond to placeholders. If it is a number, it duplicates the number of copies. <ko>placeholder에 해당하는 아이템들. 숫자면 갯수만큼 복제를 한다.</ko>
* @param - The group key to be configured in items. It is automatically generated by default. <ko>추가할 아이템에 설정할 그룹 키. 생략하면 값이 자동으로 생성된다.</ko>
*/
__proto.appendPlaceholders = function (items, groupKey) {
var _this = this;
var result = this.groupManager.appendPlaceholders(items, groupKey);
this._syncGroups(true);
return __assign(__assign({}, result), {
remove: function () {
_this.removePlaceholders({
groupKey: result.group.groupKey
});
}
});
};
/**
* Add the placeholder at the start.
* @ko placeholder들을 처음에 추가한다.
* @param - Items that correspond to placeholders. If it is a number, it duplicates the number of copies. <ko>placeholder에 해당하는 아이템들. 숫자면 갯수만큼 복제를 한다.</ko>
* @param - The group key to be configured in items. It is automatically generated by default. <ko>추가할 아이템에 설정할 그룹 키. 생략하면 값이 자동으로 생성된다.</ko>
*/
__proto.prependPlaceholders = function (items, groupKey) {
var _this = this;
var result = this.groupManager.prependPlaceholders(items, groupKey);
this._syncGroups(true);
return __assign(__assign({}, result), {
remove: function () {
_this.removePlaceholders({
groupKey: result.group.groupKey
});
}
});
};
/**
* Remove placeholders
* @ko placeholder들을 삭제한다.
* @param type - Remove the placeholders corresponding to the groupkey. When "start" or "end", remove all placeholders in that direction. <ko>groupkey에 해당하는 placeholder들을 삭제한다. "start" 또는 "end" 일 때 해당 방향의 모든 placeholder들을 삭제한다.</ko>
*/
__proto.removePlaceholders = function (type) {
this.groupManager.removePlaceholders(type);
this._syncGroups(true);
};
/**
* Sets the status of the InfiniteGrid module with the information returned through a call to the getStatus() method.
* @ko getStatus() 메서드가 저장한 정보로 InfiniteGrid 모듈의 상태를 설정한다.
* @param - status object of the InfiniteGrid module. <ko>InfiniteGrid 모듈의 status 객체.</ko>
* @param - Whether the first rendering has already been done. <ko>첫 렌더링이 이미 되어있는지 여부.</ko>
*/
__proto.setStatus = function (status, useFirstRender) {
this.itemRenderer.setStatus(status.itemRenderer);
this.containerManager.setStatus(status.containerManager);
this.scrollManager.setStatus(status.scrollManager);
var groupManager = this.groupManager;
var prevInlineSize = this.containerManager.getInlineSize();
groupManager.setGroupStatus(status.groupManager);
this._syncInfinite();
this.infinite.setCursors(groupManager.getStartCursor(), groupManager.getEndCursor());
this._getRenderer().updateKey();
var state = {
isResize: this.containerManager.getInlineSize() !== prevInlineSize,
isRestore: true
};
if (useFirstRender) {
this._syncItems(state);
} else {
this._update(state);
}
return this;
};
/**
* Removes the group corresponding to index.
* @ko index에 해당하는 그룹을 제거 한다.
*/
__proto.removeGroupByIndex = function (index) {
var nextGroups = this.groupManager.getGroups();
return this.removeGroupByKey(nextGroups[index].groupKey);
};
/**
* Removes the group corresponding to key.
* @ko key에 해당하는 그룹을 제거 한다.
*/
__proto.removeGroupByKey = function (key) {
var nextItemInfos = this.groupManager.getItems();
var firstIndex = findIndex(nextItemInfos, function (item) {
return item.groupKey === key;
});
var lastIndex = findLastIndex(nextItemInfos, function (item) {
return item.groupKey === key;
});
if (firstIndex === -1) {
return this;
}
nextItemInfos.splice(firstIndex, lastIndex - firstIndex + 1);
return this.syncItems(nextItemInfos);
};
/**
* Removes the item corresponding to index.
* @ko index에 해당하는 아이템을 제거 한다.
*/
__proto.removeByIndex = function (index) {
var nextItemInfos = this.getItems(true);
nextItemInfos.splice(index, 1);
return this.syncItems(nextItemInfos);
};
/**
* Removes the item corresponding to key.
* @ko key에 해당하는 아이템을 제거 한다.
*/
__proto.removeByKey = function (key) {
var nextItemInfos = this.getItems(true);
var index = findIndex(nextItemInfos, function (item) {
return item.key === key;
});
return this.removeByIndex(index);
};
/**
* Update the size of the items and render them.
* @ko 아이템들의 사이즈를 업데이트하고 렌더링을 한다.
* @param - Items to be updated. <ko>업데이트할 아이템들.</ko>
* @param - Options for rendering. <ko>렌더링을 하기 위한 옵션.</ko>
*/
__proto.updateItems = function (items, options) {
if (options === void 0) {
options = {};
}
this.groupManager.updateItems(items, options);
return this;
};
/**
* Return all items of InfiniteGrid.
* @ko InfiniteGrid의 모든 아이템들을 반환한다.
* @param - Whether to include items corresponding to placeholders. <ko>placeholder에 해당하는 아이템들을 포함할지 여부.</ko>
*/
__proto.getItems = function (includePlaceholders) {
return this.groupManager.getGroupItems(includePlaceholders);
};
/**
* Return visible items of InfiniteGrid.
* @ko InfiniteGrid의 보이는 아이템들을 반환한다.
* @param - Whether to include items corresponding to placeholders. <ko>placeholder에 해당하는 아이템들을 포함할지 여부.</ko>
*/
__proto.getVisibleItems = function (includePlaceholders) {
return this.groupManager.getVisibleItems(includePlaceholders);
};
/**
* Return rendering items of InfiniteGrid.
* @ko InfiniteGrid의 렌더링 아이템들을 반환한다.
*/
__proto.getRenderingItems = function () {
return this.groupManager.getRenderingItems();
};
/**
* Return all groups of InfiniteGrid.
* @ko InfiniteGrid의 모든 그룹들을 반환한다.
* @param - Whether to include groups corresponding to placeholders. <ko>placeholder에 해당하는 그룹들을 포함할지 여부.</ko>
*/
__proto.getGroups = function (includePlaceholders) {
return this.groupManager.getGroups(includePlaceholders);
};
/**
* Return visible groups of InfiniteGrid.
* @ko InfiniteGrid의 보이는 그룹들을 반환한다.
* @param - Whether to include groups corresponding to placeholders. <ko>placeholder에 해당하는 그룹들을 포함할지 여부.</ko>
*/
__proto.getVisibleGroups = function (includePlaceholders) {
return this.groupManager.getVisibleGroups(includePlaceholders);
};
/**
* Set to wait to request data.
* @ko 데이터를 요청하기 위해 대기 상태로 설정한다.
* @param direction - direction in which data will be added. <ko>데이터를 추가하기 위한 방향.</ko>
*/
__proto.wait = function (direction) {
if (direction === void 0) {
direction = DIRECTION.END;
}
this._waitType = direction;
this._checkStartLoading(direction);
};
/**
* When the data request is complete, it is set to ready state.
* @ko 데이터 요청이 끝났다면 준비 상태로 설정한다.
*/
__proto.ready = function () {
this._waitType = "";
};
/**
* Returns whether it is set to wait to request data.
* @ko 데이터를 요청하기 위해 대기 상태로 설정되어 있는지 여부를 반환한다.
*/
__proto.isWait = function () {
return !!this._waitType;
};
/**
* Releases the instnace and events and returns the CSS of the container and elements.
* @ko 인스턴스와 이벤트를 해제하고 컨테이너와 엘리먼트들의 CSS를 되돌린다.
*/
__proto.destroy = function () {
this.off();
this.watcher.destroy();
this.groupManager.destroy();
this.scrollManager.destroy();
this.infinite.destroy();
};
__proto._getRenderer = function () {
return this.options.renderer;
};
__proto._getRendererItems = function () {
return this.getRenderingItems().map(function (item) {
return {
element: item.element,
key: item.type + "_" + item.key,
orgItem: item
};
});
};
__proto._syncItems = function (state) {
this._getRenderer().syncItems(this._getRendererItems(), state);
};
__proto._render = function (state) {
this._getRenderer().render(this._getRendererItems(), state);
};
__proto._update = function (state) {
if (state === void 0) {
state = {};
}
this._getRenderer().update(state);
};
__proto._resizeScroll = function () {
var scrollManager = this.scrollManager;
scrollManager.resize();
this.infinite.setSize(scrollManager.getContentSize());
};
__proto._syncGroups = function (isUpdate) {
var infinite = this.infinite;
this._syncInfinite();
this.groupManager.setCursors(infinite.getStartCursor(), infinite.getEndCursor());
if (isUpdate) {
this._update();
} else {
this._render();
}
};
__proto._syncInfinite = function () {
this.infinite.syncItems(this.getGroups(true).map(function (_a) {
var groupKey = _a.groupKey,
grid = _a.grid,
type = _a.type;
var outlines = grid.getOutlines();
return {
key: groupKey,
isVirtual: type === GROUP_TYPE.VIRTUAL,
startOutline: outlines.start,
endOutline: outlines.end
};
}));
};
__proto._scroll = function () {
this.infinite.scroll(this.scrollManager.getRelativeScrollPos());
};
__proto._onRequestInsert = function (direction, eventType, e) {
var _this = this;
if (this._waitType) {
this._checkStartLoading(this._waitType);
return;
}
this.trigger(new ComponentEvent$1(eventType, {
groupKey: e.key,
nextGroupKey: e.nextKey,
isVirtual: e.isVirtual,
wait: function () {
_this.wait(direction);
},
ready: function () {
_this.ready();
}
}));
};
__proto._renderItems = function (options, isTrusted) {
if (options === void 0) {
options = {};
}
if (!isTrusted && options.useResize) {
this.watcher.resize();
this.containerManager.resize();
}
this._resizeScroll();
if (!this.getRenderingItems().length) {
var children = toArray$1(this.getContainerElement().children);
if (children.length > 0) {
// no items, but has children
this.groupManager.syncItems(convertInsertedItems(children));
this._syncInfinite();
this.setCursors(0, 0, true);
this._getRenderer().updated();
} else {
this.infinite.scroll(0);
}
return this;
}
if (!this.getVisibleGroups(true).length) {
this.setCursors(0, 0);
} else {
this.groupManager.renderItems(options);
}
return this;
};
__proto._checkStartLoading = function (direction) {
var groupManager = this.groupManager;
var infinite = this.infinite;
if (!groupManager.getLoadingType() && infinite.isLoading(direction) && groupManager.startLoading(direction) && groupManager.hasLoadingItem()) {
this._update();
}
};
__proto._checkEndLoading = function () {
var groupManager = this.groupManager;
var loadingType = this.groupManager.getLoadingType();
if (loadingType && (!this._waitType || !this.infinite.isLoading(loadingType)) && groupManager.endLoading() && groupManager.hasLoadingItem()) {
this._update();
}
};
var InfiniteGrid_1;
InfiniteGrid.defaultOptions = __assign(__assign({}, DEFAULT_GRID_OPTIONS), {
container: false,
containerTag: "div",
renderer: null,
threshold: 100,
useRecycle: true
});
InfiniteGrid.propertyTypes = INFINITEGRID_PROPERTY_TYPES;
InfiniteGrid = InfiniteGrid_1 = __decorate([InfiniteGridGetterSetter], InfiniteGrid);
return InfiniteGrid;
}(Component);
/**
* MasonryInfiniteGrid is a grid that stacks items with the same width as a stack of bricks. Adjust the width of all images to the same size, find the lowest height column, and insert a new item.
* @ko MasonryInfiniteGrid는 벽돌을 쌓아 올린 모양처럼 동일한 너비를 가진 아이템을 쌓는 레이아웃이다. 모든 이미지의 너비를 동일한 크기로 조정하고, 가장 높이가 낮은 열을 찾아 새로운 이미지를 삽입한다. 따라서 배치된 아이템 사이에 빈 공간이 생기지는 않지만 배치된 레이아웃의 아래쪽은 울퉁불퉁해진다.
* @param {HTMLElement | string} container - A base element for a module <ko>모듈을 적용할 기준 엘리먼트</ko>
* @param {MasonryInfiniteGridOptions} options - The option object of the MasonryInfiniteGrid module <ko>MasonryInfiniteGrid 모듈의 옵션 객체</ko>
*/
var MasonryInfiniteGrid =
/*#__PURE__*/
function (_super) {
__extends(MasonryInfiniteGrid, _super);
function MasonryInfiniteGrid() {
return _super !== null && _super.apply(this, arguments) || this;
}
MasonryInfiniteGrid.propertyTypes = __assign(__assign({}, InfiniteGrid.propertyTypes), MasonryGrid.propertyTypes);
MasonryInfiniteGrid.defaultOptions = __assign(__assign(__assign({}, InfiniteGrid.defaultOptions), MasonryGrid.defaultOptions), {
gridConstructor: MasonryGrid
});
MasonryInfiniteGrid = __decorate([InfiniteGridGetterSetter], MasonryInfiniteGrid);
return MasonryInfiniteGrid;
}(InfiniteGrid);
/**
* 'justified' is a printing term with the meaning that 'it fits in one row wide'. JustifiedInfiniteGrid is a grid that the item is filled up on the basis of a line given a size.
* If 'data-grid-inline-offset' or 'data-grid-content-offset' are set for item element, the ratio is maintained except for the offset value.
* If 'data-grid-maintained-target' is set for an element whose ratio is to be maintained, the item is rendered while maintaining the ratio of the element.
* @ko 'justified'는 '1행의 너비에 맞게 꼭 들어찬'이라는 의미를 가진 인쇄 용어다. JustifiedInfiniteGrid는 용어의 의미대로 너비가 주어진 사이즈를 기준으로 아이템가 가득 차도록 배치하는 Grid다.
* 아이템 엘리먼트에 'data-grid-inline-offset' 또는 'data-grid-content-offset'를 설정하면 offset 값을 제외하고 비율을 유지한다.
* 비율을 유지하고 싶은 엘리먼트에 'data-grid-maintained-target'을 설정한다면 해당 엘리먼트의 비율을 유지하면서 아이템이 렌더링이 된다.
* @param {HTMLElement | string} container - A base element for a module <ko>모듈을 적용할 기준 엘리먼트</ko>
* @param {JustifiedInfiniteGridOptions} options - The option object of the JustifiedInfiniteGrid module <ko>JustifiedInfiniteGrid 모듈의 옵션 객체</ko>
*/
var JustifiedInfiniteGrid =
/*#__PURE__*/
function (_super) {
__extends(JustifiedInfiniteGrid, _super);
function JustifiedInfiniteGrid() {
return _super !== null && _super.apply(this, arguments) || this;
}
JustifiedInfiniteGrid.propertyTypes = __assign(__assign({}, InfiniteGrid.propertyTypes), JustifiedGrid.propertyTypes);
JustifiedInfiniteGrid.defaultOptions = __assign(__assign(__assign({}, InfiniteGrid.defaultOptions), JustifiedGrid.defaultOptions), {
gridConstructor: JustifiedGrid
});
JustifiedInfiniteGrid = __decorate([InfiniteGridGetterSetter], JustifiedInfiniteGrid);
return JustifiedInfiniteGrid;
}(InfiniteGrid);
/**
* 'Frame' is a printing term with the meaning that 'it fits in one row wide'. FrameInfiniteGrid is a grid that the item is filled up on the basis of a line given a size.
* @ko 'Frame'는 '1행의 너비에 맞게 꼭 들어찬'이라는 의미를 가진 인쇄 용어다. FrameInfiniteGrid는 용어의 의미대로 너비가 주어진 사이즈를 기준으로 아이템이 가득 차도록 배치하는 Grid다.
* @param {HTMLElement | string} container - A base element for a module <ko>모듈을 적용할 기준 엘리먼트</ko>
* @param {FrameInfiniteGridOptions} options - The option object of the FrameInfiniteGrid module <ko>FrameGrid 모듈의 옵션 객체</ko>
*/
var FrameInfiniteGrid =
/*#__PURE__*/
function (_super) {
__extends(FrameInfiniteGrid, _super);
function FrameInfiniteGrid() {
return _super !== null && _super.apply(this, arguments) || this;
}
FrameInfiniteGrid.propertyTypes = __assign(__assign({}, InfiniteGrid.propertyTypes), FrameGrid.propertyTypes);
FrameInfiniteGrid.defaultOptions = __assign(__assign(__assign({}, InfiniteGrid.defaultOptions), FrameGrid.defaultOptions), {
gridConstructor: FrameGrid
});
FrameInfiniteGrid = __decorate([InfiniteGridGetterSetter], FrameInfiniteGrid);
return FrameInfiniteGrid;
}(InfiniteGrid);
/**
* The PackingInfiniteGrid is a grid that shows the important items bigger without sacrificing the weight of the items.
* Rows and columns are separated so that items are dynamically placed within the horizontal and vertical space rather than arranged in an orderly fashion.
* If `sizeWeight` is higher than `ratioWeight`, the size of items is preserved as much as possible.
* Conversely, if `ratioWeight` is higher than `sizeWeight`, the ratio of items is preserved as much as possible.
* @ko PackingInfiniteGrid는 아이템의 본래 크기에 따른 비중을 해치지 않으면서 중요한 카드는 더 크게 보여 주는 레이아웃이다.
* 행과 열이 구분돼 아이템을 정돈되게 배치하는 대신 가로세로 일정 공간 내에서 동적으로 아이템을 배치한다.
* `sizeWeight`가 `ratioWeight`보다 높으면 아이템들의 size가 최대한 보존이 된다.
* 반대로 `ratioWeight`가 `sizeWeight`보다 높으면 아이템들의 비율이 최대한 보존이 된다.
* @param {HTMLElement | string} container - A base element for a module <ko>모듈을 적용할 기준 엘리먼트</ko>
* @param {PackingInfiniteGridOptions} options - The option object of the PackingInfiniteGrid module <ko>PackingInfiniteGrid 모듈의 옵션 객체</ko>
*/
var PackingInfiniteGrid =
/*#__PURE__*/
function (_super) {
__extends(PackingInfiniteGrid, _super);
function PackingInfiniteGrid() {
return _super !== null && _super.apply(this, arguments) || this;
}
PackingInfiniteGrid.propertyTypes = __assign(__assign({}, InfiniteGrid.propertyTypes), PackingGrid.propertyTypes);
PackingInfiniteGrid.defaultOptions = __assign(__assign(__assign({}, InfiniteGrid.defaultOptions), PackingGrid.defaultOptions), {
gridConstructor: PackingGrid
});
PackingInfiniteGrid = __decorate([InfiniteGridGetterSetter], PackingInfiniteGrid);
return PackingInfiniteGrid;
}(InfiniteGrid);
var modules = {
__proto__: null,
'default': InfiniteGrid,
withInfiniteGridMethods: withInfiniteGridMethods,
getRenderingItems: getRenderingItems,
mountRenderingItems: mountRenderingItems,
InfiniteGridItem: InfiniteGridItem,
MasonryInfiniteGrid: MasonryInfiniteGrid,
JustifiedInfiniteGrid: JustifiedInfiniteGrid,
FrameInfiniteGrid: FrameInfiniteGrid,
PackingInfiniteGrid: PackingInfiniteGrid,
Renderer: Renderer,
IS_IOS: IS_IOS,
CONTAINER_CLASS_NAME: CONTAINER_CLASS_NAME,
IGNORE_PROPERITES_MAP: IGNORE_PROPERITES_MAP,
INFINITEGRID_PROPERTY_TYPES: INFINITEGRID_PROPERTY_TYPES,
DIRECTION: DIRECTION,
INFINITEGRID_EVENTS: INFINITEGRID_EVENTS,
ITEM_INFO_PROPERTIES: ITEM_INFO_PROPERTIES,
INFINITEGRID_METHODS: INFINITEGRID_METHODS,
get GROUP_TYPE () { return GROUP_TYPE; },
get ITEM_TYPE () { return ITEM_TYPE; },
get STATUS_TYPE () { return STATUS_TYPE; },
INVISIBLE_POS: INVISIBLE_POS
};
for (var name in modules) {
InfiniteGrid[name] = modules[name];
}
return InfiniteGrid;
})));
//# sourceMappingURL=infinitegrid.js.map
|
/**
* QCObjects 2.3
* ________________
*
* Author: Jean Machuca <correojean@gmail.com>
*
* Cross Browser Javascript Framework for MVC Patterns
* QuickCorp/QCObjects is licensed under the
* GNU Lesser General Public License v3.0
* [LICENSE] (https://github.com/QuickCorp/QCObjects/blob/master/LICENSE.txt)
*
* Permissions of this copyleft license are conditioned on making available
* complete source code of licensed works and modifications under the same
* license or the GNU GPLv3. Copyright and license notices must be preserved.
* Contributors provide an express grant of patent rights. However, a larger
* work using the licensed work through interfaces provided by the licensed
* work may be distributed under different terms and without source code for
* the larger work.
*
* Copyright (C) 2015 Jean Machuca,<correojean@gmail.com>
*
* Everyone is permitted to copy and distribute verbatim copies of this
* license document, but changing it is not allowed.
*/
/*eslint no-unused-vars: "off"*/
/*eslint no-redeclare: "off"*/
/*eslint no-empty: "off"*/
/*eslint strict: "off"*/
/*eslint no-mixed-operators: "off"*/
(function(_top) {
"use strict";
var _protected_code_ = function(_) {
var __oldtoString = (typeof _.prototype !== "undefined") ? (_.prototype.toString) : (function() {
return "";
});
_.prototype.toString = function() {
var _protected_symbols = ["ComplexStorageCache",
"css",
"append",
"attachIn",
"debug",
"info",
"warn",
"QC_Append",
"set",
"get",
"done",
"componentDone",
"_new_",
"__new__",
"Class",
"ClassFactory",
"New",
"Export",
"Package",
"Import",
"subelements",
"componentLoader",
"buildComponents",
"Controller",
"View",
"VO",
"Service",
"serviceLoader",
"JSONService",
"ConfigService",
"SourceJS",
"SourceCSS",
"ArrayList",
"ArrayCollection",
"Effect",
"Timer",
"sum",
"avg",
"table",
"max",
"min",
"range",
"matrix",
"matrix2d",
"matrix3d",
"unique"
];
var _ret_;
if (_protected_symbols.includes(this.name)) {
_ret_ = this.name + "{ [QCObjects native code] }";
} else {
_ret_ = __oldtoString.call(this);
}
return _ret_;
};
};
(_protected_code_)(Function);
var _methods_ = function(_) {
var _m = [];
for (var i in _) {
if ((typeof _[i]).toLowerCase() === "function") {
_m.push(_[i]);
}
}
return _m;
};
String.prototype.__mAll__ = function (regex) {
// This is an alternative to old browsers that dont support String.prototype.matchAll
// https://github.com/tc39/proposal-string-matchall
var matches = [];
this.replace(regex, function () {
var match = Array.prototype.slice.call(arguments, 0, -2);
match.input = arguments[arguments.length - 1];
match.index = arguments[arguments.length - 2];
matches.push(match);
});
return matches;
};
if (typeof String.prototype.matchAll === "undefined"){
String.prototype.matchAll = String.prototype.__mAll__;
}
var isBrowser = typeof window !== "undefined" && typeof window.self !== "undefined" && window === window.self;
var _DOMCreateElement = function(elementName) {
var _ret_;
if (isBrowser) {
_ret_ = document.createElement(elementName);
} else {
_ret_ = {};
}
return _ret_;
};
if (!isBrowser) {
const fs = require("fs");
}
var _DataStringify = function(data) {
var getCircularReplacer = function() {
var seen = new WeakSet();
var _level = 0;
return function(key, value) {
if (typeof value === "object" && value !== null) {
if (seen.has(value)) {
_level += 1;
return (_level <= 3) ? (_LegacyCopy(value)) : (null);
}
seen.add(value);
}
return value;
};
};
return JSON.stringify(data, getCircularReplacer());
};
if (isBrowser) {
var _subelements = function subelements(selector) {
return [...this.querySelectorAll(selector)];
};
Element.prototype.subelements = _subelements;
HTMLDocument.prototype.subelements = _subelements;
HTMLElement.prototype.subelements = _subelements;
if (typeof ShadowRoot !== "undefined"){
ShadowRoot.prototype.subelements = _subelements;
}
}
if (isBrowser) {
try {
_top = (typeof window.top !== "undefined") ? (window.top) : (window);
_top["_allowed_"] = true;
} catch (e) {
try {
_top = document;
_top["_allowed_"] = true;
} catch (e2) {
try {
_top = global;
_top["_allowed_"] = true;
} catch (e3) {
_top = {};
_top["_allowed_"] = true;
}
}
}
} else if (typeof global !== "undefined") {
_top = global;
}
var basePath = (
function() {
var _basePath = "";
if (isBrowser) {
var baseURI = _top.document.baseURI.split("?")[0].split("/");
baseURI.pop();
_basePath = baseURI.join("/") + "/";
} else {
var process;
try {
process = require("process");
} catch (e) {
// not a process module
}
if (typeof process !== "undefined") {
_basePath = `${process.cwd()}/`;
} else {
_basePath = "";
}
}
return _basePath;
}
)();
if (isBrowser) {
/**
* Polyfilling Promise
*/
if (!("Promise" in _top)) {
_top.Promise = function(_f) {
var _p = {
then: function() {},
catch: function() {},
_then: function(response) {
this.then.call(_p, response);
},
_catch: function(response) {
this.catch.call(_p, response);
}
};
_f.call(_p, _p._then, _p._catch);
return _p;
};
}
if (typeof _top.console === "undefined") {
_top.console = function() {};
_top.console.prototype.log = function(message) {};
}
var domain = (
function() {
return (typeof document !== "undefined" && document.domain !== "") ? (document.domain) : ("localhost");
}
)();
var _secretKey = (
function() {
var __secretKey = _top[(![] + [])[((+!+[]) + (+!+[]))] + (typeof ![])[(+!+[])] + (typeof [])[((+!+[]) + (+!+[])) * ((+!+[]) + (+!+[]))] + (![] + [])[(+!+[])] + (!![] + [])[(+[])] + ([] + [] + [][
[]
])[(+[+!+[] + [+[]]]) / ((+!+[]) + (+!+[]))] + (typeof ![])[(+!+[])] + ([] + [] + [][
[]
])[(+!+[])]]["h" + (typeof ![])[(+!+[])] + (![] + [])[(+!+[] + ((+!+[]) + (+!+[])))] + (!![] + [])[(+[])]].toLowerCase();
return __secretKey;
}
)();
var is_phonegap = (
function() {
return (typeof cordova !== "undefined") ? (true) : (false);
}
)();
} else {
// This is only for code integrity purpose using non-browser implementations
// like using node.js
var _secretKey = "secret";
var domain = "localhost";
}
_top._asyncLoad = [];
var asyncLoad = function(callback, args) {
var asyncCallback = {
"func": callback,
"args": args,
"dispatch": function() {
this.func.apply(null, this.args);
}
};
_top._asyncLoad.push(asyncCallback);
return asyncCallback;
};
if (isBrowser) {
var _fireAsyncLoad = function() {
if (document.readyState === "complete") {
_top._asyncLoad.map(function (fc){
fc.dispatch.call(fc);
});
}
};
document.onreadystatechange = _fireAsyncLoad;
} else if (typeof global !== "undefined") {
global._fireAsyncLoad = function() {
_top._asyncLoad.map(function (fc){
fc.dispatch.call(fc);
});
};
}
_top.asyncLoad = asyncLoad;
var Logger = function() {
return {
debugEnabled: true,
infoEnabled: true,
warnEnabled: true,
debug: function(message) {
if (this.debugEnabled) {
console.log("\x1b[35m%s\x1b[0m","[DEBUG] " + message);
}
},
info: function(message) {
if (this.infoEnabled) {
console.info("\x1b[33m%s\x1b[0m","[INFO] " + message);
}
},
warn: function(message) {
if (this.warnEnabled) {
console.warn("\x1b[31m%s\x1b[0m","[WARN] " + message);
}
}
};
};
var logger = new Logger();
logger.debugEnabled = false;
logger.infoEnabled = false;
_top.logger = logger;
var Base64 = {
_keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
encode: function(e) {
var t = "";
var n, r, i, s, o, u, a;
var f = 0;
e = Base64._utf8_encode(e);
while (f < e.length) {
n = e.charCodeAt(f++);
r = e.charCodeAt(f++);
i = e.charCodeAt(f++);
s = n >> 2;
o = (n & 3) << 4 | r >> 4;
u = (r & 15) << 2 | i >> 6;
a = i & 63;
if (isNaN(r)) {
u = a = 64;
} else if (isNaN(i)) {
a = 64;
}
t = t + this._keyStr.charAt(s) + this._keyStr.charAt(o) + this._keyStr.charAt(u) + this._keyStr.charAt(a);
}
return t;
},
decode: function(e) {
var t = "";
var n, r, i;
var s, o, u, a;
var f = 0;
e = e.replace(/[^A-Za-z0-9+/=]/g, "");
while (f < e.length) {
s = this._keyStr.indexOf(e.charAt(f++));
o = this._keyStr.indexOf(e.charAt(f++));
u = this._keyStr.indexOf(e.charAt(f++));
a = this._keyStr.indexOf(e.charAt(f++));
n = s << 2 | o >> 4;
r = (o & 15) << 4 | u >> 2;
i = (u & 3) << 6 | a;
t = t + String.fromCharCode(n);
if (u !== 64) {
t = t + String.fromCharCode(r);
}
if (a !== 64) {
t = t + String.fromCharCode(i);
}
}
t = Base64._utf8_decode(t);
return t;
},
_utf8_encode: function(e) {
e = e.replace(/rn/g, "n");
var t = "";
for (var n = 0; n < e.length; n++) {
var r = e.charCodeAt(n);
if (r < 128) {
t += String.fromCharCode(r);
} else if (r > 127 && r < 2048) {
t += String.fromCharCode(r >> 6 | 192);
t += String.fromCharCode(r & 63 | 128);
} else {
t += String.fromCharCode(r >> 12 | 224);
t += String.fromCharCode(r >> 6 & 63 | 128);
t += String.fromCharCode(r & 63 | 128);
}
}
return t;
},
_utf8_decode: function(e) {
var t = "";
var n = 0;
var r = 0;
var c1 = 0;
var c2 = 0;
var c3;
while (n < e.length) {
r = e.charCodeAt(n);
if (r < 128) {
t += String.fromCharCode(r);
n++;
} else if (r > 191 && r < 224) {
c2 = e.charCodeAt(n + 1);
t += String.fromCharCode((r & 31) << 6 | c2 & 63);
n += 2;
} else {
c2 = e.charCodeAt(n + 1);
c3 = e.charCodeAt(n + 2);
t += String.fromCharCode((r & 15) << 12 | (c2 & 63) << 6 | c3 & 63);
n += 3;
}
}
return t;
}
};
var waitUntil = function(func, exp) {
var _waitUntil = function(func, exp) {
var maxWaitCycles = 2000;
var _w = 0;
var _t = setInterval(function() {
if (exp.call()) {
clearInterval(_t);
func.call();
logger.debug("Ejecuting " + func.name + " after wait");
} else {
if (_w < maxWaitCycles) {
_w += 1;
logger.debug("WAIT UNTIL " + func.name + " is true, " + _w.toString() + " cycles");
} else {
logger.debug("Max execution time for " + func.name + " expression until true");
clearInterval(_t);
}
}
}, 1);
};
setTimeout(function() {
_waitUntil(func, exp);
}, 1);
};
var ComplexStorageCache = function(params) {
var object, load, alternate;
object = params.index;
load = params.load;
alternate = params.alternate;
var cachedObjectID = this.getID(object);
var cachedResponse = localStorage.getItem(cachedObjectID);
if (this.isEmpty(cachedResponse)) {
var cachedNewResponse = load.call(null, {
"cachedObjectID": cachedObjectID,
"cachedResponse": cachedResponse,
"cache": this
});
this.save(object, cachedNewResponse);
logger.debug("RESPONSE OF {{cachedObjectID}} CACHED".replace("{{cachedObjectID}}", cachedObjectID));
} else {
var alternateResponse = alternate.call(null, {
"cachedObjectID": cachedObjectID,
"cachedResponse": cachedResponse,
"cache": this
});
logger.debug("RESPONSE OF {{cachedObjectID}} IS ALREADY CACHED ".replace("{{cachedObjectID}}", cachedObjectID));
}
return this;
};
ComplexStorageCache.prototype.getItem = function(cachedObjectID) {
var retrievedObject = localStorage.getItem(cachedObjectID);
if (!this.isEmpty(retrievedObject)) {
return JSON.parse(retrievedObject);
} else {
return null;
}
};
ComplexStorageCache.prototype.setItem = function(cachedObjectID, value) {
localStorage.setItem(cachedObjectID, _DataStringify(value));
};
ComplexStorageCache.prototype.isEmpty = function(object) {
var r = false;
switch (true) {
case (typeof object === "undefined"):
case (typeof object === "string" && object === ""):
case (typeof object === "string" && object === "undefined"):
case (typeof object === "number" && object === 0):
case (object === null):
r = true;
break;
default:
r = false;
}
return r;
};
ComplexStorageCache.prototype.getID = function(object) {
var cachedObjectID = "cachedObject_" + Base64.encode(_DataStringify(object).replace(",", "_").replace("{", "_").replace("}", "_"));
return cachedObjectID;
};
ComplexStorageCache.prototype.save = function(object, cachedNewResponse) {
var cachedObjectID = this.getID(object);
logger.debug("CACHING THE RESPONSE OF {{cachedObjectID}} ".replace("{{cachedObjectID}}", cachedObjectID));
this.setItem(cachedObjectID, cachedNewResponse);
};
ComplexStorageCache.prototype.getCached = function(object) {
var cachedObjectID = this.getID(object);
return this.getItem(cachedObjectID);
};
ComplexStorageCache.prototype.clear = function() {
Object.keys(localStorage).filter ( function (k) {return k.startsWith("cachedObject_");} ).map ( function (c) {localStorage.removeItem(c);});
};
/**
* Detecting passive events feature
*
* https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md#feature-detection
**/
// Test via a getter in the options object to see if the passive property is accessed
if (isBrowser) {
var supportsPassive = false;
try {
var opts = Object.defineProperty({}, "passive", {
get: function() {
supportsPassive = true;
return supportsPassive;
}
});
window.addEventListener("testPassive", null, opts);
window.removeEventListener("testPassive", null, opts);
} catch (e) {}
var captureFalse = function() {
return (supportsPassive) ? ({
passive: true
}) : (false);
};
// Use our detect's results. passive applied if supported, capture will be false either way.
//elem.addEventListener('touchstart', fn, captureFalse);
}
/**
* Basic Type of all elements
*/
if (isBrowser){
Element.prototype.find = function(tag) {
var _oo = [];
var _tags = document.subelements(tag);
_tags.map(function (_tt,_t){
if ((typeof _tags[_t] !== "undefined") && _tags[_t].parentNode.tagName === this.parentNode.tagName) {
_oo.push(_Cast(_tt, (new Object())));
}
});
return _oo;
};
}
/**
* Primary instance ID of all objects
*/
var __instanceID;
// Adaptation of Production steps of ECMA-262, Edition 5, 15.2.3.5
// Reference: http://es5.github.io/#x15.2.3.5
var _Object_Create = (function() {
// make a safe reference to Object.prototype.hasOwnProperty
var hasOwn = Object.prototype.hasOwnProperty;
return function(O) {
// 1. If Type(O) is not Object or Null throw a TypeError exception.
if (typeof O !== "object") {
throw TypeError("Object prototype may only be an Object or null. The type is " + typeof(O));
}
// 2. Let obj be the result of creating a new object as if by the
// expression new Object() where Object is the standard built-in
// constructor with that name
// 3. Set the [[Prototype]] internal property of obj to O.
var QCObjects = function() {};
QCObjects.prototype = O;
var obj = new QCObjects();
// Let's not keep a stray reference to O...
// 4. If the argument Properties is present and not undefined, add
// own properties to obj as if by calling the standard built-in
// function Object.defineProperties with arguments obj and
// Properties.
if (arguments.length > 1) {
// Object.defineProperties does ToObject on its first argument.
var Properties = Object(arguments[1]);
for (var prop in Properties) {
if (hasOwn.call(Properties, prop)) {
obj[prop] = Properties[prop];
}
}
}
// 5. Return obj
return obj;
};
})();
// Object.assign Polyfilling
// Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign#Polyfill
if (typeof Object.assign !== "function") {
// Must be writable: true, enumerable: false, configurable: true
Object.defineProperty(Object, "assign", {
value: function assign(target, varArgs) { // .length of function is 2
"use strict";
if (target === null) { // TypeError if undefined or null
throw new TypeError("Cannot convert undefined or null to object");
}
var to = Object(target);
for (var index = 1; index < arguments.length; index++) {
var nextSource = arguments[index];
if (nextSource !== null) { // Skip over if undefined or null
for (var nextKey in nextSource) {
// Avoid bugs when hasOwnProperty is shadowed
if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
to[nextKey] = nextSource[nextKey];
}
}
}
}
return to;
},
writable: true,
configurable: true
});
}
var _LegacyCopy = function(obj) {
var _ret_;
switch (typeof obj) {
case "string":
_ret_ = obj;
break;
case "number":
_ret_ = obj;
break;
case "object":
_ret_ = Object.assign({}, obj);
break;
case "function":
_ret_ = Object.assign({}, obj);
break;
default:
break;
}
return _ret_;
};
var _QC_CLASSES = {};
var _QC_PACKAGES = {};
var _QC_PACKAGES_IMPORTED = [];
var _QC_READY_LISTENERS = [];
/**
* Returns the object or function name
*
* @param Object or function
*/
var ObjectName = function(o) {
var ret = "";
if (typeof o.constructor === "function") {
ret = o.constructor.name;
} else if (typeof o.constructor === "object") {
ret = o.constructor.toString().split(" ")[1].replace("]", "");
}
return ret;
};
/**
* Casts an object to another object class type
*
* @param {Object} obj_source
* @param {Object} obj_dest
*/
var _Cast = function(obj_source, obj_dest) {
for (var v in obj_source) {
if (typeof obj_source[v] !== "undefined") {
try {
obj_dest[v] = obj_source[v];
} catch (e) {
}
}
}
return obj_dest;
};
/**
* Casts an object to another object class type. Only properties
*
* @param {Object} obj_source
* @param {Object} obj_dest
*/
var _CastProps = function(obj_source, obj_dest) {
for (var v in obj_source) {
if (typeof obj_source[v] !== "undefined" && typeof obj_source[v] !== "function") {
try {
obj_dest[v] = obj_source[v];
} catch (e) {
}
} else if (typeof obj_source[v] === "function"){
try {
obj_dest[v] = obj_source[v].bind(obj_dest);
} catch (e) {
}
}
}
return obj_dest;
};
/**
* Internal use to determine the forbidden names for classes
* Reserved words
*
* @param {String} name
* @param {Object} type
* @param {Object} definition
*/
var __is__forbidden_name__ = function (){
return (["__proto__", "prototype", "Object", "Map", "defineProperty", "indexOf", "toString", "__instanceID"].indexOf(arguments[0])!== -1)?(true):(false);
};
/**
* Creates new object class of another object
*
* @param {String} name
* @param {Object} type
* @param {Object} definition
*/
var Class = function(name, type, definition) {
var o;
var name = arguments[0];
if (__is__forbidden_name__.call(this, name)){
throw new Error(`${name} is not an allowed word in the name of a class`);
}
if (isBrowser) {
var type = (arguments.length > 2) ? (arguments[1]) : (HTMLElement);
} else {
var type = (arguments.length > 2) ? (arguments[1]) : (Object);
}
var definition = (arguments.length > 2) ? (arguments[2]) : (
(arguments.length > 1) ? (arguments[1]) : ({})
);
if (typeof type === "undefined") {
if (isBrowser) {
type = HTMLElement; // defaults to HTMLElement type
} else {
type = Object;
}
} else {
definition = _Cast(
(typeof definition === "undefined") ? ({}) : (definition),
(typeof type["__definition"] !== "undefined") ? (_LegacyCopy(type.__definition)) : ({})
);
}
type = (type.hasOwnProperty.call(type,"prototype")) ? (type.prototype) : (_LegacyCopy(type));
if (typeof definition !== "undefined" && !definition.hasOwnProperty.call(definition,"__new__")) {
definition["__new__"] = function(properties) {
_CastProps(properties, this);
};
}
if (typeof definition !== "undefined" && !definition.hasOwnProperty.call(definition,"css")) {
definition["css"] = function QC_CSS3(_css) {
if (typeof this["body"] !== "undefined" && this["body"]["style"] !== "undefined") {
logger.debug("body style");
this["body"]["style"] = _Cast(_css, this["body"]["style"]);
}
};
}
if (typeof definition !== "undefined" && !definition.hasOwnProperty.call(definition,"hierarchy")) {
definition["hierarchy"] = function hierarchy() {
var __classType = function(o_c) {
return (o_c.hasOwnProperty.call(o_c,"__classType")) ? (o_c.__classType) : ((o_c.hasOwnProperty.call(o_c,"__definition")) ? (o_c.__definition.__classType) : (ObjectName(o_c)));
};
var __hierarchy = [];
__hierarchy.push(__classType(this));
if (this.hasOwnProperty.call(this,"__definition")) {
__hierarchy = __hierarchy.concat(this.__definition.hierarchy.call(this.__definition));
}
return __hierarchy;
};
}
if (typeof definition !== "undefined" && !definition.hasOwnProperty.call(definition,"append")) {
definition["append"] = function QC_Append() {
var child = (arguments.length > 0) ? (arguments[0]) : (this["body"]);
if (typeof this["body"] !== "undefined") {
logger.debug("append element");
if (arguments.lenght > 0) {
logger.debug("append to element");
this["body"].append(child);
if (typeof this["childs"] === "undefined") {
this["childs"] = [];
}
this["childs"].push(child);
} else {
if (isBrowser) {
logger.debug("append to body");
document.body.append(child);
}
}
}
};
}
if (typeof definition !== "undefined" && !definition.hasOwnProperty.call(definition,"attachIn")) {
definition["attachIn"] = function QC_AttachIn(tag) {
if (isBrowser) {
var tags = document.subelements(tag);
for (var i = 0, j = tags.length; i < j; i++) {
tags[i].append(this);
}
} else {
// not yet implemented.
}
};
}
// hack to prevent pre-population of __instanceID into the class definition
if (typeof definition !== "undefined" && definition.hasOwnProperty.call(definition,"__instanceID")){
delete definition.__instanceID;
}
o = _Object_Create(type, definition);
o["__definition"] = definition;
o["__definition"]["__classType"] = name;
_QC_CLASSES[name] = o;
_top[name] = _QC_CLASSES[name];
return _top[name];
};
Class.prototype.toString = function() {
return "Class(name, type, definition) { [QCObjects native code] }";
};
/**
* Returns the QCObjects Class Factory of a given ClassName
*
* @param {String} name
*/
var ClassFactory = function(className) {
var _classFactory;
if (className !== null && className.indexOf(".")>-1){
var packageName = className.split(".").slice(0,className.split(".").length-1).join(".");
var _className = className.split(".").slice(-1).join("");
var _package = Package(packageName);
var packageClasses = (typeof _package !== "undefined")?(_package.filter(classFactory=>{
return typeof classFactory !== "undefined"
&& classFactory.hasOwnProperty.call(classFactory,"__definition")
&& isQCObjects_Class(classFactory)
&& classFactory.__definition.__classType===_className
&& !classFactory.hasOwnProperty.call(classFactory,"__instanceID");}).reverse()):([]);
if (packageClasses.length>0){
_classFactory = packageClasses[0];
}
} else if (className !== null && _QC_CLASSES.hasOwnProperty.call(_QC_CLASSES,className)) {
_classFactory = _QC_CLASSES[className];
}
return _classFactory;
};
if (isBrowser) {
Element.prototype.append = function QC_Append(child) {
if (typeof child.__definition !== "undefined" && typeof child.__definition.__classType !== "undefined" && typeof child.body) {
this.appendChild(child.body);
} else {
this.appendChild(child);
}
};
/**
* A replacement for direct using of innerHTML
* use: [element].render('content') where 'content' is the string corresponding
* to the DOM to insert in the element
**/
Element.prototype.render = function QC_Render(content) {
var _self = this;
var _appendVDOM = function (_self,content){
if (typeof document.implementation.createHTMLDocument !== "undefined"){
var doc = document.implementation.createHTMLDocument("");
doc.innerHTML = content;
doc.body.subelements("*").map(function (element){
return _self.append(element);
});
}
};
if (typeof this.innerHTML !== "undefined"){
try {
this.innerHTML += content;
}catch (e){
_appendVDOM(_self,content);
}
} else {
_appendVDOM(_self,content);
}
};
}
/**
* Returns a method from a superior QCObjects Class
* It is useful for Class Inheritance in the _new_ and __new__ method constructors
* @example _super_('MySuperClass','MySuperMethod').call(this,params) #where this is the current instance and params are method parameters
*
* @param {String} className
* @param {String} classMethodName
* @param {Object} params
*/
var _super_ = function(className, classMethodName, params) {
return ClassFactory(className)[classMethodName];
};
_super_.prototype.toString = function() {
return "_super_(className,classMethodName,params) { [QCObjects native code] }";
};
/**
* Creates an object from a Class definition
*
* @param {QC_Object} o
* @param {Object} args
*/
var New = function(c, args) {
var args = (arguments.length > 1) ? (arguments[1]) : ({});
__instanceID = (typeof __instanceID === "undefined" || __instanceID === null) ? (0) : (__instanceID + 1);
var c_new = (typeof c === "undefined") ? (_Object_Create(({}).constructor.prototype, {})) : (_Object_Create(c.constructor.prototype, c.__definition));
c_new.__definition = _Cast({
"__instanceID": __instanceID
}, (typeof c !== "undefined") ? (c.__definition) : ({}));
c_new["__instanceID"] = __instanceID;
if (c_new.hasOwnProperty.call(c_new,"definition") && typeof c_new.__definition !== "undefined" && c_new.__definition !== null) {
c_new.__definition["__instanceID"] = __instanceID;
}
if (c_new.hasOwnProperty.call(c_new,"__new__")) {
if (typeof c_new !== "undefined" && !c_new.__definition.hasOwnProperty.call(c_new.__definition,"body")) {
try {
if (isBrowser) {
c_new["body"] = _Cast(c_new["__definition"], _DOMCreateElement(c_new.__definition.__classType));
c_new["body"]["style"] = _Cast(c_new.__definition, c_new["body"]["style"]);
} else {
c_new["body"] = {};
c_new["body"]["style"] = {};
}
} catch (e) {
c_new["body"] = {};
c_new["body"]["style"] = {};
}
} else if (c_new.__definition.hasOwnProperty.call(c_new.__definition,"body")) {
c_new["body"] = c_new.__definition.body;
}
c_new.__new__(args);
if (c_new.hasOwnProperty.call(c_new,"_new_")) {
c_new._new_(args);
}
}
return c_new;
};
New.prototype.toString = function() {
return "New(QCObjectsClassName, args) { [QCObjects native code] }";
};
var Export = function(f) {
if (isBrowser) {
try {
_top[f.name] = f;
window[f.name] = f;
} catch (e) {}
} else if (typeof global !== "undefined") {
if (!global.hasOwnProperty.call(global,f.name)) {
global[f.name] = f;
}
}
};
Export.prototype.toString = function() {
return "Export(function or symbol) { [QCObjects native code] }";
};
if (!isBrowser) {
var findPackageNodePath = function(packagename) {
const fs = require("fs");
var sdkPath = null;
try {
var sdkPaths = [
`${ClassFactory("CONFIG").get("projectPath")}${ClassFactory("CONFIG").get("relativeImportPath")}`,
`${ClassFactory("CONFIG").get("basePath")}${ClassFactory("CONFIG").get("relativeImportPath")}`,
`${ClassFactory("CONFIG").get("projectPath")}`,
`${ClassFactory("CONFIG").get("basePath")}`,
`${ClassFactory("CONFIG").get("relativeImportPath")}`,
`${process.cwd()}${ClassFactory("CONFIG").get("relativeImportPath")}`,
`${process.cwd()}/node_modules/` + packagename,
`${process.cwd()}/node_modules`,
`${process.cwd()}`,
"node_modules",
"./",
""
].concat(module.paths);
sdkPaths = sdkPaths.filter(p => {
return fs.existsSync(p + "/" + packagename);
});
if (sdkPaths.length > 0) {
sdkPath = sdkPaths[0];
logger.info(packagename + " is Installed.");
} else {
// logger.debug(packagename + ' is not in a standard path.');
}
} catch (e) {
// do nothing
console.log(e);
}
return sdkPath;
};
Export(findPackageNodePath);
}
Class("_Crypt", Object, {
last_string: "",
last_key: "",
construct: false,
_new_: function(o) {
var string = o["string"];
var key = (o.hasOwnProperty.call(o,"key")) ? (o["key"]) : (null);
this.__new__(o);
key = (key === null) ? (this.__instanceID) : (key);
this.last_key = key;
this.last_string = string;
this.construct = true;
},
_encrypt: function() {
var string = this.last_string;
var key = this.last_key;
var result = "";
var char;
var keychar;
for (var i = 0; i < string.length; i++) {
char = string.substr(i, 1);
keychar = key.substr((i % key.length) - 1, 1);
char = String.fromCharCode(char.charCodeAt(0) + keychar.charCodeAt(0));
result += char;
}
this.last_string = Base64.encode(result);
return this.last_string;
},
_decrypt: function() {
var string = this.last_string;
var key = this.last_key;
var result = "";
var char;
var keychar;
string = Base64.decode(string);
for (var i = 0; i < string.length; i++) {
char = string.substr(i, 1);
keychar = key.substr((i % key.length) - 1, 1);
char = String.fromCharCode(char.charCodeAt(0) - keychar.charCodeAt(0));
result += char;
}
this.last_string = result;
return this.last_string;
},
encrypt: function(string, key) {
var crypt = New(ClassFactory("_Crypt"), {
string: string,
key: (key !== "")?(key):("12345678ABC")
});
return crypt._encrypt();
},
decrypt: function(string, key) {
var crypt = New(ClassFactory("_Crypt"), {
string: string,
key: (key !== "")?(key):("12345678ABC")
});
return crypt._decrypt();
}
});
var _CryptObject = function(o) {
return ClassFactory("_Crypt").encrypt(_DataStringify(o), _secretKey);
};
var _DecryptObject = function(s) {
return JSON.parse(ClassFactory("_Crypt").decrypt(s, _secretKey));
};
Class("Processor", {
processors: {
"config": function (arg){
return CONFIG.get(arg,"");
},
"ENV": function(arg) {
return (typeof process !== "undefined")?(process.env[arg]):("");
},
"global": function (arg){
return (typeof global !== "undefined")?(global[arg]):("");
}
},
setProcessor: function (_proc_){
if (typeof _proc_ === "function" && _proc_.name !== ""){
this.processors[_proc_.name] = _proc_;
}
},
execute: function (processorName, args){
let processorHandler = this;
return processorHandler.processors[processorName].apply(processorHandler, args.split(","));
},
process: function(template) {
if (typeof template === "string"){
let processorHandler = this;
Object.keys(processorHandler.processors).map(function (funcName){
[...template.matchAll(new RegExp("\\$"+funcName+"\\((.*)\\).*","g"))].map(
function (procesorMatch){
var match0 = `$${funcName}(${procesorMatch[1]})`;
template = template.replace(match0,processorHandler.execute.call(processorHandler, funcName, procesorMatch[1]));
}
);
});
}
return template;
},
processObject: function (obj){
let __instance__ = this;
if (typeof obj === "object"){
Object.keys(obj).map(
function (_k){
if (typeof obj[_k] === "object" && !obj[_k].hasOwnProperty.call(obj[_k],"call")){
obj[_k] = __instance__.processObject(obj[_k]);
} else if (typeof obj[_k] === "string"){
obj[_k] = __instance__.process(obj[_k]);
}
}
);
} else if (typeof obj === "string"){
obj = __instance__.process(obj);
}
return obj;
}
});
Class("CONFIG", Object, {
_CONFIG: {
"relativeImportPath": "",
"remoteImportsPath": "",
"remoteSDKPath": "https://sdk.qcobjects.dev/",
"asynchronousImportsLoad": false,
"removePackageScriptAfterLoading":true,
"componentsBasePath": "",
"delayForReady": 0,
"preserveComponentBodyTag": false,
"overrideComponentTag": false,
"useConfigService": false,
"routingWay": "hash",
"useSDK": true,
"useLocalSDK": false,
"basePath": basePath
},
_CONFIG_ENC: null,
set: function(name, value) {
// hack to force update basePath from CONFIG
if (name === "basePath") {
basePath = value;
}
var _conf = (
function(config) {
if (config._CONFIG_ENC === null){
config._CONFIG_ENC = ClassFactory("_Crypt").encrypt(_DataStringify({}), _secretKey);
}
var _protectedEnc = config._CONFIG_ENC.valueOf();
var _protectedConf = config._CONFIG.valueOf();
return _CastProps(_protectedConf, _DecryptObject(_protectedEnc));
}
)(this);
_conf[name] = value;
this._CONFIG_ENC = _CryptObject(_conf);
if (this._CONFIG.hasOwnProperty.call(this._CONFIG,name)) {
this._CONFIG[name] = value;
}
},
get: function(name,_default) {
var _value;
try {
var _conf = (
function(config) {
if (config._CONFIG_ENC === null){
config._CONFIG_ENC = ClassFactory("_Crypt").encrypt(_DataStringify({}), _secretKey);
}
var _protectedEnc = config._CONFIG_ENC.valueOf();
var _protectedConf = config._CONFIG.valueOf();
return _CastProps(_protectedConf, _DecryptObject(_protectedEnc));
}
)(this);
if (typeof _conf[name] !== "undefined"){
_value = _conf[name];
} else if (typeof _default !== "undefined"){
_value = _default;
}
} catch (e){
logger.debug("Something wrong when trying to get CONFIG values");
logger.debug("No config value for: "+name);
_value = _default;
}
return ClassFactory("Processor").processObject.call(ClassFactory("Processor"),_value);
}
});
var CONFIG = ClassFactory("CONFIG");
Export(CONFIG);
Export(waitUntil);
Export(_super_);
Export(ComplexStorageCache);
Export(ClassFactory);
Export(_DOMCreateElement);
var isQCObjects_Object = function (_){
return (typeof _ === "object"
&& _.hasOwnProperty.call(_,"__classType")
&& _.hasOwnProperty.call(_,"__instanceID")
&& _.hasOwnProperty.call(_,"__definition")
&& typeof _.__definition !== "undefined"
)?(true):(false);
};
var isQCObjects_Class = function (_){
return (typeof _ === "object"
&& (!_.hasOwnProperty.call(_,"__instanceID"))
&& _.hasOwnProperty.call(_,"__definition")
&& typeof _.__definition !== "undefined"
&& _.__definition.hasOwnProperty.call(_.__definition,"__classType")
)?(true):(false);
};
/**
* Defines a package for Class classification
*
* @param {Object} namespace
* @param {Object} classes
*/
var Package = function(namespace, classes) {
if (_QC_PACKAGES.hasOwnProperty.call(_QC_PACKAGES,namespace) &&
typeof _QC_PACKAGES[namespace] !== "undefined" &&
_QC_PACKAGES[namespace].hasOwnProperty.call(_QC_PACKAGES[namespace],"length") &&
_QC_PACKAGES[namespace].length > 0 &&
typeof classes !== "undefined" &&
classes.hasOwnProperty.call(classes,"length") &&
classes.length > 0
) {
classes.filter(
function (_c1){
return isQCObjects_Class(_c1);
}
).map(function (_class_){
_class_.__definition.__namespace = namespace;
});
_QC_PACKAGES[namespace] = _QC_PACKAGES[namespace].concat(classes);
} else if (typeof classes !== "undefined"){
if (typeof classes === "object" && classes.hasOwnProperty.call(classes,"length")){
classes.filter(
function (_c1){
return isQCObjects_Class(_c1);
}
).map(function (_class_){
_class_.__definition.__namespace = namespace;
});
} else if (isQCObjects_Class(classes)) {
classes.__definition.__namespace = namespace;
}
_QC_PACKAGES[namespace] = classes;
}
return (_QC_PACKAGES.hasOwnProperty.call(_QC_PACKAGES,namespace))?(_QC_PACKAGES[namespace]):(undefined);
};
Package.prototype.toString = function() {
return "Package(namespace, classes) { [QCObjects native code] }";
};
/**
* Imports a script with the package nomenclature
*
* @param {Object} packagename
* @param {Object} ready
* @param {Boolean} external
*/
var Import = function() {
var packagename;
var ready = function() {};
var external = false;
if (arguments.length < 1) {
return;
} else if (arguments.length === 1) {
packagename = arguments[0];
} else if (arguments.length === 2) {
packagename = arguments[0];
ready = arguments[1];
} else if (arguments.length > 2) {
packagename = arguments[0];
ready = arguments[1];
external = arguments[2];
logger.debug("[Import] Setting external=" + external.toString() + " resource to import: " + packagename);
}
if (external) {
logger.debug("[Import] Registering external resource to import: " + packagename);
} else {
logger.debug("[Import] Registering local resource to import: " + packagename);
}
var _promise_import_;
if (isBrowser) {
_promise_import_ = new Promise(function(resolve, reject) {
var allPackagesImported = function() {
var ret = false;
var cp = 0;
for (var p in _QC_PACKAGES) {
cp++;
}
if (cp < _QC_PACKAGES_IMPORTED.length) {
ret = false;
} else {
ret = true;
}
return ret;
};
var readyImported = function(e) {
_QC_PACKAGES_IMPORTED.push(ready);
if (allPackagesImported()) {
_QC_PACKAGES_IMPORTED.map(function (_imported_){
_QC_READY_LISTENERS.push(_imported_);
});
}
if (isBrowser && ClassFactory("CONFIG").get("removePackageScriptAfterLoading")){
e.target.remove();
}
resolve.call(_promise_import_, {
"_imported_": e.target,
"_package_name_": packagename
});
};
if (!_QC_PACKAGES.hasOwnProperty.call(_QC_PACKAGES,packagename)) {
var s1 = _DOMCreateElement("script");
s1.type = ClassFactory("CONFIG").get("sourceType", "text/javascript");
s1.async = (ClassFactory("CONFIG").get("asynchronousImportsLoad")) ? (true) : (false);
s1.onreadystatechange = function() {
if (s1.readyState === "complete") {
readyImported.call();
}
};
s1.onload = readyImported;
s1.onerror = function(e) {
reject.call(_promise_import_, {
"_imported_": s1,
"_package_name_": packagename
});
};
s1.src = (external) ? (ClassFactory("CONFIG").get("remoteImportsPath") + packagename + ".js") : (basePath + ClassFactory("CONFIG").get("relativeImportPath") + packagename + ".js");
document.getElementsByTagName("head")[0].appendChild(s1);
}
});
_promise_import_.catch(function() {
logger.debug("Import: Error loading a package ");
});
} else {
// support to be used in a nodejs environment
_promise_import_ = new Promise(function(resolve, reject) {
try {
var standardNodePath = findPackageNodePath(packagename);
var packageAbsoluteName = "";
if (standardNodePath !== null) {
packageAbsoluteName = standardNodePath + "/" + packagename;
} else {
var jsNodePath = findPackageNodePath(packagename + ".js");
if (jsNodePath !== null) {
packageAbsoluteName = jsNodePath + "/" + packagename + ".js";
} else {
packageAbsoluteName = basePath + ClassFactory("CONFIG").get("relativeImportPath") + packagename;
}
}
try {
resolve.call(_promise_import_, {
"_imported_": require(`${packageAbsoluteName}`),
"_package_name_": packagename
});
}catch (e){
console.log(e);
reject.call(_promise_import_, {
"_imported_": null,
"_package_name_": packagename
});
}
} catch (e) {
console.log(e);
reject.call(_promise_import_, {
"_imported_": null,
"_package_name_": packagename
});
}
}).catch(function(e) {
// something wrong importing a package
console.log(e);
logger.debug("Something happened when importing " + packagename);
});
}
return _promise_import_;
};
Import.prototype.toString = function() {
return "Import(packagename,ready,external) { [QCObjects native code] }";
};
if (isBrowser) {
/**
* Adds a Cast functionality to every Element of DOM
*/
Element.prototype.Cast = function QC_Object(_o) {
_o.__definition.body = this;
var _o = New(_o);
return _o;
};
}
Class("TagElements", Array, {
show: function() {
this.map(function(element) {
return element.style.opacity = 1;
});
},
hide: function() {
this.map(function(element) {
return element.style.opacity = 0;
});
},
effect: function() {
var effectArguments = [...arguments].slice(1);
var effectClass = arguments[0];
if ((typeof effectClass).toLowerCase() === "string") {
effectClass = ClassFactory(effectClass);
}
this.map(function(element) {
return effectClass.apply.apply(effectClass, [element].concat(effectArguments));
});
},
findElements: function(elementName) {
var _o = New(ClassFactory("TagElements"));
if (isBrowser) {
for (var _k in this) {
if (typeof _k === "number" && typeof this[_k] !== "function" && this[_k].hasOwnProperty.call(this[_k],"subelements")) {
_o.push(this[_k].subelements(elementName));
}
}
} else {
// not yet implemented.
}
return _o;
}
});
/**
* Gets the element of DOM found by tag name
*
* @param {Object} tagname
* @param {Object} innerHTML
*/
var Tag = function(tagname, innerHTML) {
var _o = New(ClassFactory("TagElements"));
if (isBrowser) {
var o = document.subelements(tagname);
var addedKeys = [];
for (var _i = 0; _i < o.length; _i++) {
if (typeof innerHTML !== "undefined" && o[_i].hasOwnProperty.call(o[_i],"innerHTML")) {
o[_i].innerHTML = innerHTML;
}
if (addedKeys.indexOf(_i) < 0) {
_o.push(o[_i]);
addedKeys.push(_i);
}
}
} else {
// not yet implemented.
}
return _o;
};
/**
* Defines a Custom Ready listener
*/
function Ready(e) {
if (isBrowser) {
_QC_READY_LISTENERS.push(e.bind(window));
} else if (typeof global !== "undefined") {
_QC_READY_LISTENERS.push(e.bind(global));
}
}
var ready = Ready; // case insensitive ready option
/**
* Default Ready event function for window. Executes all micro ready events of Import calls
*
* @param {Object} e
*/
var _Ready = function(e) {
var _execReady = function() {
_QC_READY_LISTENERS.map(function (_ready_listener_,_r){
if (typeof _ready_listener_ === "function") {
_ready_listener_.call();
delete _QC_READY_LISTENERS[_r];
}
});
};
if (ClassFactory("CONFIG").get("delayForReady") > 0) {
if (isBrowser) {
setTimeout(_execReady.bind(window), ClassFactory("CONFIG").get("delayForReady"));
} else if (typeof global !== "undefined") {
setTimeout(_execReady.bind(global), ClassFactory("CONFIG").get("delayForReady"));
}
} else {
_execReady.call(_top);
}
};
if (isBrowser) {
window.onload = _Ready;
if (is_phonegap) {
document.addEventListener("deviceready", _Ready, captureFalse);
}
} else {
global.onload = _Ready;
}
/**
* Dynamic Data Objects Class
* Usage:
* Class('TestDDO',{
* _new_:function (){
* this.ddo = New(DDO,{
* instance:this,
* name:'ddo',
* value:0,
* fget:function (value){
* logger.debug('returned value '+ value );
* }
* })
* }
* });
*
*/
Class("DDO", Object, {
_new_: function({
instance,
name,
fget,
fset,
value
}) {
var _value;
var ddoInstance = this;
var name = (typeof name === "undefined") ? (ObjectName(ddoInstance)) : (name);
Object.defineProperty(instance, name, {
set(val) {
_value = val;
logger.debug("value changed " + name);
var ret;
if (typeof fset !== "undefined" && typeof fset === "function") {
ret = fset(_value);
} else {
ret = _value;
}
return;
},
get() {
logger.debug("returning value " + name);
var is_ddo = function(v) {
if (typeof v === "object" && v.hasOwnProperty.call(v,"value")) {
return v.value;
}
return v;
};
var ret;
if (typeof fget !== "undefined" && typeof fget === "function") {
ret = fget(is_ddo(_value));
} else {
ret = is_ddo(_value);
}
return ret;
}
});
}
});
Class("InheritClass", Object, {});
Class("DefaultTemplateHandler", Object, {
template: "",
assign: function(data) {
var processorHandler = this.component.processorHandler;
var parsedAssignmentText = this.template;
var _value;
for (var k in data) {
_value = data[k];
_value = ClassFactory("Processor").processObject.call(processorHandler,_value);
parsedAssignmentText = parsedAssignmentText.replace((new RegExp("{{" + k + "}}", "g")), _value);
}
parsedAssignmentText = ClassFactory("Processor").processObject.call(processorHandler,parsedAssignmentText);
return parsedAssignmentText;
}
});
var __routing_params__ = function (routing, routingPath){
let standardRoutingPath = routing.path.replace(/{(.*?)}/g,"(?<$1>.*)"); //allowing {param}
return {...[...routingPath.matchAll((new RegExp( standardRoutingPath ,"g")))][0]["groups"]};
};
var __valid_routings__ = function (routings, routingPath){
return routings.filter(function(routing) {
var standardRoutingPath = routing.path.replace(/{(.*?)}/g,"(?<$1>.*)");
return (new RegExp(standardRoutingPath, "g")).test(routingPath);
}).reverse();
};
var __valid_routing_way__ = function (validRoutingWays, routingWay){
return validRoutingWays.includes(routingWay);
};
_top.__oldpopstate = _top.onpopstate;
Class("Component", Object, {
domain: domain,
basePath: basePath,
templateURI: "",
templateHandler: "DefaultTemplateHandler",
processorHandler: null,
tplsource: "default",
url: "",
name: "",
method: "GET",
data: {},
reload: false,
shadowed:false,
cached: true,
done: function() {
//TODO: default done method
},
fail: function() {
//TODO: default fail method
},
set: function(name, value) {
this[name] = value;
},
get: function(name) {
return this[name];
},
__promise__: null,
feedComponent: function (){
var _component_ = this;
var _feedComponent_InBrowser = function (_component_){
var container = (_component_.hasOwnProperty.call(_component_,"container") && typeof _component_.container !== "undefined" && _component_.container !== null) ? (_component_.container) : (_component_.body);
var parsedAssignmentText = _component_.parsedAssignmentText;
_component_.innerHTML = parsedAssignmentText;
if (_component_.shadowed){
logger.debug("COMPONENT {{NAME}} is shadowed".replace("{{NAME}}", _component_.name));
logger.debug("Preparing slots for Shadowed COMPONENT {{NAME}}".replace("{{NAME}}", _component_.name));
var tmp_shadowContainer = _DOMCreateElement("div");
container.subelements("[slot]").map(
function (c){
if (c.parentElement===container){
tmp_shadowContainer.appendChild(c);
}
});
logger.debug("Creating shadowedContainer for COMPONENT {{NAME}}".replace("{{NAME}}", _component_.name));
var shadowContainer = _DOMCreateElement("div");
shadowContainer.classList.add("shadowHost");
try {
_component_.shadowRoot = shadowContainer.attachShadow({mode: "open"});
} catch (e){
try {
logger.debug("Shadowed COMPONENT {{NAME}} is repeated".replace("{{NAME}}", _component_.name));
_component_.shadowRoot = shadowContainer.shadowRoot;
} catch (e){
logger.debug("Shadowed COMPONENT {{NAME}} is not allowed on this browser".replace("{{NAME}}", _component_.name));
}
}
if (typeof _component_.shadowRoot !== "undefined" && _component_.shadowRoot !== null){
if (_component_.reload) {
logger.debug("FORCED RELOADING OF CONTAINER FOR Shadowed COMPONENT {{NAME}}".replace("{{NAME}}", _component_.name));
shadowContainer.shadowRoot.innerHTML = _component_.innerHTML;
} else {
tmp_shadowContainer.innerHTML = _component_.parseTemplate(tmp_shadowContainer.innerHTML);
logger.debug("ADDING Shadowed COMPONENT {{NAME}} ".replace("{{NAME}}", _component_.name));
shadowContainer.shadowRoot.innerHTML += _component_.innerHTML;
}
logger.debug("ADDING Slots to Shadowed COMPONENT {{NAME}} ".replace("{{NAME}}", _component_.name));
shadowContainer.innerHTML += tmp_shadowContainer.innerHTML;
logger.debug("APPENDING Shadowed COMPONENT {{NAME}} to Container ".replace("{{NAME}}", _component_.name));
if (container.subelements(".shadowHost")<1){
container.appendChild(shadowContainer);
} else {
logger.debug("Shadowed Container for COMPONENT {{NAME}} is already present in the tree ".replace("{{NAME}}", _component_.name));
}
} else {
logger.debug("Shadowed COMPONENT {{NAME}} is bad configured".replace("{{NAME}}", _component_.name));
}
} else {
if (_component_.reload) {
logger.debug("FORCED RELOADING OF CONTAINER FOR COMPONENT {{NAME}}".replace("{{NAME}}", _component_.name));
container.innerHTML = _component_.innerHTML;
} else {
logger.debug("ADDING COMPONENT {{NAME}} ".replace("{{NAME}}", _component_.name));
container.innerHTML += _component_.innerHTML;
}
}
};
var _feedComponent_InNode = function (_component_){
var parsedAssignmentText = _component_.parsedAssignmentText;
_component_.innerHTML = parsedAssignmentText;
};
var _ret_;
if (isBrowser){
_ret_ = _feedComponent_InBrowser(_component_);
} else {
_ret_ = _feedComponent_InNode(_component_);
}
return _ret_;
},
rebuild: function() {
var _component = this;
var _promise = new Promise(function(resolve, reject) {
switch (true) {
case (typeof _component.get("tplsource") !== "undefined" &&
_component.get("tplsource") === "default" &&
typeof _component.get("templateURI") !== "undefined" &&
_component.get("templateURI") !== ""):
_component.set("url", _component.get("basePath") + _component.get("templateURI"));
componentLoader(_component, false).then(
function(standardResponse) {
resolve.call(_promise, standardResponse);
},
function(standardResponse) {
reject.call(_promise, standardResponse);
});
break;
case (typeof _component.get("tplsource") !== "undefined" &&
_component.get("tplsource") === "external" &&
typeof _component.get("templateURI") !== "undefined" &&
_component.get("templateURI") !== ""):
_component.set("url", _component.get("templateURI"));
componentLoader(_component, false).then(
function(standardResponse) {
resolve.call(_promise, standardResponse);
},
function(standardResponse) {
reject.call(_promise, standardResponse);
});
break;
case (typeof _component.get("tplsource") !== "undefined" &&
_component.get("tplsource") === "inline"):
logger.debug("Component " + _component.name + " has specified template-source=inline, so it is assumed that template is already declared");
_component.feedComponent();
var standardResponse = {
request: null,
component: _component
};
if (typeof _component.done === "function") {
_component.done.call(_component, standardResponse);
}
resolve(_promise, standardResponse);
break;
case (typeof _component.get("tplsource") !== "undefined" &&
_component.get("tplsource") === "none"):
logger.debug("Component " + _component.name + " has specified template-source=none, so no template load was done");
var standardResponse = {
request: null,
component: _component
};
if (typeof _component.done === "function") {
_component.done.call(_component, standardResponse);
}
resolve(_promise, standardResponse);
break;
default:
logger.debug("Component " + _component.name + " will not be rebuilt because no templateURI is present");
reject.call(_promise, {
request: null,
component: _component
});
break;
}
});
return _promise;
},
Cast: function(o) {
return _Cast(this, o);
},
routingWay: null,
validRoutingWays: ["pathname", "hash", "search"],
routingNodes: [],
routings: [],
routingPath: "",
_bindroute: function() {
if (isBrowser) {
if (!ClassFactory("Component")._bindroute.__assigned) {
document.addEventListener("componentsloaded", function(e) {
e.stopImmediatePropagation();
e.stopPropagation();
if (!ClassFactory("Component")._bindroute.__assigned) {
_top.onpopstate = function(e) {
e.stopImmediatePropagation();
e.stopPropagation();
ClassFactory("Component").route();
if (typeof e.target.__oldpopstate !== "undefined" && typeof e.target.__oldpopstate === "function") {
e.target.__oldpopstate.call(e.target, e);
}
};
Tag("a").map(function(a) {
a.oldclick = a.onclick;
a.onclick = function(e) {
var _ret_ = true;
if (!_top.global.get("routingPaths")) {
_top.global.set("routingPaths", []);
}
var routingWay = ClassFactory("CONFIG").get("routingWay");
var routingPath = e.target[routingWay];
if (_top.global.get("routingPaths").includes(routingPath) &&
e.target[routingWay] !== document.location[routingWay] &&
e.target.href !== document.location.href
) {
logger.debug("A ROUTING WAS FOUND: " + routingPath);
window.history.pushState({
href: e.target.href
}, e.target.href, e.target.href);
ClassFactory("Component").route();
_ret_ = false;
} else {
logger.debug("NO ROUTING FOUND FOR: " + routingPath);
}
if (typeof e.target.oldclick !== "undefined" && typeof e.target.oldclick === "function") {
e.target.oldclick.call(e.target, e);
}
return _ret_;
};
return null;
});
ClassFactory("Component")._bindroute.__assigned = true;
}
}, captureFalse);
}
} else {
// not yet implemented.
}
},
route: function() {
var componentClass = this;
var isValidInstance = (componentClass.hasOwnProperty.call(componentClass,"__instanceID") &&
componentClass.hasOwnProperty.call(componentClass,"subcomponents")) ? (true) : (false);
var __route__ = function(componentList) {
componentList.map(function (rc, r){
if (typeof rc !== "undefined"
&& rc.hasOwnProperty.call(rc,"_reroute_")){
rc._reroute_();
if (rc.hasOwnProperty.call(rc,"subcomponents") &&
typeof rc.subcomponents !== "undefined" &&
rc.subcomponents.length > 0
) {
logger.debug("LOOKING FOR ROUTINGS IN SUBCOMPONENTS FOR: " + rc.name);
__route__.call(componentClass, rc.subcomponents);
}
} else if (typeof rc !== "undefined"){
logger.debug("IT WAS NOT POSSIBLE TO RE-ROUTE: " + rc.name);
}
});
};
if (isValidInstance || global.hasOwnProperty.call(global,"componentsStack")) {
if (isValidInstance && componentClass.hasOwnProperty.call(componentClass,"name")) {
logger.debug("loading routings for instance" + componentClass.name);
}
__route__.call(componentClass, (isValidInstance) ? (componentClass.subcomponents) : (global.componentsStack));
} else {
logger.debug("An undetermined result expected if load routings. So will not be loaded this time.");
}
},
fullscreen: function() {
if (isBrowser) {
var elem = this.body;
if (elem.requestFullscreen) {
elem.requestFullscreen();
} else if (elem.mozRequestFullScreen) {
/* Firefox */
elem.mozRequestFullScreen();
} else if (elem.webkitRequestFullscreen) {
/* Chrome, Safari & Opera */
elem.webkitRequestFullscreen();
} else if (elem.msRequestFullscreen) {
/* IE/Edge */
elem.msRequestFullscreen();
}
} else {
// not yet implemented.
}
},
closefullscreen: function() {
if (isBrowser) {
if (document.exitFullscreen) {
document.exitFullscreen();
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else if (document.webkitExitFullscreen) {
document.webkitExitFullscreen();
} else if (document.msExitFullscreen) {
document.msExitFullscreen();
}
} else {
// noy yet implemented.
}
},
_generateRoutingPaths: function(componentBody) {
var component = this;
if (isBrowser) {
if (__valid_routing_way__(component.validRoutingWays, component.routingWay)) {
if (typeof componentBody !== "undefined") {
component.innerHTML = componentBody.innerHTML;
component.routingNodes = componentBody.subelements("routing");
component.routings = [];
component.routingNodes.map(function (routingNode, r){
var attributeNames = routingNode.getAttributeNames();
var routing = {};
attributeNames.map(function (attributeName, a){
routing[attributeNames[a]] = routingNode.getAttribute(attributeNames[a]);
});
component.routings.push(routing);
if (!_top.global.get("routingPaths")) {
_top.global.set("routingPaths", []);
}
if (!_top.global.get("routingPaths").includes(routing.path)) {
_top.global.get("routingPaths").push(routing.path);
}
});
}
}
} else {
// not yet implemented.
}
},
parseTemplate: function (template){
var _self = this;
var _parsedAssignmentText;
if (_self.hasOwnProperty.call(_self,"templateHandler")) {
var value = template;
var templateHandlerName = _self.templateHandler;
var templateHandlerClass = ClassFactory(_self.templateHandler);
var templateInstance = New(templateHandlerClass, {
component: _self,
template: value
});
var selfData = _self.data;
if (_self.hasOwnProperty.call(_self,"assignRoutingParams") && _self.assignRoutingParams){
try {
selfData = Object.assign(selfData,_self.routingParams);
}catch (e){
logger.debug("[parseTemplate] it was not possible to assign the routing params to the template");
}
}
_parsedAssignmentText = templateInstance.assign(selfData);
} else {
_parsedAssignmentText = value;
}
return _parsedAssignmentText;
},
_new_: function(properties) {
this.routingWay = ClassFactory("CONFIG").get("routingWay");
var self = this;
self.processorHandler = New(ClassFactory("Processor"),{
component: self
});
Object.defineProperty(self, "body", {
set(value) {
self._body = value;
self._generateRoutingPaths(value);
},
get() {
return self._body;
}
});
Object.defineProperty(self, "cacheIndex", {
set(value) {
// readonly
logger.debug("[cacheIndex] This property is readonly");
},
get() {
return Base64.encode(self.name + _DataStringify(self.routingSelected));
}
});
Object.defineProperty(self, "parsedAssignmentText", {
set(value) {
// readonly
logger.debug("[parsedAssignmentText] This property is readonly");
},
get() {
self._parsedAssignmentText = self.parseTemplate(self.template);
return self._parsedAssignmentText;
}
});
Object.defineProperty(self, "shadowRoot", {
set(value) {
if (typeof self.__shadowRoot == "undefined"){
self.__shadowRoot = value;
} else {
logger.debug("[shadowRoot] This property can only be assigned once!");
}
},
get() {
return self.__shadowRoot;
}
});
Object.defineProperty(self, "routingSelected",{
set(value){
logger.debug("[routingSelected] This is a read-only property of the component");
},
get(){
return __valid_routings__(this.routings,this.routingPath);
}
});
Object.defineProperty(self, "routingParams",{
set(value){
logger.debug("[routingParams] This is a read-only property of the component");
},
get(){
var component = this;
return [{}].concat(component.routingSelected.map(function (routing){
return __routing_params__(routing,component.routingPath);
})).reduce(function (accumulator, colData, index){return Object.assign(accumulator, colData);});
}
});
this.__new__(properties);
if (!this._reroute_()) {
this.rebuild().catch(function(standardResponse) {
logger.debug("Component not rebuilt");
});
}
},
_reroute_: function() {
//This method set the selected routing and makes the switch to the templateURI
var rc = this;
var _rebuilt = false;
if (isBrowser){
if (__valid_routing_way__(rc.validRoutingWays, rc.routingWay)) {
rc.routingPath = document.location[rc.routingWay];
rc.routingSelected.map(function (routing, r){
var componentURI = ComponentURI({
"COMPONENTS_BASE_PATH": ClassFactory("CONFIG").get("componentsBasePath"),
"COMPONENT_NAME": routing.name.toString(),
"TPLEXTENSION": (routing.hasOwnProperty.call(routing,"tplextension")) ? (routing.tplextension) : (rc.tplextension),
"TPL_SOURCE": "default" //here is always default in order to get the right uri
});
rc.templateURI = componentURI;
});
if (rc.routingSelected.length > 0) {
rc.template = "";
rc.body.innerHTML = "";
rc.rebuild().then(function() {
// not yet implemented.
}).catch(function(standardResponse) {
logger.debug("Component not rebuilt");
});
_rebuilt = true;
}
}
}
return _rebuilt;
},
lazyLoadImages: function (){
if (isBrowser){
var component = this;
var _componentRoot = (component.shadowed)?(component.shadowRoot):(component.body);
var _imgLazyLoaded = [..._componentRoot.subelements("img[lazy-src]")];
var _lazyLoadImages = function(image) {
image.setAttribute("src", image.getAttribute("lazy-src"));
image.onload = () => {
image.removeAttribute("lazy-src");
};
};
if ("IntersectionObserver" in window) {
var observer = new IntersectionObserver((items, observer) => {
items.forEach((item) => {
if (item.isIntersecting) {
_lazyLoadImages(item.target);
observer.unobserve(item.target);
}
});
});
_imgLazyLoaded.map(function(img) {
return observer.observe(img);
});
} else {
_imgLazyLoaded.map(_lazyLoadImages);
}
} else {
// not yet implemented
}
return null;
},
scrollIntoHash: function (){
if (isBrowser){
var component = this;
if (document.location.hash !== ""){
var _componentRoot = (component.shadowed)?(component.shadowRoot):(component.body);
_componentRoot.subelements(document.location.hash).map(
function (element){
if (typeof element.scrollIntoView === "function"){
element.scrollIntoView(
ClassFactory("CONFIG").get("scrollIntoHash",{behavior: "auto", block: "top", inline: "top"})
);
}
}
);
}
} else {
// not yet implemented
}
},
i18n_translate: function (){
if (isBrowser){
if (ClassFactory("CONFIG").get("use_i18n")){
var component = this;
var _componentRoot = (component.shadowed)?(component.shadowRoot):(component.body);
var lang1=ClassFactory("CONFIG").get("lang","en");
var lang2 = navigator.language.slice(0, 2);
var i18n = _top.global.get("i18n");
if ((lang1 !== lang2) && (typeof i18n === "object" && i18n.hasOwnProperty.call(i18n,"messages"))){
var callback_i18n = function (){
var component = this;
return new Promise(function (resolve, reject){
var messages = i18n.messages.filter(function (message){
return message.hasOwnProperty.call(message,lang1) && message.hasOwnProperty.call(message,lang2);
});
_componentRoot.subelements("ul,li,h1,h2,h3,a,b,p,input,textarea,summary,details,option,component")
.map(function (element){
messages.map(function (message){
var _innerHTML = element.innerHTML;
_innerHTML = _innerHTML.replace(new RegExp(`${message[lang1]}`,"g"),message[lang2]);
element.innerHTML = _innerHTML;
return null;
});
return element;
});
resolve();
});
};
callback_i18n.call(component).then(function (){
logger.debug("i18n loaded for component: "+component.name);
});
}
}
} else {
// not yet implemented
}
},
_componentHelpers:[],
addComponentHelper: function (componentHelper){
var component = this;
component._componentHelpers.push(componentHelper);
},
runComponentHelpers: function() {
if (isBrowser){
var component = this;
var __component_helpers__ = [];
/*
* BEGIN use i18n translation
*/
__component_helpers__.push(component.i18n_translate.bind(component));
/*
* END use i18n translation
*/
/*
* BEGIN component scrollIntoHash
*/
__component_helpers__.push(component.scrollIntoHash.bind(component));
/*
* END component scrollIntoHash
*/
/*
* BEGIN component images lazy-load
*/
__component_helpers__.push(component.lazyLoadImages.bind(component));
/*
* END component images lazy-load
*/
__component_helpers__ = __component_helpers__.concat(component._componentHelpers);
__component_helpers__.map(
function (_component_helper_){
_component_helper_();
}
);
} else {
// not yet implemented
}
}
});
ClassFactory("Component")._bindroute.__assigned=false;
(_methods_)(ClassFactory("Component")).map(function (__c__){(_protected_code_)(__c__);});
Class("Controller", Object, {
dependencies: [],
component: null,
routingSelectedAttr: function (attrName){
return this.component.routingSelected.map(function (r){return r[attrName];}).filter(function (v){return v;}).pop();
},
isTouchable:function (){
return ("ontouchstart" in window)
|| (navigator.MaxTouchPoints > 0)
|| (navigator.msMaxTouchPoints > 0);
},
onpress:function (subelementSelector,handler){
try {
if (this.isTouchable()){
this.component.body.subelements(subelementSelector)[0].addEventListener("touchstart",handler, {passive:true});
} else {
this.component.body.subelements(subelementSelector)[0].addEventListener("click",handler, {passive:true});
}
}catch (e){
logger.debug("No button to assign press event");
}
},
createRoutingController: function (){
var controller = this;
var component = controller.component;
var controllerName = controller.routingSelectedAttr("controllerclass");
if (typeof controllerName !== "undefined"){
var _Controller = ClassFactory(controllerName);
if (typeof _Controller !== "undefined") {
component.routingController = New(_Controller, {
component: component
}); // Initializes the main controller for the component
if (component.routingController.hasOwnProperty.call(component.routingController,"done") && typeof component.routingController.done === "function") {
component.routingController.done.call(component.routingController);
}
}
}
}
});
Class("View", Object, {
dependencies: [],
component: null
});
Class("Service", Object, {
domain: domain,
basePath: basePath,
url: "",
method: "GET",
data: {},
reload: false,
cached: false,
set: function(name, value) {
this[name] = value;
},
get: function(name) {
return this[name];
}
});
Class("JSONService", ClassFactory("Service"), {
method: "GET",
cached: false,
headers: {
"Content-Type": "application/json",
"charset": "utf-8"
},
JSONresponse: null,
done: function(result) {
logger.debug("***** RECEIVED RESPONSE:");
logger.debug(result.service.template);
this.JSONresponse = JSON.parse(result.service.template);
}
});
Class("ConfigService", ClassFactory("JSONService"), {
method: "GET",
cached: false,
configFileName: "config.json",
headers: {
"Content-Type": "application/json",
"charset": "utf-8"
},
JSONresponse: null,
done: function(result) {
logger.debug("***** CONFIG LOADED:");
logger.debug(result.service.template);
this.JSONresponse = JSON.parse(result.service.template);
if (this.JSONresponse.hasOwnProperty.call(this.JSONresponse,"__encoded__")) {
this.JSONresponse = JSON.parse(ClassFactory("_Crypt").decrypt(this.JSONresponse.__encoded__, _secretKey));
}
for (var k in this.JSONresponse) {
ClassFactory("CONFIG").set(k, this.JSONresponse[k]);
}
this.configLoaded.call(this);
},
fail: function(result) {
this.configLoaded.call(this);
},
_new_: function(o) {
this.set("url", this.get("basePath") + this.get("configFileName"));
}
});
Class("VO", Object, {});
/**
* Returns a standarized uri for a component
* @example
* templateURI = ComponentURI({'COMPONENTS_BASE_PATH':'','COMPONENT_NAME':'','TPLEXTENSION':'','TPL_SOURCE':''})
* @author: Jean Machuca <correojean@gmail.com>
* @param params an object with the params to build the uri path
*/
var ComponentURI = function(params) {
var templateURI = "";
if (params["TPL_SOURCE"] === "default") {
templateURI = "{{COMPONENTS_BASE_PATH}}{{COMPONENT_NAME}}.{{TPLEXTENSION}}";
for (var k in params) {
var param = params[k];
templateURI = templateURI.replace("{{" + k + "}}", params[k]);
}
}
return templateURI;
};
/**
* Loads a simple component from a template
*
* @author: Jean Machuca <correojean@gmail.com>
* @param component a Component object
*/
var componentLoader = function(component, _async) {
var _componentLoaderInBrowser = function(component, _async) {
component.__promise__ = new Promise(function(resolve, reject) {
var _promise = component.__promise__;
var container = (component.hasOwnProperty.call(component,"container") && typeof component.container !== "undefined" && component.container !== null) ? (component.container) : (component.body);
if (container !== null) {
var _feedComponent_ = function(component) {
component.feedComponent();
var standardResponse = {
"request": xhr,
"component": component
};
resolve.call(_promise, standardResponse);
};
logger.debug("LOADING COMPONENT DATA {{DATA}} FROM {{URL}}".replace("{{DATA}}", _DataStringify(component.data)).replace("{{URL}}", component.url));
var _componentLoaded = function() {
var successStatus = (is_file) ? (0) : (200);
if (xhr.status === successStatus) {
var response = xhr.responseText;
logger.debug("Data received {{DATA}}".replace("{{DATA}}", _DataStringify(response)));
logger.debug("CREATING COMPONENT {{NAME}}".replace("{{NAME}}", component.name));
component.template = response;
if (component.cached && (typeof cache !== "undefined")) {
cache.save(component.name, component.template);
}
_feedComponent_.call(this, component);
} else {
var standardResponse = {
"request": xhr,
"component": component
};
reject.call(_promise, standardResponse);
}
};
if (typeof component.template === "string" && component.template !== ""){
// component already has a template it does not need to be reloaded
_feedComponent_.call(this, component);
} else {
var is_file = (component.url.startsWith("file:")) ? (true) : (false);
var xhr = new XMLHttpRequest();
if (!is_file){
try {
logger.debug("Calling the url of component in async mode.");
xhr.open(component.method, component.url, true);
} catch (e){
logger.debug("Last try has failed... The component cannot be loaded.");
}
} else {
if ("fetch" in _top){
logger.debug("I can use fetch...");
logger.debug("It is a file to be loaded, so I will try to use fetch");
var _p = fetch (component.url).then(response=>{
logger.debug("I got a response from fetch, so I'll feed the component");
response.text().then(text=>{
component.template=text;
_feedComponent_.call(this, component);
});
});
}
}
if (!is_phonegap && !is_file) {
xhr.setRequestHeader("Content-Type", "text/html");
}
if (!is_file) {
xhr.onload = _componentLoaded;
}
var _directLoad = function(is_file) {
is_file = (typeof is_file === "undefined" || !is_file)?(false):(true);
logger.debug("SENDING THE NORMAL REQUEST ");
if (is_file) {
if(!("fetch" in _top)){
logger.debug("I have to try to load the file using xhr... ");
xhr.send(null);
if (xhr.status === XMLHttpRequest.DONE) {
_componentLoaded.call(this);
}
}
} else {
logger.debug("Trying to send the data to the component... ");
xhr.send(_DataStringify(component.data));
}
};
if (component.cached && (!is_file)) {
logger.debug("USING CACHE FOR COMPONENT: " + component.name);
var cache = new ComplexStorageCache({
"index": component.cacheIndex,
"load": function(cacheController) {
_directLoad.call(this,is_file);
},
"alternate": function(cacheController) {
if (component.method === "GET") {
component.template = cacheController.cache.getCached(component.cacheIndex);
_feedComponent_.call(this, component);
} else {
_directLoad.call(this,is_file);
}
return;
}
});
global.lastCache = cache;
} else {
logger.debug("NOT USING CACHE FOR COMPONENT: " + component.name);
_directLoad.call(this,is_file);
}
}
return;
} else {
logger.debug("CONTAINER DOESNT EXIST");
}
});
component.__promise__.then(function(standardResponse) {
var _ret_;
if (typeof component.done === "function") {
_ret_ = component.done.call(component, standardResponse);
}
return Promise.resolve(_ret_);
}, function(standardResponse) {
var _ret_;
if (typeof component.fail === "function") {
_ret_ = component.fail.call(component, standardResponse);
}
return Promise.reject(_ret_);
}).catch(function(e) {
logger.debug("Something wrong loading the component");
});
return component.__promise__;
};
var _componentLoaderInNode = function(component, _async) {
component.__promise__ = new Promise(function(resolve, reject) {
var _promise = component.__promise__;
var _feedComponent_ = function(component) {
component.feedComponent();
var standardResponse = {
"request": null,
"component": component
};
resolve.call(_promise, standardResponse);
};
logger.debug("LOADING COMPONENT DATA {{DATA}} FROM {{URL}}".replace("{{DATA}}", _DataStringify(component.data)).replace("{{URL}}", component.url));
var _componentLoaded = function(err, responseText) {
if (!err) {
var response = responseText.toString();
logger.debug("Data received {{DATA}}".replace("{{DATA}}", _DataStringify(response)));
logger.debug("CREATING COMPONENT {{NAME}}".replace("{{NAME}}", component.name));
component.template = response;
if (component.cached && (typeof cache !== "undefined")) {
cache.save(component.name, component.template);
}
_feedComponent_.call(this, component);
} else {
var standardResponse = {
"request": null,
"component": component
};
reject.call(_promise, standardResponse);
}
};
if (typeof component.template === "string" && component.template !== ""){
// component already has a template it does not need to be reloaded
_feedComponent_.call(this, component);
} else {
logger.debug("Loading the component as a local file in server...");
var _directLoad = function(is_file) {
const fs = require("fs");
logger.debug("SENDING THE NORMAL REQUEST ");
fs.readFile(component.url, _componentLoaded);
};
if (component.cached ) {
logger.debug("USING CACHE FOR COMPONENT: " + component.name);
var cache = new ComplexStorageCache({
"index": component.cacheIndex,
"load": function(cacheController) {
_directLoad.call(this);
},
"alternate": function(cacheController) {
if (component.method === "GET") {
component.template = cacheController.cache.getCached(component.cacheIndex);
_feedComponent_.call(this, component);
} else {
_directLoad.call(this);
}
return;
}
});
global.lastCache = cache;
} else {
logger.debug("NOT USING CACHE FOR COMPONENT: " + component.name);
_directLoad.call(this);
}
}
return;
});
component.__promise__.then(function(standardResponse) {
var _ret_;
if (typeof component.done === "function") {
_ret_ = component.done.call(component, standardResponse);
}
return Promise.resolve(_ret_);
}, function(standardResponse) {
var _ret_;
if (typeof component.fail === "function") {
_ret_ = component.fail.call(component, standardResponse);
}
return Promise.reject(_ret_);
}).catch(function(e) {
logger.debug("Something wrong loading the component");
});
return component.__promise__;
};
var _ret_;
if (isBrowser){
if (typeof _async !== "undefined" && _async) {
_ret_ = asyncLoad(_componentLoaderInBrowser, arguments);
} else {
_ret_ = _componentLoaderInBrowser(component, _async);
}
} else {
_ret_ = _componentLoaderInNode(component, _async);
}
return _ret_;
};
/**
* Loads a simple component from a template
*
* @author: Jean Machuca <correojean@gmail.com>
* @param service a Service object
*/
var serviceLoader = function(service, _async) {
var _serviceLoaderInBrowser = function(service, _async) {
var _promise = new Promise(
function(resolve, reject) {
logger.debug("LOADING SERVICE DATA {{DATA}} FROM {{URL}}".replace("{{DATA}}", _DataStringify(service.data)).replace("{{URL}}", service.url));
var xhr = new XMLHttpRequest();
xhr.withCredentials = service.withCredentials;
var xhrasync = true; // always async because xhr sync is deprecated
xhr.open(service.method, service.url, xhrasync);
for (var header in service.headers) {
try {
if (typeof service.headers[header] !== "function"){
xhr.setRequestHeader(header, service.headers[header]);
}
} catch (e){
logger.debug("Something went wrong when assign the header "+header);
}
}
xhr.onload = function() {
if (xhr.status === 200) {
var response = xhr.responseText;
logger.debug("Data received {{DATA}}".replace("{{DATA}}", _DataStringify(response)));
logger.debug("CREATING SERVICE {{NAME}}".replace("{{NAME}}", service.name));
service.template = response;
if (service.cached && (typeof cache !== "undefined")) {
cache.save(service.name, service.template);
}
if (typeof service.done === "function") {
var standardResponse = {
"request": xhr,
"service": service
};
service.done.call(service, standardResponse);
resolve.call(_promise, standardResponse);
}
} else {
if (typeof service.fail === "function") {
var standardResponse = {
"request": xhr,
"service": service
};
service.fail.call(service, standardResponse);
reject.call(_promise, standardResponse);
}
}
};
var _directLoad = function() {
logger.debug("SENDING THE NORMAL REQUEST ");
try {
xhr.send(_DataStringify(service.data));
} catch (e) {
logger.debug("SOMETHING WRONG WITH REQUEST ");
reject.call(_promise, {
request: xhr,
service: service
});
}
};
if (service.cached) {
var cache = new ComplexStorageCache({
"index": service.data,
"load": function(cacheController) {
_directLoad.call(this);
},
"alternate": function(cacheController) {
if (service.method === "GET") {
service.template = cacheController.cache.getCached(service.name);
if (typeof service.done === "function") {
var standardResponse = {
"request": xhr,
"service": service
};
service.done.call(service, standardResponse);
resolve.call(_promise, standardResponse);
}
} else {
_directLoad.call(this);
}
return;
}
});
global.lastCache = cache;
} else {
_directLoad.call(this);
}
return xhr;
}
);
return _promise;
};
var _serviceLoaderInNode = function(service, _async) {
var _promise = new Promise(
function(resolve, reject) {
var serviceURL = new URL(service.url);
var req;
service.useHTTP2 = service.hasOwnProperty.call(service,"useHTTP2") && service.useHTTP2;
var captureEvents = function (req){
logger.debug("LOADING SERVICE DATA (non-browser) {{DATA}} FROM {{URL}}".replace("{{DATA}}", _DataStringify(service.data)).replace("{{URL}}", service.url));
var dataXML;
var standardResponse = {
"http2Client": client,
"request": req,
"service": service,
"responseHeaders": null
};
if (typeof service.data === "object" && service.data !== null){
if (service.useHTTP2){
try {
logger.debug("Sending data...");
let buffer = new Buffer(_DataStringify(service.data));
req.write(buffer);
}catch (e){
logger.debug("It was not possible to send any data");
}
}
}
dataXML = "";
req.on("response", (responseHeaders,flags) => {
logger.debug("receiving response...");
standardResponse.responseHeaders = responseHeaders;
/*
for (const name in responseHeaders) {
logger.debug(`${name}: ${responseHeaders[name]}`);
}
*/
dataXML = "";
});
req.on("data", (chunk) => {
logger.debug("receiving data...");
// do something with the data
dataXML += ""+ chunk.toString();
service.template = dataXML;
});
if (service.useHTTP2){
req.resume();
}
req.on("end", () => {
logger.debug("ending call...");
service.template = dataXML;
if (service.hasOwnProperty.call(service,"useHTTP2") && service.useHTTP2) {
client.destroy();
} else {
req.destroy();
}
service.done.call(service, standardResponse);
resolve.call(_promise, standardResponse);
});
if (service.useHTTP2){
req.end();
}
};
try {
var requestOptions;
if (service.useHTTP2) {
logger.debug("using http2");
var http2 = require("http2");
var client = http2.connect(serviceURL.origin);
requestOptions = Object.assign({
":method": service.method,
":path": serviceURL.pathname
}, service.options);
requestOptions = Object.assign(requestOptions,service.headers);
req = client.request(requestOptions);
req.setEncoding("utf8");
captureEvents(req);
} else {
if (serviceURL.protocol === "http:"){
var http = require("http");
var request = http.request;
requestOptions = Object.assign({
"url": service.url,
headers: service.headers
}, service.options);
var req = request(service.url);
captureEvents(req);
} else if (serviceURL.protocol === "https:"){
var https = require("https");
requestOptions = Object.assign({
hostname: serviceURL.hostname,
port: serviceURL.port,
path: serviceURL.pathname,
method: service.method,
headers: service.headers
}, service.options);
var _req_ = https.request(requestOptions, function (req){
captureEvents(req);
});
_req_.end();
} else {
var e = "Protocol not supported: "+serviceURL.protocol;
logger.debug(e);
throw new Error (e);
}
}
} catch (e) {
logger.debug(e);
service.fail.call(service, e);
reject.call(_promise, e);
}
}).catch(function(e) {
console.log(e);
logger.debug("Something happened when trying to call the service: " + service.name);
service.fail.call(service, e);
});
return _promise;
};
var _ret_;
if (isBrowser) {
if (typeof _async !== "undefined" && _async) {
_ret_ = asyncLoad(_serviceLoaderInBrowser, arguments);
} else {
_ret_ = _serviceLoaderInBrowser(service, _async);
}
} else {
_ret_ = _serviceLoaderInNode(service, _async);
}
return _ret_;
};
Export(serviceLoader);
Export(componentLoader);
Export(ComponentURI);
Export(ObjectName);
Export(_DataStringify);
Export(isQCObjects_Class);
Export(isQCObjects_Object);
asyncLoad(function() {
Class("global", Object, {
_GLOBAL: {},
set: function(name, value) {
this._GLOBAL[name] = value;
},
get: function(name,_default) {
var _value;
if (typeof this._GLOBAL[name] !== "undefined"){
_value = this._GLOBAL[name];
} else if (typeof _default !== "undefined"){
_value = _default;
}
return _value;
},
__start__: function() {
var __load__serviceWorker = function() {
var _promise;
if (isBrowser) {
_promise = new Promise(function(resolve, reject) {
if (("serviceWorker" in navigator) &&
(typeof ClassFactory("CONFIG").get("serviceWorkerURI") !== "undefined")) {
ClassFactory("CONFIG").set("serviceWorkerScope", ClassFactory("CONFIG").get("serviceWorkerScope") ? (ClassFactory("CONFIG").get("serviceWorkerScope")) : ("/"));
navigator.serviceWorker.register(ClassFactory("CONFIG").get("serviceWorkerURI"), {
scope: ClassFactory("CONFIG").get("serviceWorkerScope")
})
.then(function(registration) {
logger.debug("Service Worker Registered");
resolve.call(_promise, registration);
}, function(registration) {
logger.debug("Error registering Service Worker");
reject.call(_promise, registration);
});
navigator.serviceWorker.ready.then(function(registration) {
logger.debug("Service Worker Ready");
resolve.call(_promise, registration);
}, function(registration) {
logger.debug("Error loading Service Worker");
reject.call(_promise, registration);
});
}
});
}
return _promise;
};
var _buildComponents = function() {
if (isBrowser) {
logger.debug("Starting to bind routes");
ClassFactory("Component")._bindroute.call(ClassFactory("Component"));
logger.debug("Starting to building components");
global.componentsStack = document.buildComponents.call(document);
logger.debug("Initializing the service worker");
__load__serviceWorker.call(_top).catch(function() {
logger.debug("error loading the service worker");
});
}
};
if (ClassFactory("CONFIG").get("useConfigService")) {
global.configService = New(ClassFactory("ConfigService"));
global.configService.configLoaded = _buildComponents;
serviceLoader(global.configService);
} else {
_buildComponents.call(this);
}
}
});
Object.defineProperty(global,"PackagesNameList",{
set(val){
logger.debug("PackagesNameList is readonly");
return;
},
get(){
var _get_packages_names = function (_packages){
var _keys = [];
for (var _k in _packages){
if (
typeof _packages[_k] !== "undefined"
&& typeof _packages[_k] !== "function"
&& _packages[_k].hasOwnProperty.call(_packages[_k],"length")
&& _packages[_k].length>0
){
_keys.push(_k);
_keys = _keys.concat(_get_packages_names(_packages[_k]));
}
}
return _keys;
};
return _get_packages_names(_QC_PACKAGES);
}
});
Object.defineProperty(global,"PackagesList",{
set(value){
logger.debug("PackagesList is readonly");
return;
},
get(){
return global.PackagesNameList.map(function (packagename) {
let _classesList = Package(packagename);
let _ret_;
if (_classesList){
_ret_ = {
packageName:packagename,
classesList:_classesList.filter(function (_packageClass) {
return isQCObjects_Class(_packageClass);
}
)
};
}
return _ret_;
}).filter(function (_p){return typeof _p !== "undefined";});
}
});
Object.defineProperty(global,"ClassesList",{
set(value){
logger.debug("ClassesList is readonly");
return;
},
get(){
var _classesList = [];
global.PackagesList.map(function (_package_element){
_classesList = _classesList.concat(_package_element.classesList.map(
function (_class_element){
return {
packageName:_package_element.packageName,
className:_package_element.packageName+"."+_class_element.__definition.__classType,
classFactory:_class_element
};
}
));
return _package_element;
});
return _classesList;
}
});
Object.defineProperty(global,"ClassesNameList",{
set(value){
logger.debug("ClassesNameList is readonly");
return;
},
get(){
return global.ClassesList.map(function (_class_element) {
return _class_element.className;
});
}
});
if (isBrowser) {
// use of GLOBAL word is deprecated in node.js
// this is only for compatibility purpose with old versions of QCObjects in browsers
Class("GLOBAL", _QC_CLASSES["global"]); // case insensitive for compatibility con old versions;
Export(ClassFactory("GLOBAL"));
}
Export(global);
if (ClassFactory("CONFIG").get("useSDK")) {
(function() {
var remoteImportsPath = ClassFactory("CONFIG").get("remoteImportsPath");
var external = (!ClassFactory("CONFIG").get("useLocalSDK")) ? (true) : (false);
ClassFactory("CONFIG").set("remoteImportsPath", ClassFactory("CONFIG").get("remoteSDKPath"));
var tryImportingSDK = false;
var sdkName = "QCObjects-SDK";
if (isBrowser) {
tryImportingSDK = true;
} else {
var sdkPath = findPackageNodePath("qcobjects-sdk");
if (sdkPath !== null) {
sdkName = "qcobjects-sdk";
tryImportingSDK = true;
} else {
sdkName = "node_modules/qcobjects-sdk/QCObjects-SDK";
tryImportingSDK = true;
}
}
if (tryImportingSDK) {
logger.info("Importing SDK... " + sdkName);
Import(sdkName, function() {
if (external) {
logger.debug("QCObjects-SDK.js loaded from remote location");
} else {
logger.debug("QCObjects-SDK.js loaded from local");
}
ClassFactory("CONFIG").set("remoteImportsPath", remoteImportsPath);
}, external);
} else {
logger.debug("SDK has not been imported as it is not available at the moment");
}
}).call(null);
}
}, null);
if (isBrowser) {
Element.prototype.buildComponents = function(rebuildObjects = false) {
var tagFilter = (!rebuildObjects) ? ("component:not([loaded])") : ("component");
var d = this;
var _buildComponent = function(components) {
var componentsBuiltWith = components.map (function (_component_, _c){
_component_ = components[_c];
var data = {};
var attributenames = components[_c].getAttributeNames().filter(function(a) {
return a.startsWith("data-");
}).map(function(a) {
return a.split("-")[1];
});
attributenames.map(function (_attribute_name_){
data[_attribute_name_] = components[_c].getAttribute("data-" + _attribute_name_);
});
var componentDone = function() {
var viewName = this.body.getAttribute("viewClass");
var _View = ClassFactory(viewName);
if (typeof _View !== "undefined") {
this.view = New(_View, {
component: this
}); // Initializes the main view for the component
if (this.view.hasOwnProperty.call(this.view,"done") && typeof this.view.done === "function") {
this.view.done.call(this.view);
}
}
var controllerName = this.body.getAttribute("controllerClass");
if (!controllerName){
controllerName = "Controller";
}
var _Controller = ClassFactory(controllerName);
if (typeof _Controller !== "undefined") {
this.controller = New(_Controller, {
component: this
}); // Initializes the main controller for the component
if (this.controller.hasOwnProperty.call(this.controller,"done") && typeof this.controller.done === "function") {
this.controller.done.call(this.controller);
}
if (this.controller.hasOwnProperty.call(this.controller,"createRoutingController")){
this.controller.createRoutingController.call(this.controller);
}
}
var effectClassName = this.body.getAttribute("effectClass");
var _Effect = ClassFactory(effectClassName);
if (typeof _Effect !== "undefined") {
this.effect = New(_Effect, {
component: this
});
this.effect.apply(this.effect.defaultParams);
}
if (this.shadowed && (typeof this.shadowRoot !== "undefined")){
this.subcomponents = _buildComponent(this.shadowRoot.subelements(tagFilter));
} else {
this.subcomponents = _buildComponent(this.body.subelements(tagFilter));
}
if (ClassFactory("CONFIG").get("overrideComponentTag")) {
this.body.outerHTML = this.body.innerHTML;
}
this.body.setAttribute("loaded", true);
this.runComponentHelpers();
if ((Tag("component[loaded=true]").length * 100 / Tag("component:not([template-source=none])").length) >= 100) {
d.dispatchEvent(new CustomEvent("componentsloaded", {
detail: {
lastComponent: this
}
}));
}
};
var __shadowed_not_set = (components[_c].getAttribute("shadowed") === null) ? (true) : (false);
var shadowed = (components[_c].getAttribute("shadowed") === "true") ? (true) : (false);
var __cached_not_set = (components[_c].getAttribute("cached") === null) ? (true) : (false);
var cached = (components[_c].getAttribute("cached") === "true") ? (true) : (false);
var tplextension = (typeof ClassFactory("CONFIG").get("tplextension") !== "undefined") ? (ClassFactory("CONFIG").get("tplextension")) : ("html");
tplextension = (components[_c].getAttribute("tplextension") !== null) ? (components[_c].getAttribute("tplextension")) : (tplextension);
var tplsource = (components[_c].getAttribute("template-source") === null) ? ("default") : (components[_c].getAttribute("template-source"));
var _componentName = components[_c].getAttribute("name");
var _componentClassName = (components[_c].getAttribute("componentClass") !== null) ? (components[_c].getAttribute("componentClass")) : ("Component");
var _serviceClassName = (components[_c].getAttribute("serviceClass") !== null) ? (components[_c].getAttribute("serviceClass")) : (null);
/* __enable_service_class__ = true by default */
var __enable_service_class__ = (
(components[_c].hasOwnProperty.call(components[_c], "enableServiceClass") && components[_c].enableServiceClass)
|| (!components[_c].hasOwnProperty.call(components[_c], "enableServiceClass"))
) ? (true) : (false);
var _response_to_data_ = (components[_c].getAttribute("response-to") !== null && components[_c].getAttribute("response-to") === "data") ? (true) : (false);
var _response_to_template_ = (components[_c].getAttribute("response-to") !== null && components[_c].getAttribute("response-to") === "template") ? (true) : (false);
var __componentClassName = (ClassFactory("CONFIG").get("preserveComponentBodyTag"))?(
(_componentName !== null)?("com.qcobjects.components."+_componentName+".ComponentBody"):("com.qcobjects.components.ComponentBody")
):(_componentClassName);
_componentName = (_componentName !== null)?(_componentName):(
(ClassFactory(__componentClassName) && ClassFactory(__componentClassName).hasOwnProperty.call(ClassFactory(__componentClassName),"name")
)?(
ClassFactory(__componentClassName).name
):("")
);
var componentURI;
componentURI = ComponentURI({
"COMPONENTS_BASE_PATH": ClassFactory("CONFIG").get("componentsBasePath"),
"COMPONENT_NAME": _componentName,
"TPLEXTENSION": tplextension,
"TPL_SOURCE": tplsource
});
if (ClassFactory("CONFIG").get("preserveComponentBodyTag")) {
Package((_componentName !== "")?("com.qcobjects.components."+_componentName+""):("com.qcobjects.components"),[
Class("ComponentBody", ClassFactory("Component"), {
name: _componentName,
tplsource:tplsource,
tplextension:tplextension,
reload: true
})
]);
}
var __classDefinition = ClassFactory(__componentClassName);
var __serviceClass = ClassFactory(_serviceClassName);
if (!_response_to_data_ && __classDefinition && __classDefinition.hasOwnProperty.call(__classDefinition, "responseTo")){
_response_to_data_ = (__classDefinition.responseTo === "data")?(true):(false);
} else if (!_response_to_data_ && ClassFactory("Component").hasOwnProperty.call(ClassFactory("Component"), "responseTo")){
_response_to_data_ = (ClassFactory("Component").responseTo === "data")?(true):(false);
}
if (!_response_to_template_ && __classDefinition && __classDefinition.hasOwnProperty.call(__classDefinition, "responseTo")){
_response_to_template_ = (__classDefinition.responseTo === "template")?(true):(false);
} else if (!_response_to_template_ && ClassFactory("Component").hasOwnProperty.call(ClassFactory("Component"), "responseTo")){
_response_to_template_ = (ClassFactory("Component").responseTo === "template")?(true):(false);
}
var __create_component_instance_ = function (data, serviceResponse) {
var __shadowed = (__shadowed_not_set) ? ((__classDefinition && __classDefinition.shadowed) || ClassFactory("Component").shadowed) : (shadowed);
var __definition = {
name: _componentName,
data: data,
cached: (__cached_not_set) ? (ClassFactory("Component").cached) : (cached),
shadowed: __shadowed,
tplextension: tplextension,
body: (ClassFactory("CONFIG").get("preserveComponentBodyTag")) ? (_DOMCreateElement("componentBody")):(components[_c]),
templateURI: componentURI,
tplsource: tplsource,
subcomponents: []
};
if (_response_to_template_){
__definition.template = serviceResponse;
}
if (typeof _componentName === "undefined" || _componentName === "" || _componentName === null){
/* this allows to use the original property defined
in the component definition if it is not present in the tag */
delete __definition.name;
}
if (componentURI === ""){
/* this allows to use the original property defined
in the component definition if it is not present in the tag */
delete __definition.templateURI;
}
var newComponent = New(__classDefinition, __definition);
if (ClassFactory("CONFIG").get("preserveComponentBodyTag")) {
components[_c].append(newComponent);
}
newComponent.done = componentDone;
return newComponent;
};
var newComponent;
if (typeof __serviceClass !== "undefined"
&& (typeof __enable_service_class__ !== "undefined"
&& __enable_service_class__ === true)
&& (_response_to_data_ || _response_to_template_)
){
logger.info("Loading service "+_serviceClassName);
var serviceInstance = New(__serviceClass, {
data: data
});
serviceLoader(serviceInstance).then(function ({request, service}){
var serviceResponse = service.template;
if (_response_to_data_){
if (typeof data === "object" && typeof serviceResponse === "object"){
data = Object.assign(data, serviceResponse);
} else {
data = serviceResponse;
}
}
newComponent = __create_component_instance_.call(this, data, serviceResponse);
newComponent.serviceInstance = serviceInstance;
newComponent.serviceData = data;
}).catch (function (e){
logger.debug("Something went wroing while trying to load the service "+_serviceClassName);
});
} else {
newComponent = __create_component_instance_.call(this, data, null);
}
return newComponent;
});
return componentsBuiltWith;
};
var components = d.subelements(tagFilter);
return _buildComponent(components);
};
HTMLDocument.prototype.buildComponents = Element.prototype.buildComponents;
HTMLElement.prototype.buildComponents = Element.prototype.buildComponents;
var _ComponentWidget_ = class extends HTMLElement {
constructor() {
super();
const componentWidget = this;
const componentName = componentWidget.nodeName.toLowerCase();
const componentBody = _DOMCreateElement("component");
const __enabled__atributes__ = ["cached","splashscreen","response-to","shadowed","componentClass", "controllerClass", "viewClass", "serviceClass", "effectClass", "tplextension", "template-source", "data"];
componentBody.setAttribute("name",componentName);
if (!componentWidget.hasAttribute("shadowed")) {
componentBody.setAttribute("shadowed","true");
}
__enabled__atributes__.map (function (attributeName){
if (componentWidget.hasAttribute(attributeName)){
componentBody.setAttribute(attributeName,componentWidget.getAttribute(attributeName));
componentWidget.removeAttribute(attributeName);
}
});
var data_attributenames = componentWidget.getAttributeNames().filter(function(a) {
return a.startsWith("data-");
}).map(function(a) {
return a.split("-")[1];
});
data_attributenames.map(function (_attribute_name_){
componentBody.setAttribute("data-" + _attribute_name_, componentWidget.getAttribute("data-" + _attribute_name_));
componentWidget.removeAttribute("data-" + _attribute_name_);
});
[...componentWidget.children].map(function (element){
componentBody.appendChild(element.cloneNode(true));
element.remove();
});
componentWidget.append(componentBody);
}
};
Export(_ComponentWidget_);
var RegisterWidget = function (widgetName){
customElements.define(widgetName,class extends _ComponentWidget_ {});
};
var RegisterWidgets = function (){
var widgetList = [...arguments];
widgetList.filter(function (widgetName){return typeof widgetName === "string";}).map(function (widgetName){
RegisterWidget(widgetName);
});
};
(_protected_code_)(RegisterWidget);
(_protected_code_)(RegisterWidgets);
Export(RegisterWidget);
Export(RegisterWidgets);
} else {
// not yet implemented.
}
if (!isBrowser) {
Class("BackendMicroservice", Object, {
domain: domain,
basePath: basePath,
body: null,
stream: null,
request: null,
cors: function (){
if (this.route.cors){
let {allow_origins,allow_credentials,allow_methods,allow_headers} = this.route.cors;
var microservice = this;
if (typeof microservice.headers !== "object"){
microservice.headers = {};
}
if (typeof allow_origins !== "undefined"){
// an example of allow_origins is ['https://example.com','http://www.example.com']
if (allow_origins === "*" || (typeof microservice.request.headers.origin === "undefined") || [...allow_origins].indexOf(microservice.request.headers.origin)!== -1){
// for compatibility with all browsers allways return a wildcard when the origin is allowed
microservice.headers["Access-Control-Allow-Origin"] = "*";
} else {
logger.debug("Origin is not allowed: " + microservice.request.headers.origin);
logger.debug("Forcing to finish the response...");
this.body = {};
try {
this.done();
} catch (e){}
}
} else {
microservice.headers["Access-Control-Allow-Origin"] = "*";
}
if (typeof allow_credentials !== "undefined"){
microservice.headers["Access-Control-Allow-Credentials"] = allow_credentials.toString();
} else {
microservice.headers["Access-Control-Allow-Credentials"] = "true";
}
if (typeof allow_methods !== "undefined"){
microservice.headers["Access-Control-Allow-Methods"] = [...allow_methods].join(",");
} else {
microservice.headers["Access-Control-Allow-Methods"] = "GET, OPTIONS, POST";
}
if (typeof allow_headers !== "undefined"){
microservice.headers["Access-Control-Allow-Headers"] = [...allow_headers].join(",");
} else {
microservice.headers["Access-Control-Allow-Headers"] = "*";
}
}
},
_new_: function(o) {
logger.debug("Executing BackendMicroservice ");
let microservice = this;
microservice.body = null;
let request = microservice.request;
this.cors();
let stream = o.stream;
microservice.stream = stream;
stream.on("data", (data) => {
// data from POST, GET
var requestMethod = request.method.toLowerCase();
var supportedMethods = {
"post": microservice.post,
};
if (supportedMethods.hasOwnProperty.call(supportedMethods,requestMethod)) {
supportedMethods[requestMethod].call(microservice, data);
}
});
// data from POST, GET
var requestMethod = request.method.toLowerCase();
var supportedMethods = {
"get": microservice.get,
"head": microservice.head,
"put": microservice.put,
"delete": microservice.delete,
"connect": microservice.connect,
"options": microservice.options,
"trace": microservice.trace,
"patch": microservice.patch
};
if (supportedMethods.hasOwnProperty.call(supportedMethods,requestMethod)) {
supportedMethods[requestMethod].call(microservice);
}
},
head: function(formData) {
this.done();
},
get: function(formData){
this.done();
},
post: function(formData) {
this.done();
},
put: function(formData) {
this.done();
},
delete: function(formData) {
this.done();
},
connect: function(formData) {
this.done();
},
options: function(formData) {
this.done();
},
trace: function(formData) {
this.done();
},
patch: function(formData) {
this.done();
},
finishWithBody: function(stream) {
try {
stream.write(_DataStringify(this.body));
stream.end();
} catch (e) {
logger.debug("Something wrong writing the response for microservice" + e.toString());
}
},
done: function () {
logger.debugEnabled = true;
var microservice = this;
var stream = microservice.stream;
try {
stream.respond(microservice.headers);
} catch (e){
logger.debug(e.toString());
}
if (microservice.body !== null) {
try {
microservice.finishWithBody.call(microservice, stream);
} catch (e){
logger.debug(e.toString());
}
}
}
});
}
Class("SourceJS", Object, {
domain: domain,
basePath: basePath,
body: _DOMCreateElement("script"),
type: "text/javascript",
containerTag: "body",
url: "",
data: {},
async: false,
external: false,
set: function(name, value) {
this[name] = value;
},
get: function(name) {
return this[name];
},
status: false,
done: function() {},
fail: function() {},
rebuild: function() {
var context = this;
try {
document.getElementsByTagName(context.containerTag)[0].appendChild(
(function(s, url, context) {
s.type = context.type;
s.src = url;
s.crossOrigin = (context.hasOwnProperty.call(context,"crossOrigin")) ? (context.crossOrigin) : ("anonymous");
s.async = context.async;
s.onreadystatechange = function() {
if (this.readyState === "complete") {
context.done.call(context);
}
};
s.onload = function(e) {
context.status = true;
context.done.call(context, e);
};
s.onerror = function(e) {
context.status = false;
context.fail.call(context, e);
};
context.body = s;
return s;
}).call(this,
_DOMCreateElement("script"),
(this.external) ? (this.url) : (this.basePath + this.url), context));
} catch (e) {
context.status = false;
context.fail.call(context, e);
}
},
Cast: function(o) {
return _Cast(this, o);
},
"_new_": function(properties) {
this.__new__(properties);
this.rebuild();
}
});
Class("SourceCSS", Object, {
domain: domain,
basePath: basePath,
body: _DOMCreateElement("link"),
url: "",
data: {},
async: false,
external: false,
set: function(name, value) {
this[name] = value;
},
get: function(name) {
return this[name];
},
done: function() {},
rebuild: function() {
var context = this;
if (isBrowser){
window.document.getElementsByTagName("head")[0].appendChild(
(function(s, url, context) {
s.type = "text/css";
s.rel = "stylesheet";
s.href = url;
s.crossOrigin = "anonymous";
s.onreadystatechange = function() {
if (this.readyState === "complete") {
context.done.call(context);
}
};
s.onload = context.done;
context.body = s;
return s;
}).call(this,
_DOMCreateElement("link"),
(this.external) ? (this.url) : (this.basePath + this.url), context));
}
},
Cast: function(o) {
return _Cast(this, o);
},
"_new_": function(properties) {
this.__new__(properties);
this.rebuild();
}
});
/**
* Array math functions
*/
var __to_number = function(value) {
return (isNaN(value)) ? (new Number(0)) : (new Number(value));
};
Array.prototype.unique = function() {
return this.filter(function (value, index, self) { return self.indexOf(value) === index;});
};
Array.unique = function (a){
return a.unique();
};
(_protected_code_)(Array.unique);
(_protected_code_)(Array.prototype.unique);
Array.prototype.table = function() {
console.table(this);
};
Array.table = function (a){
return a.table();
};
(_protected_code_)(Array.table);
(_protected_code_)(Array.prototype.table);
Array.prototype.sum = function() {
return this.reduce(function(prev, current) {
return __to_number(prev) + __to_number(current);
},0);
};
Array.sum = function (a){
return a.sum();
};
(_protected_code_)(Array.sum);
(_protected_code_)(Array.prototype.sum);
Array.prototype.avg = function() {
return (this.length<1)?(0):(this.reduce(function(prev, current) {
return ((__to_number(prev) + __to_number(current)) / 2);
}));
};
Array.avg = function (a){
return a.avg();
};
(_protected_code_)(Array.avg);
(_protected_code_)(Array.prototype.avg);
Array.prototype.min = function() {
return this.reduce(function(prev, current) {
return ( __to_number(prev)<=__to_number(current) ) ? (prev):(current);
},Infinity);
};
Array.min = function (a){
return a.min();
};
(_protected_code_)(Array.min);
(_protected_code_)(Array.prototype.min);
Array.prototype.max = function() {
return this.reduce(function(prev, current) {
return ( __to_number(prev)>=__to_number(current) ) ? (prev):(current);
},0);
};
Array.max = function (a){
return a.max();
};
(_protected_code_)(Array.max);
(_protected_code_)(Array.prototype.max);
Array.prototype.sortBy = function (propName, sortAsc = true){
var sort_function = (sortAsc)?(
function (prev, current) { return current[propName] < prev[propName] ? 1 : -1;}
):(
function (prev, current) { return current[propName] > prev[propName] ? 1 : -1;}
);
return this.sort(sort_function);
};
Array.sortBy = function (a, propName, sortAsc = true){
return a.sortBy(propName, sortAsc);
};
(_protected_code_)(Array.sortBy);
(_protected_code_)(Array.prototype.sortBy);
Array.matrix = function (_length, _fillValue = 0){
var x_func = function (x){return _fillValue;};
return Array.from({length:_length},x_func);
};
(_protected_code_)(Array.matrix);
Array.matrix2d = function (_length, _fillValue = 0){
var y_func = function (y){return _fillValue;};
var x_func = function (x){return Array.from({length:_length},y_func);};
return Array.from({length:_length},x_func);
};
(_protected_code_)(Array.matrix2d);
Array.matrix3d = function (_length, _fillValue = 0){
var y_func = function (y){return Array.from({length:_length},function (){return _fillValue;});};
var x_func = function (x){return Array.from({length:_length},y_func);};
return Array.from({length:_length},x_func);
};
(_protected_code_)(Array.matrix3d);
_top.range = function (start, stop=0, step=1) {
if (stop===0 || typeof stop === "undefined"){
stop = start;
start = 0;
}
return Array.from({ length: (stop - start) / step + 1}, function (_, i) {return start + (i * step);});
};
(_protected_code_)(_top.range);
String.prototype.list = function () { var __instance=this; return _top.range(0,__instance.length-1).map( function (i) {return __instance[i];}); };
(_protected_code_)(String.prototype.list);
_top.getDocumentLayout = function () {
var h = (w, h) => {
return w>h ? "landscape": null;
};
var v = (w, h) => {
return h>w ? "portrait": null;
};
var square = (w, h) => {
return w===h ? "square": null;
};
return [
h(document.documentElement.clientWidth,document.documentElement.clientHeight),
v(document.documentElement.clientWidth,document.documentElement.clientHeight),
square(document.documentElement.clientWidth,document.documentElement.clientHeight)
].filter(e=>e!==null).pop();
};
/**
* End of array math functions
*/
Class("ArrayList", Array, []);
ClassFactory("ArrayList").matrix = Array.matrix;
ClassFactory("ArrayList").matrix2d = Array.matrix2d;
ClassFactory("ArrayList").matrix3d = Array.matrix3d;
(_protected_code_)(ClassFactory("ArrayList").matrix);
(_protected_code_)(ClassFactory("ArrayList").matrix2d);
(_protected_code_)(ClassFactory("ArrayList").matrix3d);
Class("ArrayCollection", Object, {
source: New(ClassFactory("ArrayList"), []),
changed: function(prop, value) {
logger.debug("VALUE CHANGED");
logger.debug(prop);
logger.debug(value);
},
push: function(value) {
var self = this;
logger.debug("VALUE ADDED");
logger.debug(value);
self.source.push(value);
},
pop: function(value) {
var self = this;
logger.debug("VALUE POPPED");
logger.debug(value);
self.source.pop(value);
},
_new_: function(source) {
var self = this;
var _index = 0;
self.source = New(ClassFactory("ArrayList"), source);
for (var _k in self.source) {
if (!isNaN(_k)) {
logger.debug("binding " + _k.toString());
(function(_pname) {
Object.defineProperty(self, _pname, {
set(value) {
logger.debug("setting " + _pname + "=" + value);
self.source[_pname] = value;
self.changed(_pname, value);
},
get() {
return self.source[_pname];
}
});
})(_k);
_index++;
}
}
self.source.length = _index;
Object.defineProperty(self, "length", {
get() {
return self.source.length;
}
});
}
});
Class("Effect", {
duration: 1000,
animate: function({
timing,
draw,
duration
}) {
let start = performance.now();
requestAnimationFrame(function animate(time) {
// timeFraction goes from 0 to 1
let timeFraction = (time - start) / duration;
if (timeFraction > 1) timeFraction = 1;
// calculate the current animation state
let progress = timing(timeFraction);
draw(Math.round(progress * 100)); // draw it
if (timeFraction < 1) {
requestAnimationFrame(animate);
} else {
// if this is an object with a done method
if (typeof this !== "undefined"
&& this !== null
&& this.hasOwnProperty.call(this,"done") &&
(typeof this.done).toLowerCase() === "function") {
this.done.call(this);
}
}
});
}
});
Class("TransitionEffect",ClassFactory("Effect"),{
duration:385,
defaultParams:{
alphaFrom:0,
alphaTo:1,
angleFrom:180,
angleTo:0,
radiusFrom:0,
radiusTo:30,
scaleFrom:0,
scaleTo:1
},
fitToHeight:false,
fitToWidth:false,
effects: [],
_new_:function (o){
logger.info("DECLARING TransitionEffect ");
this.component.defaultParams = this.defaultParams;
},
apply: function ({alphaFrom,
alphaTo,
angleFrom,
angleTo,
radiusFrom,
radiusTo,
scaleFrom,
scaleTo}){
var _transition_ = this;
logger.info("EXECUTING TransitionEffect ");
if (_transition_.fitToHeight){
_transition_.component.body.height = _transition_.component.body.offsetParent.scrollHeight;
}
if (_transition_.fitToWidth){
_transition_.component.body.width = _transition_.component.body.offsetParent.scrollWidth;
}
_transition_.component.body.style.display = "block";
_transition_.effects.map(function (effectClassName,eff){
var effectClassMethod = _super_(effectClassName,"apply");
var args = [_transition_.component.body].concat(Object.values(
{
alphaFrom,
alphaTo,
angleFrom,
angleTo,
radiusFrom,
radiusTo,
scaleFrom,
scaleTo
}
));
effectClassMethod.apply(_transition_,args);
});
}
});
Class("Timer", {
duration: 1000,
alive: true,
thread: function({
timing,
intervalInterceptor,
duration
}) {
var timer = this;
let start = performance.now();
requestAnimationFrame(function thread(time) {
// timeFraction goes from 0 to 1
let elapsed = (time - start);
let timeFraction = elapsed / duration;
if (timeFraction > 1) timeFraction = 1;
// calculate the current progress state
let progress = timing(timeFraction, elapsed);
intervalInterceptor(Math.round(progress * 100)); // draw it
if ((timeFraction < 1 || duration === -1) && timer.alive) {
requestAnimationFrame(thread);
}
});
}
});
Class("Toggle", ClassFactory("InheritClass"), {
_toggle: false,
_inverse: true,
_positive: null,
_negative: null,
_dispatched: null,
_args: {},
changeToggle: function() {
this._toggle = (this._toggle) ? (false) : (true);
},
_new_: function({
positive,
negative,
args
}) {
this._positive = positive;
this._negative = negative;
this._args = args;
},
fire: function() {
var toggle = this;
var _promise = new Promise(function(resolve, reject) {
if (typeof toggle._positive === "function" && typeof toggle._negative === "function") {
if (toggle._inverse) {
toggle._dispatched = (toggle._toggle) ? (toggle._negative.bind(toggle)) : (toggle._positive.bind(toggle));
} else {
toggle._dispatched = (toggle._toggle) ? (toggle._positive.bind(toggle)) : (toggle._negative.bind(toggle));
}
toggle._dispatched.call(toggle, toggle._args);
resolve.call(_promise, toggle);
} else {
logger.debug("Toggle functions are not declared");
reject.call(_promise, toggle);
}
}).then(function(toggle) {
toggle.changeToggle();
}).catch(function(e) {
logger.debug(e.toString());
});
return _promise;
}
});
// Set Processors
(function (_top){
let mapper = function (componentName, valueName) {
/*
* Mapper processor
* @usage
* $mapper(<componentName>,<valueName>)
*
* Where componentName is the name of the component (same value as in attribute tag name) without quotes
* and valueName is the name of the variable that contains the value to map, it can be either a property of
* the component instance, the data object or a global value
*/
let globalValue = global.get(valueName);
let componentValue = this.component.get(valueName);
let dataValue = this.component.data[valueName];
let list = (typeof dataValue !== "undefined")?( dataValue ):( (typeof componentValue !== "undefined")?( componentValue ):( globalValue ) );
let listItems = "";
if (typeof list !== "undefined" && typeof list["map"] !== "undefined"){
listItems = list.map ( function (element) {
let dataItems = [...Object.keys(element)].map(k => ` data-${k}="${element[k].toString()}"`).join("");
return `<component name="${componentName}" ${dataItems} ></component>`;
}).join("");
} else {
logger.debug(`${componentName}.${valueName} does not have a map property`);
}
return listItems;
};
ClassFactory("Processor").setProcessor(mapper);
let layout = function (layoutname, cssfile){
/*
* Layout processor
* @usage
* $layout(<layoutname>, <cssfile>)
* Where layoutname can be "portrait" or "landscape" without quotes
* cssfile is the uri for the css file to import
*/
var layout_portrait = `
/* CSS Document for Mobile Imports */
@import url("${cssfile}") (orientation:portrait);
@import url("${cssfile}") (max-width:460px);
@import url("${cssfile}") (aspect-ratio: 9/16);
@import url("${cssfile}") (aspect-ratio: 10/16);
@import url("${cssfile}") (aspect-ratio: 5/8);
@import url("${cssfile}") (aspect-ratio: 3/4);
@import url("${cssfile}") (aspect-ratio: 2/3);
`;
var layout_landscape = `
@import url("${cssfile}") (orientation:landscape) and (min-width:460px);
@import url("${cssfile}") (aspect-ratio: 16/9) and (min-width:460px);
@import url("${cssfile}") (aspect-ratio: 16/10) and (min-width:460px);
@import url("${cssfile}") (aspect-ratio: 8/5) and (min-width:460px);
@import url("${cssfile}") (aspect-ratio: 4/3) and (min-width:460px);
@import url("${cssfile}") (aspect-ratio: 3/2) and (min-width:460px);
`;
var layout_code = {
"landscape":layout_landscape,
"portrait":layout_portrait
};
return (layout_code.hasOwnProperty.call(layout_code, layoutname))?(layout_code[layoutname]):("");
};
ClassFactory("Processor").setProcessor(layout);
let component = function () {
/*
* component processor
* @usage
* $component(name=<name>, componentClass=<componentClass>, ...)
* Returns a component tag declaration like:
* <component name=<name> ...></component>
*/
let arg = [...arguments].map(function (a){ return {[a.split("=")[0]]:a.split("=")[1]};}).reduce(function (k1, k2) {return Object.assign(k1, k2);});
let attrs = [...Object.keys(arg)].map(function (a) {return `${a}=${arg[a]}`;}).join(" ");
return `<component ${attrs}></component>`;
};
ClassFactory("Processor").setProcessor(component);
let repeat = function (length, text) {
/*
* Repeat processor
* @usage
* $repeat(<length>, <text>)
* Where length is the number of occurrences of text
*/
return _top.range(length).map(
function (index) {
return text.replace("{{index}}",index.toString());
}
).join("");
};
ClassFactory("Processor").setProcessor(repeat);
})(_top);
/**
* Load every component tag declared in the body
**/
Ready(function() {
if (!ClassFactory("CONFIG").get("useSDK")) {
global.__start__();
}
});
/*
Public variables and functions
*/
Export(Export); /* exports the same Export function once */
Export(Import);
Export(Package);
Export(Class);
Export(New);
Export(Tag);
Export(Ready);
Export(ready);
Export(isBrowser);
Export(_methods_);
if (!isBrowser) {
if (typeof global !== "undefined" && global.hasOwnProperty.call(global,"_fireAsyncLoad")) {
global._fireAsyncLoad.call(this);
}
if (typeof global !== "undefined" && global.hasOwnProperty.call(global,"onload")) {
global.onload.call(this);
}
}
if (isBrowser) {
asyncLoad(function() {
Ready(function() {
window.onpopstate = function(event) {
event.stopImmediatePropagation();
event.stopPropagation();
ClassFactory("Component").route();
};
/*
* scroll management custom events
* usage: document.addEventListener('percentY90',function(e){console.log(e.detail.percentY)});
* possible events: scrollpercent, defaultscroll, percentY0, percentY25, percentY50, percentY75, percentY90
*/
(function (_top){
let lastKnownScrollPosition = 0;
let ticking = false;
let scrollHeight = Math.max(
document.body.scrollHeight, document.documentElement.scrollHeight,
document.body.offsetHeight, document.documentElement.offsetHeight,
document.body.clientHeight, document.documentElement.clientHeight
);
let scrollWidth = Math.max(
document.body.scrollWidth, document.documentElement.scrollWidth,
document.body.offsetWidth, document.documentElement.offsetWidth,
document.body.clientWidth, document.documentElement.clientWidth
);
function scrollDispatcher(event) {
var percentY = Math.round(_top.scrollY * 100 / scrollHeight);
var percentX = Math.round(_top.scrollX * 100 / scrollWidth);
var scrollPercentEventEvent = new CustomEvent("scrollpercent", {
detail: {
percentX: percentX,
percentY: percentY
}
});
event.target.dispatchEvent(scrollPercentEventEvent);
var secondaryEventName = "defaultscroll";
var __valid_scrolls__ = [0, 5, 10, 25, 50, 75, 90, 95, 100];
__valid_scrolls__.filter(function (p) { return p===percentY;}).map (function (pY){
secondaryEventName = "percentY"+percentY.toString();
var secondaryCustomEvent = new CustomEvent(secondaryEventName, {
detail: {
percentX: percentX,
percentY: percentY
}
});
event.target.dispatchEvent(secondaryCustomEvent);
});
}
document.addEventListener("scroll", function(event) {
if (!ticking) {
requestAnimationFrame(function() {
scrollDispatcher(event);
ticking = false;
});
ticking = true;
}
});
})(_top);
});
}, null);
}
/* Freezing Object && Object.prototype to prevent prototype pollution risks */
(function (isBrowser){
var __freeze__ = function (){
Object.freeze(Object.prototype);
Object.freeze(Object);
};
if (isBrowser && CONFIG.get("secureObjects", false)){
Ready(function (){
__freeze__();
});
} else if (CONFIG.get("secureObjects", false)) {
__freeze__();
}
})(isBrowser);
}).call(null,(typeof module === "object" && typeof module.exports === "object")?(module.exports = global):((typeof global === "object")?(global):(
(typeof window === "object")?(window):({})
)));
|
var Q = require(SP_NODE_MODULES + 'q');
var Database = require(SP_MODULES_FOLDER + 'database/database.module.js');
module.exports = function (args) {
var args = args || {};
var self = new BASEITEM(args.initialAttributes);
self.req = args.req;
self.create = PROMISIFY(create);
function create(args, resolve, reject) {
Database.Message.create({ text: args.text }).then(function (newMessage) {
self.set(newMessage);
resolve();
}, function (err) {
self.error = {
message: 'Something went terribly wrong with the database module.',
database_error: err
};
reject();
})
}
return self;
}
module.exports.Collection = function(args) {
var args = args || {};
var collection = new BASECOLLECTION(args.initialItems);
collection.req = args.req;
collection.load = PROMISIFY(load);
function load(args, resolve, reject) {
Database.Message.read({ page: args.page, size: args.size }).then(function (messages) {
collection.set(messages);
resolve();
}, function (db_error) {
collection.error = {
message: 'Unable to load messages from database',
database_error: db_error
};
reject();
});
}
return collection;
} |
define(function (require) {
'use strict';
/**
* Module dependencies.
*/
var Aloha = require('aloha');
return {
/**
* Selects the text from the given range.
*
* @param {RangyRange} range
*/
selectTextFromRange: function (range) {
var selection = Aloha.getSelection();
selection.removeAllRanges();
selection.addRange(range);
}
};
});
|
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var github_service_1 = require('./services/github.service');
var packages_service_1 = require('./services/packages.service');
var core_1 = require('@angular/core');
var platform_browser_1 = require('@angular/platform-browser');
var router_1 = require('@angular/router');
var http_1 = require('@angular/http');
var app_component_1 = require('./app.component');
var sidebar_module_1 = require('./components/sidebar/sidebar.module');
var footer_module_1 = require('./components/footer/footer.module');
var navbar_module_1 = require('./components/navbar/navbar.module');
var chart_module_1 = require('./components/chart/chart.module');
var common_1 = require('@angular/common');
var cookies_service_1 = require('angular2-cookie/services/cookies.service');
var app_routing_1 = require('./app.routing');
var insights_module_1 = require('./pages/insights/insights.module');
var user_module_1 = require('./pages/user/user.module');
var repositories_module_1 = require('./pages/repositories/repositories.module');
var configure_module_1 = require('./pages/configure/configure.module');
var package_module_1 = require('./pages/package/package.module');
var login_module_1 = require('./pages/login/login.module');
var stats_service_1 = require("./services/stats.service");
var home_module_1 = require("./pages/home/home.module");
var AppModule = (function () {
function AppModule() {
}
AppModule = __decorate([
core_1.NgModule({
imports: [
http_1.HttpModule,
platform_browser_1.BrowserModule,
sidebar_module_1.SidebarModule,
footer_module_1.FooterModule,
chart_module_1.ChartModule,
navbar_module_1.NavbarModule,
router_1.RouterModule,
home_module_1.HomeModule,
repositories_module_1.RepositoriesModule,
insights_module_1.InsightsModule,
package_module_1.PackageModule,
configure_module_1.ConfigureModule,
user_module_1.UserModule,
login_module_1.LoginModule,
router_1.RouterModule.forRoot(app_routing_1.MODULE_ROUTES)
],
declarations: [
app_component_1.AppComponent
],
providers: [{ provide: common_1.LocationStrategy, useClass: common_1.HashLocationStrategy }, cookies_service_1.CookieService, github_service_1.GithubService, packages_service_1.PackagesService, stats_service_1.StatsService],
bootstrap: [app_component_1.AppComponent]
}),
__metadata('design:paramtypes', [])
], AppModule);
return AppModule;
}());
exports.AppModule = AppModule;
//# sourceMappingURL=app.module.js.map |
import React from "react";
import {Renderer} from "neutrine/lib/components";
import {Icon} from "neutrine/lib/components";
import {Media, MediaContent, MediaStart, MediaEnd} from "neutrine/lib/components";
import style from "./style.scss";
//Button component wrapper
let Button = function (props) {
return (
<div onClick={props.onClick} className={style.button}>
<Icon size="26px" icon={props.icon} />
</div>
);
};
//Export sandbox header editor component
export const SandboxHeader = function (props) {
let sandboxName = (typeof props.sandbox.name === "string") ? props.sandbox.name : "Untitled";
return (
<Media className={style.root}>
{/* Left side --> editor logo */}
<MediaStart className="siimple--flex siimple--flex-row">
<div className={style.logo} onClick={props.onLogoClick}>
<strong>jviz</strong>lab
</div>
</MediaStart>
{/* Center side --> display sandbox name and status */}
<MediaContent align="center">
<div className={style.title}>
<strong>{sandboxName}</strong>
</div>
</MediaContent>
{/* Right side --> sandbox actions */}
<MediaEnd className="siimple--flex siimple--flex-row">
<Button icon="save" onClick={props.onSaveClick} />
<Button icon="download" onClick={props.onExportClick} />
<Button icon="gear" onClick={props.onConfigClick} />
<div className={style.divider} />
<Button icon="trash" onClick={props.onDeleteClick} />
</MediaEnd>
</Media>
);
};
//Editor header default props
SandboxHeader.defaultProps = {
"sandbox": {},
"onLogoClick": null,
"onSaveClick": null,
"onExportClick": null,
"onConfigClick": null,
"onDeleteClick": null
};
|
/**
* @license Highstock JS v8.1.0 (2020-05-05)
*
* Indicator series type for Highstock
*
* (c) 2010-2019 Kacper Madej
*
* License: www.highcharts.com/license
*/
'use strict';
(function (factory) {
if (typeof module === 'object' && module.exports) {
factory['default'] = factory;
module.exports = factory;
} else if (typeof define === 'function' && define.amd) {
define('highcharts/indicators/roc', ['highcharts', 'highcharts/modules/stock'], function (Highcharts) {
factory(Highcharts);
factory.Highcharts = Highcharts;
return factory;
});
} else {
factory(typeof Highcharts !== 'undefined' ? Highcharts : undefined);
}
}(function (Highcharts) {
var _modules = Highcharts ? Highcharts._modules : {};
function _registerModule(obj, path, args, fn) {
if (!obj.hasOwnProperty(path)) {
obj[path] = fn.apply(null, args);
}
}
_registerModule(_modules, 'indicators/roc.src.js', [_modules['parts/Utilities.js']], function (U) {
/* *
*
* (c) 2010-2020 Kacper Madej
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
var isArray = U.isArray,
seriesType = U.seriesType;
/* eslint-disable require-jsdoc */
// Utils:
function populateAverage(xVal, yVal, i, period, index) {
/* Calculated as:
(Closing Price [today] - Closing Price [n days ago]) /
Closing Price [n days ago] * 100
Return y as null when avoiding division by zero */
var nDaysAgoY,
rocY;
if (index < 0) {
// y data given as an array of values
nDaysAgoY = yVal[i - period];
rocY = nDaysAgoY ?
(yVal[i] - nDaysAgoY) / nDaysAgoY * 100 :
null;
}
else {
// y data given as an array of arrays and the index should be used
nDaysAgoY = yVal[i - period][index];
rocY = nDaysAgoY ?
(yVal[i][index] - nDaysAgoY) / nDaysAgoY * 100 :
null;
}
return [xVal[i], rocY];
}
/* eslint-enable require-jsdoc */
/**
* The ROC series type.
*
* @private
* @class
* @name Highcharts.seriesTypes.roc
*
* @augments Highcharts.Series
*/
seriesType('roc', 'sma',
/**
* Rate of change indicator (ROC). The indicator value for each point
* is defined as:
*
* `(C - Cn) / Cn * 100`
*
* where: `C` is the close value of the point of the same x in the
* linked series and `Cn` is the close value of the point `n` periods
* ago. `n` is set through [period](#plotOptions.roc.params.period).
*
* This series requires `linkedTo` option to be set.
*
* @sample stock/indicators/roc
* Rate of change indicator
*
* @extends plotOptions.sma
* @since 6.0.0
* @product highstock
* @requires stock/indicators/indicators
* @requires stock/indicators/roc
* @optionparent plotOptions.roc
*/
{
params: {
index: 3,
period: 9
}
},
/**
* @lends Highcharts.Series#
*/
{
nameBase: 'Rate of Change',
getValues: function (series, params) {
var period = params.period,
xVal = series.xData,
yVal = series.yData,
yValLen = yVal ? yVal.length : 0,
ROC = [],
xData = [],
yData = [],
i,
index = -1,
ROCPoint;
// Period is used as a number of time periods ago, so we need more
// (at least 1 more) data than the period value
if (xVal.length <= period) {
return;
}
// Switch index for OHLC / Candlestick / Arearange
if (isArray(yVal[0])) {
index = params.index;
}
// i = period <-- skip first N-points
// Calculate value one-by-one for each period in visible data
for (i = period; i < yValLen; i++) {
ROCPoint = populateAverage(xVal, yVal, i, period, index);
ROC.push(ROCPoint);
xData.push(ROCPoint[0]);
yData.push(ROCPoint[1]);
}
return {
values: ROC,
xData: xData,
yData: yData
};
}
});
/**
* A `ROC` series. If the [type](#series.wma.type) option is not
* specified, it is inherited from [chart.type](#chart.type).
*
* Rate of change indicator (ROC). The indicator value for each point
* is defined as:
*
* `(C - Cn) / Cn * 100`
*
* where: `C` is the close value of the point of the same x in the
* linked series and `Cn` is the close value of the point `n` periods
* ago. `n` is set through [period](#series.roc.params.period).
*
* This series requires `linkedTo` option to be set.
*
* @extends series,plotOptions.roc
* @since 6.0.0
* @product highstock
* @excluding dataParser, dataURL
* @requires stock/indicators/indicators
* @requires stock/indicators/roc
* @apioption series.roc
*/
''; // to include the above in the js output
});
_registerModule(_modules, 'masters/indicators/roc.src.js', [], function () {
});
})); |
/*!
* vue-router v4.0.0-rc.4
* (c) 2020 Eduardo San Martin Morote
* @license MIT
*/
import { getCurrentInstance, inject, onUnmounted, onDeactivated, onActivated, computed, unref, defineComponent, reactive, h, provide, ref, watch, shallowRef, nextTick } from 'vue';
const hasSymbol = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol';
const PolySymbol = (name) =>
// vr = vue router
hasSymbol
? Symbol((process.env.NODE_ENV !== 'production') ? '[vue-router]: ' + name : name)
: ((process.env.NODE_ENV !== 'production') ? '[vue-router]: ' : '_vr_') + name;
// rvlm = Router View Location Matched
/**
* RouteRecord being rendered by the closest ancestor Router View. Used for
* `onBeforeRouteUpdate` and `onBeforeRouteLeave`. rvlm stands for Router View
* Location Matched
*
* @internal
*/
const matchedRouteKey = /*#__PURE__*/ PolySymbol((process.env.NODE_ENV !== 'production') ? 'router view location matched' : 'rvlm');
/**
* Allows overriding the router view depth to control which component in
* `matched` is rendered. rvd stands for Router View Depth
*
* @internal
*/
const viewDepthKey = /*#__PURE__*/ PolySymbol((process.env.NODE_ENV !== 'production') ? 'router view depth' : 'rvd');
/**
* Allows overriding the router instance returned by `useRouter` in tests. r stands for router
*
* @internal
*/
const routerKey = /*#__PURE__*/ PolySymbol((process.env.NODE_ENV !== 'production') ? 'router' : 'r');
/**
* Allows overriding the current route returned by `useRoute` in tests. rl stands for route location
*
* @internal
*/
const routeLocationKey = /*#__PURE__*/ PolySymbol((process.env.NODE_ENV !== 'production') ? 'route location' : 'rl');
const isBrowser = typeof window !== 'undefined';
function isESModule(obj) {
return obj.__esModule || (hasSymbol && obj[Symbol.toStringTag] === 'Module');
}
const assign = Object.assign;
function applyToParams(fn, params) {
const newParams = {};
for (const key in params) {
const value = params[key];
newParams[key] = Array.isArray(value) ? value.map(fn) : fn(value);
}
return newParams;
}
let noop = () => { };
function warn(msg) {
// avoid using ...args as it breaks in older Edge builds
const args = Array.from(arguments).slice(1);
console.warn.apply(console, ['[Vue Router warn]: ' + msg].concat(args));
}
const TRAILING_SLASH_RE = /\/$/;
const removeTrailingSlash = (path) => path.replace(TRAILING_SLASH_RE, '');
/**
* Transforms an URI into a normalized history location
*
* @param parseQuery
* @param location - URI to normalize
* @param currentLocation - current absolute location. Allows resolving relative
* paths. Must start with `/`. Defaults to `/`
* @returns a normalized history location
*/
function parseURL(parseQuery, location, currentLocation = '/') {
let path, query = {}, searchString = '', hash = '';
// Could use URL and URLSearchParams but IE 11 doesn't support it
const searchPos = location.indexOf('?');
const hashPos = location.indexOf('#', searchPos > -1 ? searchPos : 0);
if (searchPos > -1) {
path = location.slice(0, searchPos);
searchString = location.slice(searchPos + 1, hashPos > -1 ? hashPos : location.length);
query = parseQuery(searchString);
}
if (hashPos > -1) {
path = path || location.slice(0, hashPos);
// keep the # character
hash = location.slice(hashPos, location.length);
}
// no search and no query
path = resolveRelativePath(path != null ? path : location, currentLocation);
// empty path means a relative query or hash `?foo=f`, `#thing`
return {
fullPath: path + (searchString && '?') + searchString + hash,
path,
query,
hash,
};
}
/**
* Stringifies a URL object
*
* @param stringifyQuery
* @param location
*/
function stringifyURL(stringifyQuery, location) {
let query = location.query ? stringifyQuery(location.query) : '';
return location.path + (query && '?') + query + (location.hash || '');
}
/**
* Strips off the base from the beginning of a location.pathname in a non
* case-sensitive way.
*
* @param pathname - location.pathname
* @param base - base to strip off
*/
function stripBase(pathname, base) {
// no base or base is not found at the beginning
if (!base || pathname.toLowerCase().indexOf(base.toLowerCase()))
return pathname;
return pathname.slice(base.length) || '/';
}
/**
* Checks if two RouteLocation are equal. This means that both locations are
* pointing towards the same {@link RouteRecord} and that all `params`, `query`
* parameters and `hash` are the same
*
* @param a - first {@link RouteLocation}
* @param b - second {@link RouteLocation}
*/
function isSameRouteLocation(stringifyQuery, a, b) {
let aLastIndex = a.matched.length - 1;
let bLastIndex = b.matched.length - 1;
return (aLastIndex > -1 &&
aLastIndex === bLastIndex &&
isSameRouteRecord(a.matched[aLastIndex], b.matched[bLastIndex]) &&
isSameRouteLocationParams(a.params, b.params) &&
stringifyQuery(a.query) === stringifyQuery(b.query) &&
a.hash === b.hash);
}
/**
* Check if two `RouteRecords` are equal. Takes into account aliases: they are
* considered equal to the `RouteRecord` they are aliasing.
*
* @param a - first {@link RouteRecord}
* @param b - second {@link RouteRecord}
*/
function isSameRouteRecord(a, b) {
// since the original record has an undefined value for aliasOf
// but all aliases point to the original record, this will always compare
// the original record
return (a.aliasOf || a) === (b.aliasOf || b);
}
function isSameRouteLocationParams(a, b) {
if (Object.keys(a).length !== Object.keys(b).length)
return false;
for (let key in a) {
if (!isSameRouteLocationParamsValue(a[key], b[key]))
return false;
}
return true;
}
function isSameRouteLocationParamsValue(a, b) {
return Array.isArray(a)
? isEquivalentArray(a, b)
: Array.isArray(b)
? isEquivalentArray(b, a)
: a === b;
}
/**
* Check if two arrays are the same or if an array with one single entry is the
* same as another primitive value. Used to check query and parameters
*
* @param a - array of values
* @param b - array of values or a single value
*/
function isEquivalentArray(a, b) {
return Array.isArray(b)
? a.length === b.length && a.every((value, i) => value === b[i])
: a.length === 1 && a[0] === b;
}
/**
* Resolves a relative path that starts with `.`.
*
* @param to - path location we are resolving
* @param from - currentLocation.path, should start with `/`
*/
function resolveRelativePath(to, from) {
if (to.startsWith('/'))
return to;
if ((process.env.NODE_ENV !== 'production') && !from.startsWith('/')) {
warn(`Cannot resolve a relative location without an absolute path. Trying to resolve "${to}" from "${from}". It should look like "/${from}".`);
return to;
}
if (!to)
return from;
const fromSegments = from.split('/');
const toSegments = to.split('/');
let position = fromSegments.length - 1;
let toPosition;
let segment;
for (toPosition = 0; toPosition < toSegments.length; toPosition++) {
segment = toSegments[toPosition];
// can't go below zero
if (position === 1 || segment === '.')
continue;
if (segment === '..')
position--;
// found something that is not relative path
else
break;
}
return (fromSegments.slice(0, position).join('/') +
'/' +
toSegments
.slice(toPosition - (toPosition === toSegments.length ? 1 : 0))
.join('/'));
}
var NavigationType;
(function (NavigationType) {
NavigationType["pop"] = "pop";
NavigationType["push"] = "push";
})(NavigationType || (NavigationType = {}));
var NavigationDirection;
(function (NavigationDirection) {
NavigationDirection["back"] = "back";
NavigationDirection["forward"] = "forward";
NavigationDirection["unknown"] = "";
})(NavigationDirection || (NavigationDirection = {}));
/**
* Starting location for Histories
*/
const START = '';
// Generic utils
/**
* Normalizes a base by removing any trailing slash and reading the base tag if
* present.
*
* @param base - base to normalize
*/
function normalizeBase(base) {
if (!base) {
if (isBrowser) {
// respect <base> tag
const baseEl = document.querySelector('base');
base = (baseEl && baseEl.getAttribute('href')) || '/';
// strip full URL origin
base = base.replace(/^\w+:\/\/[^\/]+/, '');
}
else {
base = '/';
}
}
// ensure leading slash when it was removed by the regex above avoid leading
// slash with hash because the file could be read from the disk like file://
// and the leading slash would cause problems
if (base[0] !== '/' && base[0] !== '#')
base = '/' + base;
// remove the trailing slash so all other method can just do `base + fullPath`
// to build an href
return removeTrailingSlash(base);
}
// remove any character before the hash
const BEFORE_HASH_RE = /^[^#]+#/;
function createHref(base, location) {
return base.replace(BEFORE_HASH_RE, '#') + location;
}
function getElementPosition(el, offset) {
const docRect = document.documentElement.getBoundingClientRect();
const elRect = el.getBoundingClientRect();
return {
behavior: offset.behavior,
left: elRect.left - docRect.left - (offset.left || 0),
top: elRect.top - docRect.top - (offset.top || 0),
};
}
const computeScrollPosition = () => ({
left: window.pageXOffset,
top: window.pageYOffset,
});
function scrollToPosition(position) {
let scrollToOptions;
if ('el' in position) {
let positionEl = position.el;
const isIdSelector = typeof positionEl === 'string' && positionEl.startsWith('#');
/**
* `id`s can accept pretty much any characters, including CSS combinators
* like `>` or `~`. It's still possible to retrieve elements using
* `document.getElementById('~')` but it needs to be escaped when using
* `document.querySelector('#\\~')` for it to be valid. The only
* requirements for `id`s are them to be unique on the page and to not be
* empty (`id=""`). Because of that, when passing an id selector, it should
* be properly escaped for it to work with `querySelector`. We could check
* for the id selector to be simple (no CSS combinators `+ >~`) but that
* would make things inconsistent since they are valid characters for an
* `id` but would need to be escaped when using `querySelector`, breaking
* their usage and ending up in no selector returned. Selectors need to be
* escaped:
*
* - `#1-thing` becomes `#\31 -thing`
* - `#with~symbols` becomes `#with\\~symbols`
*
* - More information about the topic can be found at
* https://mathiasbynens.be/notes/html5-id-class.
* - Practical example: https://mathiasbynens.be/demo/html5-id
*/
if ((process.env.NODE_ENV !== 'production') && typeof position.el === 'string') {
if (!isIdSelector || !document.getElementById(position.el.slice(1))) {
try {
let foundEl = document.querySelector(position.el);
if (isIdSelector && foundEl) {
warn(`The selector "${position.el}" should be passed as "el: document.querySelector('${position.el}')" because it starts with "#".`);
// return to avoid other warnings
return;
}
}
catch (err) {
warn(`The selector "${position.el}" is invalid. If you are using an id selector, make sure to escape it. You can find more information about escaping characters in selectors at https://mathiasbynens.be/notes/css-escapes or use CSS.escape (https://developer.mozilla.org/en-US/docs/Web/API/CSS/escape).`);
// return to avoid other warnings
return;
}
}
}
const el = typeof positionEl === 'string'
? isIdSelector
? document.getElementById(positionEl.slice(1))
: document.querySelector(positionEl)
: positionEl;
if (!el) {
(process.env.NODE_ENV !== 'production') &&
warn(`Couldn't find element using selector "${position.el}" returned by scrollBehavior.`);
return;
}
scrollToOptions = getElementPosition(el, position);
}
else {
scrollToOptions = position;
}
if ('scrollBehavior' in document.documentElement.style)
window.scrollTo(scrollToOptions);
else {
window.scrollTo(scrollToOptions.left != null ? scrollToOptions.left : window.pageXOffset, scrollToOptions.top != null ? scrollToOptions.top : window.pageYOffset);
}
}
function getScrollKey(path, delta) {
const position = history.state ? history.state.position - delta : -1;
return position + path;
}
const scrollPositions = new Map();
function saveScrollPosition(key, scrollPosition) {
scrollPositions.set(key, scrollPosition);
}
function getSavedScrollPosition(key) {
const scroll = scrollPositions.get(key);
// consume it so it's not used again
scrollPositions.delete(key);
return scroll;
}
// TODO: RFC about how to save scroll position
/**
* ScrollBehavior instance used by the router to compute and restore the scroll
* position when navigating.
*/
// export interface ScrollHandler<ScrollPositionEntry extends HistoryStateValue, ScrollPosition extends ScrollPositionEntry> {
// // returns a scroll position that can be saved in history
// compute(): ScrollPositionEntry
// // can take an extended ScrollPositionEntry
// scroll(position: ScrollPosition): void
// }
// export const scrollHandler: ScrollHandler<ScrollPosition> = {
// compute: computeScroll,
// scroll: scrollToPosition,
// }
let createBaseLocation = () => location.protocol + '//' + location.host;
/**
* Creates a normalized history location from a window.location object
* @param location -
*/
function createCurrentLocation(base, location) {
const { pathname, search, hash } = location;
// allows hash based url
const hashPos = base.indexOf('#');
if (hashPos > -1) {
// prepend the starting slash to hash so the url starts with /#
let pathFromHash = hash.slice(1);
if (pathFromHash[0] !== '/')
pathFromHash = '/' + pathFromHash;
return stripBase(pathFromHash, '');
}
const path = stripBase(pathname, base);
return path + search + hash;
}
function useHistoryListeners(base, historyState, currentLocation, replace) {
let listeners = [];
let teardowns = [];
// TODO: should it be a stack? a Dict. Check if the popstate listener
// can trigger twice
let pauseState = null;
const popStateHandler = ({ state, }) => {
const to = createCurrentLocation(base, location);
const from = currentLocation.value;
const fromState = historyState.value;
let delta = 0;
if (state) {
currentLocation.value = to;
historyState.value = state;
// ignore the popstate and reset the pauseState
if (pauseState && pauseState === from) {
pauseState = null;
return;
}
delta = fromState ? state.position - fromState.position : 0;
}
else {
replace(to);
}
// console.log({ deltaFromCurrent })
// Here we could also revert the navigation by calling history.go(-delta)
// this listener will have to be adapted to not trigger again and to wait for the url
// to be updated before triggering the listeners. Some kind of validation function would also
// need to be passed to the listeners so the navigation can be accepted
// call all listeners
listeners.forEach(listener => {
listener(currentLocation.value, from, {
delta,
type: NavigationType.pop,
direction: delta
? delta > 0
? NavigationDirection.forward
: NavigationDirection.back
: NavigationDirection.unknown,
});
});
};
function pauseListeners() {
pauseState = currentLocation.value;
}
function listen(callback) {
// setup the listener and prepare teardown callbacks
listeners.push(callback);
const teardown = () => {
const index = listeners.indexOf(callback);
if (index > -1)
listeners.splice(index, 1);
};
teardowns.push(teardown);
return teardown;
}
function beforeUnloadListener() {
const { history } = window;
if (!history.state)
return;
history.replaceState(assign({}, history.state, { scroll: computeScrollPosition() }), '');
}
function destroy() {
for (const teardown of teardowns)
teardown();
teardowns = [];
window.removeEventListener('popstate', popStateHandler);
window.removeEventListener('beforeunload', beforeUnloadListener);
}
// setup the listeners and prepare teardown callbacks
window.addEventListener('popstate', popStateHandler);
window.addEventListener('beforeunload', beforeUnloadListener);
return {
pauseListeners,
listen,
destroy,
};
}
/**
* Creates a state object
*/
function buildState(back, current, forward, replaced = false, computeScroll = false) {
return {
back,
current,
forward,
replaced,
position: window.history.length,
scroll: computeScroll ? computeScrollPosition() : null,
};
}
function useHistoryStateNavigation(base) {
const { history, location } = window;
// private variables
let currentLocation = {
value: createCurrentLocation(base, location),
};
let historyState = { value: history.state };
// build current history entry as this is a fresh navigation
if (!historyState.value) {
changeLocation(currentLocation.value, {
back: null,
current: currentLocation.value,
forward: null,
// the length is off by one, we need to decrease it
position: history.length - 1,
replaced: true,
// don't add a scroll as the user may have an anchor and we want
// scrollBehavior to be triggered without a saved position
scroll: null,
}, true);
}
function changeLocation(to, state, replace) {
// when the base has a `#`, only use that for the URL
const hashIndex = base.indexOf('#');
const url = hashIndex > -1
? base.slice(hashIndex) + to
: createBaseLocation() + base + to;
try {
// BROWSER QUIRK
// NOTE: Safari throws a SecurityError when calling this function 100 times in 30 seconds
history[replace ? 'replaceState' : 'pushState'](state, '', url);
historyState.value = state;
}
catch (err) {
if ((process.env.NODE_ENV !== 'production')) {
warn('Error with push/replace State', err);
}
else {
console.error(err);
}
// Force the navigation, this also resets the call count
location[replace ? 'replace' : 'assign'](url);
}
}
function replace(to, data) {
const state = assign({}, history.state, buildState(historyState.value.back,
// keep back and forward entries but override current position
to, historyState.value.forward, true), data, { position: historyState.value.position });
changeLocation(to, state, true);
currentLocation.value = to;
}
function push(to, data) {
// Add to current entry the information of where we are going
// as well as saving the current position
const currentState = assign({},
// use current history state to gracefully handle a wrong call to
// history.replaceState
// https://github.com/vuejs/vue-router-next/issues/366
historyState.value, history.state, {
forward: to,
scroll: computeScrollPosition(),
});
if ((process.env.NODE_ENV !== 'production') && !history.state) {
warn(`history.state seems to have been manually replaced without preserving the necessary values. Make sure to preserve existing history state if you are manually calling history.replaceState:\n\n` +
`history.replaceState(history.state, '', url)\n\n` +
`You can find more information at https://next.router.vuejs.org/guide/migration/#usage-of-history-state.`);
}
changeLocation(currentState.current, currentState, true);
const state = assign({}, buildState(currentLocation.value, to, null), { position: currentState.position + 1 }, data);
changeLocation(to, state, false);
currentLocation.value = to;
}
return {
location: currentLocation,
state: historyState,
push,
replace,
};
}
/**
* Creates an HTML5 history. Most common history for single page applications.
*
* @param base -
*/
function createWebHistory(base) {
base = normalizeBase(base);
const historyNavigation = useHistoryStateNavigation(base);
const historyListeners = useHistoryListeners(base, historyNavigation.state, historyNavigation.location, historyNavigation.replace);
function go(delta, triggerListeners = true) {
if (!triggerListeners)
historyListeners.pauseListeners();
history.go(delta);
}
const routerHistory = assign({
// it's overridden right after
location: '',
base,
go,
createHref: createHref.bind(null, base),
}, historyNavigation, historyListeners);
Object.defineProperty(routerHistory, 'location', {
get: () => historyNavigation.location.value,
});
Object.defineProperty(routerHistory, 'state', {
get: () => historyNavigation.state.value,
});
return routerHistory;
}
/**
* Creates a in-memory based history. The main purpose of this history is to handle SSR. It starts in a special location that is nowhere.
* It's up to the user to replace that location with the starter location by either calling `router.push` or `router.replace`.
*
* @param base - Base applied to all urls, defaults to '/'
* @returns a history object that can be passed to the router constructor
*/
function createMemoryHistory(base = '') {
let listeners = [];
let queue = [START];
let position = 0;
function setLocation(location) {
position++;
if (position === queue.length) {
// we are at the end, we can simply append a new entry
queue.push(location);
}
else {
// we are in the middle, we remove everything from here in the queue
queue.splice(position);
queue.push(location);
}
}
function triggerListeners(to, from, { direction, delta }) {
const info = {
direction,
delta,
type: NavigationType.pop,
};
for (let callback of listeners) {
callback(to, from, info);
}
}
const routerHistory = {
// rewritten by Object.defineProperty
location: START,
state: {},
base,
createHref: createHref.bind(null, base),
replace(to) {
// remove current entry and decrement position
queue.splice(position--, 1);
setLocation(to);
},
push(to, data) {
setLocation(to);
},
listen(callback) {
listeners.push(callback);
return () => {
const index = listeners.indexOf(callback);
if (index > -1)
listeners.splice(index, 1);
};
},
destroy() {
listeners = [];
},
go(delta, shouldTrigger = true) {
const from = this.location;
const direction =
// we are considering delta === 0 going forward, but in abstract mode
// using 0 for the delta doesn't make sense like it does in html5 where
// it reloads the page
delta < 0 ? NavigationDirection.back : NavigationDirection.forward;
position = Math.max(0, Math.min(position + delta, queue.length - 1));
if (shouldTrigger) {
triggerListeners(this.location, from, {
direction,
delta,
});
}
},
};
Object.defineProperty(routerHistory, 'location', {
get: () => queue[position],
});
return routerHistory;
}
/**
* Creates a hash history. Useful for web applications with no host (e.g.
* `file://`) or when configuring a server to handle any URL.
*
* @param base - optional base to provide. Defaults to `location.pathname` or
* `/` if at root. If there is a `base` tag in the `head`, its value will be
* **ignored**.
*
* @example
* ```js
* // at https://example.com/folder
* createWebHashHistory() // gives a url of `https://example.com/folder#`
* createWebHashHistory('/folder/') // gives a url of `https://example.com/folder/#`
* // if the `#` is provided in the base, it won't be added by `createWebHashHistory`
* createWebHashHistory('/folder/#/app/') // gives a url of `https://example.com/folder/#/app/`
* // you should avoid doing this because it changes the original url and breaks copying urls
* createWebHashHistory('/other-folder/') // gives a url of `https://example.com/other-folder/#`
*
* // at file:///usr/etc/folder/index.html
* // for locations with no `host`, the base is ignored
* createWebHashHistory('/iAmIgnored') // gives a url of `file:///usr/etc/folder/index.html#`
* ```
*/
function createWebHashHistory(base) {
// Make sure this implementation is fine in terms of encoding, specially for IE11
// for `file://`, directly use the pathname and ignore the base
// location.pathname contains an initial `/` even at the root: `https://example.com`
base = location.host ? base || location.pathname : '';
// allow the user to provide a `#` in the middle: `/base/#/app`
if (base.indexOf('#') < 0)
base += '#';
if ((process.env.NODE_ENV !== 'production') && !base.endsWith('#/') && !base.endsWith('#')) {
warn(`A hash base must end with a "#":\n"${base}" should be "${base.replace(/#.*$/, '#')}".`);
}
return createWebHistory(base);
}
function isRouteLocation(route) {
return typeof route === 'string' || (route && typeof route === 'object');
}
function isRouteName(name) {
return typeof name === 'string' || typeof name === 'symbol';
}
/**
* Initial route location where the router is. Can be used in navigation guards
* to differentiate the initial navigation.
*
* @example
* ```js
* import { START_LOCATION } from 'vue-router'
*
* router.beforeEach((to, from) => {
* if (from === START_LOCATION) {
* // initial navigation
* }
* })
* ```
*/
const START_LOCATION_NORMALIZED = {
path: '/',
name: undefined,
params: {},
query: {},
hash: '',
fullPath: '/',
matched: [],
meta: {},
redirectedFrom: undefined,
};
const NavigationFailureSymbol = /*#__PURE__*/ PolySymbol((process.env.NODE_ENV !== 'production') ? 'navigation failure' : 'nf');
/**
* Enumeration with all possible types for navigation failures. Can be passed to
* {@link isNavigationFailure} to check for specific failures.
*/
var NavigationFailureType;
(function (NavigationFailureType) {
/**
* An aborted navigation is a navigation that failed because a navigation
* guard returned `false` or called `next(false)`
*/
NavigationFailureType[NavigationFailureType["aborted"] = 4] = "aborted";
/**
* A cancelled navigation is a navigation that failed because a more recent
* navigation finished started (not necessarily finished).
*/
NavigationFailureType[NavigationFailureType["cancelled"] = 8] = "cancelled";
/**
* A duplicated navigation is a navigation that failed because it was
* initiated while already being at the exact same location.
*/
NavigationFailureType[NavigationFailureType["duplicated"] = 16] = "duplicated";
})(NavigationFailureType || (NavigationFailureType = {}));
// DEV only debug messages
const ErrorTypeMessages = {
[1 /* MATCHER_NOT_FOUND */]({ location, currentLocation }) {
return `No match for\n ${JSON.stringify(location)}${currentLocation
? '\nwhile being at\n' + JSON.stringify(currentLocation)
: ''}`;
},
[2 /* NAVIGATION_GUARD_REDIRECT */]({ from, to, }) {
return `Redirected from "${from.fullPath}" to "${stringifyRoute(to)}" via a navigation guard.`;
},
[4 /* NAVIGATION_ABORTED */]({ from, to }) {
return `Navigation aborted from "${from.fullPath}" to "${to.fullPath}" via a navigation guard.`;
},
[8 /* NAVIGATION_CANCELLED */]({ from, to }) {
return `Navigation cancelled from "${from.fullPath}" to "${to.fullPath}" with a new navigation.`;
},
[16 /* NAVIGATION_DUPLICATED */]({ from, to }) {
return `Avoided redundant navigation to current location: "${from.fullPath}".`;
},
};
function createRouterError(type, params) {
if ((process.env.NODE_ENV !== 'production') || !true) {
return assign(new Error(ErrorTypeMessages[type](params)), {
type,
[NavigationFailureSymbol]: true,
}, params);
}
else {
return assign(new Error(), {
type,
[NavigationFailureSymbol]: true,
}, params);
}
}
function isNavigationFailure(error, type) {
return (error instanceof Error &&
NavigationFailureSymbol in error &&
(type == null || !!(error.type & type)));
}
const propertiesToLog = ['params', 'query', 'hash'];
function stringifyRoute(to) {
if (typeof to === 'string')
return to;
if ('path' in to)
return to.path;
const location = {};
for (const key of propertiesToLog) {
if (key in to)
location[key] = to[key];
}
return JSON.stringify(location, null, 2);
}
// default pattern for a param: non greedy everything but /
const BASE_PARAM_PATTERN = '[^/]+?';
const BASE_PATH_PARSER_OPTIONS = {
sensitive: false,
strict: false,
start: true,
end: true,
};
// Special Regex characters that must be escaped in static tokens
const REGEX_CHARS_RE = /[.+*?^${}()[\]/\\]/g;
/**
* Creates a path parser from an array of Segments (a segment is an array of Tokens)
*
* @param segments - array of segments returned by tokenizePath
* @param extraOptions - optional options for the regexp
* @returns a PathParser
*/
function tokensToParser(segments, extraOptions) {
const options = assign({}, BASE_PATH_PARSER_OPTIONS, extraOptions);
// the amount of scores is the same as the length of segments except for the root segment "/"
let score = [];
// the regexp as a string
let pattern = options.start ? '^' : '';
// extracted keys
const keys = [];
for (const segment of segments) {
// the root segment needs special treatment
const segmentScores = segment.length ? [] : [90 /* Root */];
// allow trailing slash
if (options.strict && !segment.length)
pattern += '/';
for (let tokenIndex = 0; tokenIndex < segment.length; tokenIndex++) {
const token = segment[tokenIndex];
// resets the score if we are inside a sub segment /:a-other-:b
let subSegmentScore = 40 /* Segment */ +
(options.sensitive ? 0.25 /* BonusCaseSensitive */ : 0);
if (token.type === 0 /* Static */) {
// prepend the slash if we are starting a new segment
if (!tokenIndex)
pattern += '/';
pattern += token.value.replace(REGEX_CHARS_RE, '\\$&');
subSegmentScore += 40 /* Static */;
}
else if (token.type === 1 /* Param */) {
const { value, repeatable, optional, regexp } = token;
keys.push({
name: value,
repeatable,
optional,
});
const re = regexp ? regexp : BASE_PARAM_PATTERN;
// the user provided a custom regexp /:id(\\d+)
if (re !== BASE_PARAM_PATTERN) {
subSegmentScore += 10 /* BonusCustomRegExp */;
// make sure the regexp is valid before using it
try {
new RegExp(`(${re})`);
}
catch (err) {
throw new Error(`Invalid custom RegExp for param "${value}" (${re}): ` +
err.message);
}
}
// when we repeat we must take care of the repeating leading slash
let subPattern = repeatable ? `((?:${re})(?:/(?:${re}))*)` : `(${re})`;
// prepend the slash if we are starting a new segment
if (!tokenIndex)
subPattern = optional ? `(?:/${subPattern})` : '/' + subPattern;
if (optional)
subPattern += '?';
pattern += subPattern;
subSegmentScore += 20 /* Dynamic */;
if (optional)
subSegmentScore += -8 /* BonusOptional */;
if (repeatable)
subSegmentScore += -20 /* BonusRepeatable */;
if (re === '.*')
subSegmentScore += -50 /* BonusWildcard */;
}
segmentScores.push(subSegmentScore);
}
// an empty array like /home/ -> [[{home}], []]
// if (!segment.length) pattern += '/'
score.push(segmentScores);
}
// only apply the strict bonus to the last score
if (options.strict && options.end) {
const i = score.length - 1;
score[i][score[i].length - 1] += 0.7000000000000001 /* BonusStrict */;
}
// TODO: dev only warn double trailing slash
if (!options.strict)
pattern += '/?';
if (options.end)
pattern += '$';
// allow paths like /dynamic to only match dynamic or dynamic/... but not dynamic_something_else
else if (options.strict)
pattern += '(?:/|$)';
const re = new RegExp(pattern, options.sensitive ? '' : 'i');
function parse(path) {
const match = path.match(re);
const params = {};
if (!match)
return null;
for (let i = 1; i < match.length; i++) {
const value = match[i] || '';
const key = keys[i - 1];
params[key.name] = value && key.repeatable ? value.split('/') : value;
}
return params;
}
function stringify(params) {
let path = '';
// for optional parameters to allow to be empty
let avoidDuplicatedSlash = false;
for (const segment of segments) {
if (!avoidDuplicatedSlash || !path.endsWith('/'))
path += '/';
avoidDuplicatedSlash = false;
for (const token of segment) {
if (token.type === 0 /* Static */) {
path += token.value;
}
else if (token.type === 1 /* Param */) {
const { value, repeatable, optional } = token;
const param = value in params ? params[value] : '';
if (Array.isArray(param) && !repeatable)
throw new Error(`Provided param "${value}" is an array but it is not repeatable (* or + modifiers)`);
const text = Array.isArray(param) ? param.join('/') : param;
if (!text) {
if (optional) {
// remove the last slash as we could be at the end
if (path.endsWith('/'))
path = path.slice(0, -1);
// do not append a slash on the next iteration
else
avoidDuplicatedSlash = true;
}
else
throw new Error(`Missing required param "${value}"`);
}
path += text;
}
}
}
return path;
}
return {
re,
score,
keys,
parse,
stringify,
};
}
/**
* Compares an array of numbers as used in PathParser.score and returns a
* number. This function can be used to `sort` an array
* @param a - first array of numbers
* @param b - second array of numbers
* @returns 0 if both are equal, < 0 if a should be sorted first, > 0 if b
* should be sorted first
*/
function compareScoreArray(a, b) {
let i = 0;
while (i < a.length && i < b.length) {
const diff = b[i] - a[i];
// only keep going if diff === 0
if (diff)
return diff;
i++;
}
// if the last subsegment was Static, the shorter segments should be sorted first
// otherwise sort the longest segment first
if (a.length < b.length) {
return a.length === 1 && a[0] === 40 /* Static */ + 40 /* Segment */
? -1
: 1;
}
else if (a.length > b.length) {
return b.length === 1 && b[0] === 40 /* Static */ + 40 /* Segment */
? 1
: -1;
}
return 0;
}
/**
* Compare function that can be used with `sort` to sort an array of PathParser
* @param a - first PathParser
* @param b - second PathParser
* @returns 0 if both are equal, < 0 if a should be sorted first, > 0 if b
*/
function comparePathParserScore(a, b) {
let i = 0;
const aScore = a.score;
const bScore = b.score;
while (i < aScore.length && i < bScore.length) {
const comp = compareScoreArray(aScore[i], bScore[i]);
// do not return if both are equal
if (comp)
return comp;
i++;
}
// if a and b share the same score entries but b has more, sort b first
return bScore.length - aScore.length;
// this is the ternary version
// return aScore.length < bScore.length
// ? 1
// : aScore.length > bScore.length
// ? -1
// : 0
}
const ROOT_TOKEN = {
type: 0 /* Static */,
value: '',
};
const VALID_PARAM_RE = /[a-zA-Z0-9_]/;
// After some profiling, the cache seems to be unnecessary because tokenizePath
// (the slowest part of adding a route) is very fast
// const tokenCache = new Map<string, Token[][]>()
function tokenizePath(path) {
if (!path)
return [[]];
if (path === '/')
return [[ROOT_TOKEN]];
if (!path.startsWith('/')) {
throw new Error((process.env.NODE_ENV !== 'production')
? `Route paths should start with a "/": "${path}" should be "/${path}".`
: `Invalid path "${path}"`);
}
// if (tokenCache.has(path)) return tokenCache.get(path)!
function crash(message) {
throw new Error(`ERR (${state})/"${buffer}": ${message}`);
}
let state = 0 /* Static */;
let previousState = state;
const tokens = [];
// the segment will always be valid because we get into the initial state
// with the leading /
let segment;
function finalizeSegment() {
if (segment)
tokens.push(segment);
segment = [];
}
// index on the path
let i = 0;
// char at index
let char;
// buffer of the value read
let buffer = '';
// custom regexp for a param
let customRe = '';
function consumeBuffer() {
if (!buffer)
return;
if (state === 0 /* Static */) {
segment.push({
type: 0 /* Static */,
value: buffer,
});
}
else if (state === 1 /* Param */ ||
state === 2 /* ParamRegExp */ ||
state === 3 /* ParamRegExpEnd */) {
if (segment.length > 1 && (char === '*' || char === '+'))
crash(`A repeatable param (${buffer}) must be alone in its segment. eg: '/:ids+.`);
segment.push({
type: 1 /* Param */,
value: buffer,
regexp: customRe,
repeatable: char === '*' || char === '+',
optional: char === '*' || char === '?',
});
}
else {
crash('Invalid state to consume buffer');
}
buffer = '';
}
function addCharToBuffer() {
buffer += char;
}
while (i < path.length) {
char = path[i++];
if (char === '\\' && state !== 2 /* ParamRegExp */) {
previousState = state;
state = 4 /* EscapeNext */;
continue;
}
switch (state) {
case 0 /* Static */:
if (char === '/') {
if (buffer) {
consumeBuffer();
}
finalizeSegment();
}
else if (char === ':') {
consumeBuffer();
state = 1 /* Param */;
}
else {
addCharToBuffer();
}
break;
case 4 /* EscapeNext */:
addCharToBuffer();
state = previousState;
break;
case 1 /* Param */:
if (char === '(') {
state = 2 /* ParamRegExp */;
customRe = '';
}
else if (VALID_PARAM_RE.test(char)) {
addCharToBuffer();
}
else {
consumeBuffer();
state = 0 /* Static */;
// go back one character if we were not modifying
if (char !== '*' && char !== '?' && char !== '+')
i--;
}
break;
case 2 /* ParamRegExp */:
// TODO: is it worth handling nested regexp? like :p(?:prefix_([^/]+)_suffix)
// it already works by escaping the closing )
// https://paths.esm.dev/?p=AAMeJbiAwQEcDKbAoAAkP60PG2R6QAvgNaA6AFACM2ABuQBB#
// is this really something people need since you can also write
// /prefix_:p()_suffix
if (char === ')') {
// handle the escaped )
if (customRe[customRe.length - 1] == '\\')
customRe = customRe.slice(0, -1) + char;
else
state = 3 /* ParamRegExpEnd */;
}
else {
customRe += char;
}
break;
case 3 /* ParamRegExpEnd */:
// same as finalizing a param
consumeBuffer();
state = 0 /* Static */;
// go back one character if we were not modifying
if (char !== '*' && char !== '?' && char !== '+')
i--;
break;
default:
crash('Unknown state');
break;
}
}
if (state === 2 /* ParamRegExp */)
crash(`Unfinished custom RegExp for param "${buffer}"`);
consumeBuffer();
finalizeSegment();
// tokenCache.set(path, tokens)
return tokens;
}
function createRouteRecordMatcher(record, parent, options) {
const parser = tokensToParser(tokenizePath(record.path), options);
// warn against params with the same name
if ((process.env.NODE_ENV !== 'production')) {
const existingKeys = new Set();
for (const key of parser.keys) {
if (existingKeys.has(key.name))
warn(`Found duplicated params with name "${key.name}" for path "${record.path}". Only the last one will be available on "$route.params".`);
existingKeys.add(key.name);
}
}
const matcher = assign(parser, {
record,
parent,
// these needs to be populated by the parent
children: [],
alias: [],
});
if (parent) {
// both are aliases or both are not aliases
// we don't want to mix them because the order is used when
// passing originalRecord in Matcher.addRoute
if (!matcher.record.aliasOf === !parent.record.aliasOf)
parent.children.push(matcher);
}
return matcher;
}
/**
* Creates a Router Matcher.
*
* @internal
* @param routes - array of initial routes
* @param globalOptions - global route options
*/
function createRouterMatcher(routes, globalOptions) {
// normalized ordered array of matchers
const matchers = [];
const matcherMap = new Map();
globalOptions = mergeOptions({ strict: false, end: true, sensitive: false }, globalOptions);
function getRecordMatcher(name) {
return matcherMap.get(name);
}
function addRoute(record, parent, originalRecord) {
// used later on to remove by name
let isRootAdd = !originalRecord;
let mainNormalizedRecord = normalizeRouteRecord(record);
// we might be the child of an alias
mainNormalizedRecord.aliasOf = originalRecord && originalRecord.record;
const options = mergeOptions(globalOptions, record);
// generate an array of records to correctly handle aliases
const normalizedRecords = [
mainNormalizedRecord,
];
if ('alias' in record) {
const aliases = typeof record.alias === 'string' ? [record.alias] : record.alias;
for (const alias of aliases) {
normalizedRecords.push(assign({}, mainNormalizedRecord, {
// this allows us to hold a copy of the `components` option
// so that async components cache is hold on the original record
components: originalRecord
? originalRecord.record.components
: mainNormalizedRecord.components,
path: alias,
// we might be the child of an alias
aliasOf: originalRecord
? originalRecord.record
: mainNormalizedRecord,
}));
}
}
let matcher;
let originalMatcher;
for (const normalizedRecord of normalizedRecords) {
let { path } = normalizedRecord;
// Build up the path for nested routes if the child isn't an absolute
// route. Only add the / delimiter if the child path isn't empty and if the
// parent path doesn't have a trailing slash
if (parent && path[0] !== '/') {
let parentPath = parent.record.path;
let connectingSlash = parentPath[parentPath.length - 1] === '/' ? '' : '/';
normalizedRecord.path =
parent.record.path + (path && connectingSlash + path);
}
if ((process.env.NODE_ENV !== 'production') && normalizedRecord.path === '*') {
throw new Error('Catch all routes ("*") must now be defined using a param with a custom regexp.\n' +
'See more at https://next.router.vuejs.org/guide/migration/#removed-star-or-catch-all-routes.');
}
// create the object before hand so it can be passed to children
matcher = createRouteRecordMatcher(normalizedRecord, parent, options);
if ((process.env.NODE_ENV !== 'production') && parent && path[0] === '/')
checkMissingParamsInAbsolutePath(matcher, parent);
// if we are an alias we must tell the original record that we exist
// so we can be removed
if (originalRecord) {
originalRecord.alias.push(matcher);
if ((process.env.NODE_ENV !== 'production')) {
checkSameParams(originalRecord, matcher);
}
}
else {
// otherwise, the first record is the original and others are aliases
originalMatcher = originalMatcher || matcher;
if (originalMatcher !== matcher)
originalMatcher.alias.push(matcher);
// remove the route if named and only for the top record (avoid in nested calls)
// this works because the original record is the first one
if (isRootAdd && record.name && !isAliasRecord(matcher))
removeRoute(record.name);
}
if ('children' in mainNormalizedRecord) {
let children = mainNormalizedRecord.children;
for (let i = 0; i < children.length; i++) {
addRoute(children[i], matcher, originalRecord && originalRecord.children[i]);
}
}
// if there was no original record, then the first one was not an alias and all
// other alias (if any) need to reference this record when adding children
originalRecord = originalRecord || matcher;
insertMatcher(matcher);
}
return originalMatcher
? () => {
// since other matchers are aliases, they should be removed by the original matcher
removeRoute(originalMatcher);
}
: noop;
}
function removeRoute(matcherRef) {
if (isRouteName(matcherRef)) {
const matcher = matcherMap.get(matcherRef);
if (matcher) {
matcherMap.delete(matcherRef);
matchers.splice(matchers.indexOf(matcher), 1);
matcher.children.forEach(removeRoute);
matcher.alias.forEach(removeRoute);
}
}
else {
let index = matchers.indexOf(matcherRef);
if (index > -1) {
matchers.splice(index, 1);
if (matcherRef.record.name)
matcherMap.delete(matcherRef.record.name);
matcherRef.children.forEach(removeRoute);
matcherRef.alias.forEach(removeRoute);
}
}
}
function getRoutes() {
return matchers;
}
function insertMatcher(matcher) {
let i = 0;
// console.log('i is', { i })
while (i < matchers.length &&
comparePathParserScore(matcher, matchers[i]) >= 0)
i++;
// console.log('END i is', { i })
// while (i < matchers.length && matcher.score <= matchers[i].score) i++
matchers.splice(i, 0, matcher);
// only add the original record to the name map
if (matcher.record.name && !isAliasRecord(matcher))
matcherMap.set(matcher.record.name, matcher);
}
function resolve(location, currentLocation) {
let matcher;
let params = {};
let path;
let name;
if ('name' in location && location.name) {
matcher = matcherMap.get(location.name);
if (!matcher)
throw createRouterError(1 /* MATCHER_NOT_FOUND */, {
location,
});
name = matcher.record.name;
params = assign(
// paramsFromLocation is a new object
paramsFromLocation(currentLocation.params,
// only keep params that exist in the resolved location
// TODO: only keep optional params coming from a parent record
matcher.keys.filter(k => !k.optional).map(k => k.name)), location.params);
// throws if cannot be stringified
path = matcher.stringify(params);
}
else if ('path' in location) {
// no need to resolve the path with the matcher as it was provided
// this also allows the user to control the encoding
path = location.path;
if ((process.env.NODE_ENV !== 'production') && !path.startsWith('/')) {
warn(`The Matcher cannot resolve relative paths but received "${path}". Unless you directly called \`matcher.resolve("${path}")\`, this is probably a bug in vue-router. Please open an issue at https://new-issue.vuejs.org/?repo=vuejs/vue-router-next.`);
}
matcher = matchers.find(m => m.re.test(path));
// matcher should have a value after the loop
if (matcher) {
// TODO: dev warning of unused params if provided
// we know the matcher works because we tested the regexp
params = matcher.parse(path);
name = matcher.record.name;
}
// location is a relative path
}
else {
// match by name or path of current route
matcher = currentLocation.name
? matcherMap.get(currentLocation.name)
: matchers.find(m => m.re.test(currentLocation.path));
if (!matcher)
throw createRouterError(1 /* MATCHER_NOT_FOUND */, {
location,
currentLocation,
});
name = matcher.record.name;
// since we are navigating to the same location, we don't need to pick the
// params like when `name` is provided
params = assign({}, currentLocation.params, location.params);
path = matcher.stringify(params);
}
const matched = [];
let parentMatcher = matcher;
while (parentMatcher) {
// reversed order so parents are at the beginning
matched.unshift(parentMatcher.record);
parentMatcher = parentMatcher.parent;
}
return {
name,
path,
params,
matched,
meta: mergeMetaFields(matched),
};
}
// add initial routes
routes.forEach(route => addRoute(route));
return { addRoute, resolve, removeRoute, getRoutes, getRecordMatcher };
}
function paramsFromLocation(params, keys) {
let newParams = {};
for (let key of keys) {
if (key in params)
newParams[key] = params[key];
}
return newParams;
}
/**
* Normalizes a RouteRecordRaw. Creates a copy
*
* @param record
* @returns the normalized version
*/
function normalizeRouteRecord(record) {
return {
path: record.path,
redirect: record.redirect,
name: record.name,
meta: record.meta || {},
aliasOf: undefined,
beforeEnter: record.beforeEnter,
props: normalizeRecordProps(record),
children: record.children || [],
instances: {},
leaveGuards: [],
updateGuards: [],
enterCallbacks: {},
components: 'components' in record
? record.components || {}
: { default: record.component },
};
}
/**
* Normalize the optional `props` in a record to always be an object similar to
* components. Also accept a boolean for components.
* @param record
*/
function normalizeRecordProps(record) {
const propsObject = {};
// props does not exist on redirect records but we can set false directly
const props = record.props || false;
if ('component' in record) {
propsObject.default = props;
}
else {
// NOTE: we could also allow a function to be applied to every component.
// Would need user feedback for use cases
for (let name in record.components)
propsObject[name] = typeof props === 'boolean' ? props : props[name];
}
return propsObject;
}
/**
* Checks if a record or any of its parent is an alias
* @param record
*/
function isAliasRecord(record) {
while (record) {
if (record.record.aliasOf)
return true;
record = record.parent;
}
return false;
}
/**
* Merge meta fields of an array of records
*
* @param matched - array of matched records
*/
function mergeMetaFields(matched) {
return matched.reduce((meta, record) => assign(meta, record.meta), {});
}
function mergeOptions(defaults, partialOptions) {
let options = {};
for (let key in defaults) {
options[key] =
key in partialOptions ? partialOptions[key] : defaults[key];
}
return options;
}
function isSameParam(a, b) {
return (a.name === b.name &&
a.optional === b.optional &&
a.repeatable === b.repeatable);
}
function checkSameParams(a, b) {
for (let key of a.keys) {
if (!b.keys.find(isSameParam.bind(null, key)))
return warn(`Alias "${b.record.path}" and the original record: "${a.record.path}" should have the exact same param named "${key.name}"`);
}
for (let key of b.keys) {
if (!a.keys.find(isSameParam.bind(null, key)))
return warn(`Alias "${b.record.path}" and the original record: "${a.record.path}" should have the exact same param named "${key.name}"`);
}
}
function checkMissingParamsInAbsolutePath(record, parent) {
for (let key of parent.keys) {
if (!record.keys.find(isSameParam.bind(null, key)))
return warn(`Absolute path "${record.record.path}" should have the exact same param named "${key.name}" as its parent "${parent.record.path}".`);
}
}
/**
* Encoding Rules ␣ = Space Path: ␣ " < > # ? { } Query: ␣ " < > # & = Hash: ␣ "
* < > `
*
* On top of that, the RFC3986 (https://tools.ietf.org/html/rfc3986#section-2.2)
* defines some extra characters to be encoded. Most browsers do not encode them
* in encodeURI https://github.com/whatwg/url/issues/369, so it may be safer to
* also encode `!'()*`. Leaving unencoded only ASCII alphanumeric(`a-zA-Z0-9`)
* plus `-._~`. This extra safety should be applied to query by patching the
* string returned by encodeURIComponent encodeURI also encodes `[\]^`. `\`
* should be encoded to avoid ambiguity. Browsers (IE, FF, C) transform a `\`
* into a `/` if directly typed in. The _backtick_ (`````) should also be
* encoded everywhere because some browsers like FF encode it when directly
* written while others don't. Safari and IE don't encode ``"<>{}``` in hash.
*/
// const EXTRA_RESERVED_RE = /[!'()*]/g
// const encodeReservedReplacer = (c: string) => '%' + c.charCodeAt(0).toString(16)
const HASH_RE = /#/g; // %23
const AMPERSAND_RE = /&/g; // %26
const SLASH_RE = /\//g; // %2F
const EQUAL_RE = /=/g; // %3D
const IM_RE = /\?/g; // %3F
const PLUS_RE = /\+/g; // %2B
/**
* NOTE: It's not clear to me if we should encode the + symbol in queries, it
* seems to be less flexible than not doing so and I can't find out the legacy
* systems requiring this for regular requests like text/html. In the standard,
* the encoding of the plus character is only mentioned for
* application/x-www-form-urlencoded
* (https://url.spec.whatwg.org/#urlencoded-parsing) and most browsers seems lo
* leave the plus character as is in queries. To be more flexible, we allow the
* plus character on the query but it can also be manually encoded by the user.
*
* Resources:
* - https://url.spec.whatwg.org/#urlencoded-parsing
* - https://stackoverflow.com/questions/1634271/url-encoding-the-space-character-or-20
*/
const ENC_BRACKET_OPEN_RE = /%5B/g; // [
const ENC_BRACKET_CLOSE_RE = /%5D/g; // ]
const ENC_CARET_RE = /%5E/g; // ^
const ENC_BACKTICK_RE = /%60/g; // `
const ENC_CURLY_OPEN_RE = /%7B/g; // {
const ENC_PIPE_RE = /%7C/g; // |
const ENC_CURLY_CLOSE_RE = /%7D/g; // }
const ENC_SPACE_RE = /%20/g; // }
/**
* Encode characters that need to be encoded on the path, search and hash
* sections of the URL.
*
* @internal
* @param text - string to encode
* @returns encoded string
*/
function commonEncode(text) {
return encodeURI('' + text)
.replace(ENC_PIPE_RE, '|')
.replace(ENC_BRACKET_OPEN_RE, '[')
.replace(ENC_BRACKET_CLOSE_RE, ']');
}
/**
* Encode characters that need to be encoded on the hash section of the URL.
*
* @param text - string to encode
* @returns encoded string
*/
function encodeHash(text) {
return commonEncode(text)
.replace(ENC_CURLY_OPEN_RE, '{')
.replace(ENC_CURLY_CLOSE_RE, '}')
.replace(ENC_CARET_RE, '^');
}
/**
* Encode characters that need to be encoded query values on the query
* section of the URL.
*
* @param text - string to encode
* @returns encoded string
*/
function encodeQueryValue(text) {
return (commonEncode(text)
// Encode the space as +, encode the + to differentiate it from the space
.replace(PLUS_RE, '%2B')
.replace(ENC_SPACE_RE, '+')
.replace(HASH_RE, '%23')
.replace(AMPERSAND_RE, '%26')
.replace(ENC_BACKTICK_RE, '`')
.replace(ENC_CURLY_OPEN_RE, '{')
.replace(ENC_CURLY_CLOSE_RE, '}')
.replace(ENC_CARET_RE, '^'));
}
/**
* Like `encodeQueryValue` but also encodes the `=` character.
*
* @param text - string to encode
*/
function encodeQueryKey(text) {
return encodeQueryValue(text).replace(EQUAL_RE, '%3D');
}
/**
* Encode characters that need to be encoded on the path section of the URL.
*
* @param text - string to encode
* @returns encoded string
*/
function encodePath(text) {
return commonEncode(text).replace(HASH_RE, '%23').replace(IM_RE, '%3F');
}
/**
* Encode characters that need to be encoded on the path section of the URL as a
* param. This function encodes everything {@link encodePath} does plus the
* slash (`/`) character.
*
* @param text - string to encode
* @returns encoded string
*/
function encodeParam(text) {
return encodePath(text).replace(SLASH_RE, '%2F');
}
/**
* Decode text using `decodeURIComponent`. Returns the original text if it
* fails.
*
* @param text - string to decode
* @returns decoded string
*/
function decode(text) {
try {
return decodeURIComponent('' + text);
}
catch (err) {
(process.env.NODE_ENV !== 'production') && warn(`Error decoding "${text}". Using original value`);
}
return '' + text;
}
/**
* Transforms a queryString into a {@link LocationQuery} object. Accept both, a
* version with the leading `?` and without Should work as URLSearchParams
* @internal
*
* @param search - search string to parse
* @returns a query object
*/
function parseQuery(search) {
const query = {};
// avoid creating an object with an empty key and empty value
// because of split('&')
if (search === '' || search === '?')
return query;
const hasLeadingIM = search[0] === '?';
const searchParams = (hasLeadingIM ? search.slice(1) : search).split('&');
for (let i = 0; i < searchParams.length; ++i) {
// pre decode the + into space
const searchParam = searchParams[i].replace(PLUS_RE, ' ');
// allow the = character
let eqPos = searchParam.indexOf('=');
let key = decode(eqPos < 0 ? searchParam : searchParam.slice(0, eqPos));
let value = eqPos < 0 ? null : decode(searchParam.slice(eqPos + 1));
if (key in query) {
// an extra variable for ts types
let currentValue = query[key];
if (!Array.isArray(currentValue)) {
currentValue = query[key] = [currentValue];
}
currentValue.push(value);
}
else {
query[key] = value;
}
}
return query;
}
/**
* Stringifies a {@link LocationQueryRaw} object. Like `URLSearchParams`, it
* doesn't prepend a `?`
*
* @internal
*
* @param query - query object to stringify
* @returns string version of the query without the leading `?`
*/
function stringifyQuery(query) {
let search = '';
for (let key in query) {
if (search.length)
search += '&';
const value = query[key];
key = encodeQueryKey(key);
if (value == null) {
// only null adds the value
if (value !== undefined)
search += key;
continue;
}
// keep null values
let values = Array.isArray(value)
? value.map(v => v && encodeQueryValue(v))
: [value && encodeQueryValue(value)];
for (let i = 0; i < values.length; i++) {
// only append & with i > 0
search += (i ? '&' : '') + key;
if (values[i] != null)
search += ('=' + values[i]);
}
}
return search;
}
/**
* Transforms a {@link LocationQueryRaw} into a {@link LocationQuery} by casting
* numbers into strings, removing keys with an undefined value and replacing
* undefined with null in arrays
*
* @param query - query object to normalize
* @returns a normalized query object
*/
function normalizeQuery(query) {
const normalizedQuery = {};
for (let key in query) {
let value = query[key];
if (value !== undefined) {
normalizedQuery[key] = Array.isArray(value)
? value.map(v => (v == null ? null : '' + v))
: value == null
? value
: '' + value;
}
}
return normalizedQuery;
}
/**
* Create a list of callbacks that can be reset. Used to create before and after navigation guards list
*/
function useCallbacks() {
let handlers = [];
function add(handler) {
handlers.push(handler);
return () => {
const i = handlers.indexOf(handler);
if (i > -1)
handlers.splice(i, 1);
};
}
function reset() {
handlers = [];
}
return {
add,
list: () => handlers,
reset,
};
}
function registerGuard(list, guard) {
const removeFromList = () => {
const index = list.indexOf(guard);
if (index > -1)
list.splice(index, 1);
};
onUnmounted(removeFromList);
onDeactivated(removeFromList);
onActivated(() => {
const index = list.indexOf(guard);
if (index < 0)
list.push(guard);
});
list.push(guard);
}
/**
* Add a navigation guard that triggers whenever the component for the current
* location is about to be left. Similar to {@link beforeRouteLeave} but can be
* used in any component. The guard is removed when the component is unmounted.
*
* @param leaveGuard - {@link NavigationGuard}
*/
function onBeforeRouteLeave(leaveGuard) {
if ((process.env.NODE_ENV !== 'production') && !getCurrentInstance()) {
warn('onBeforeRouteLeave must be called at the top of a setup function');
return;
}
const activeRecord = inject(matchedRouteKey, {}).value;
if (!activeRecord) {
(process.env.NODE_ENV !== 'production') &&
warn('onBeforeRouteLeave must be called at the top of a setup function');
return;
}
registerGuard(activeRecord.leaveGuards, leaveGuard);
}
/**
* Add a navigation guard that triggers whenever the current location is about
* to be updated. Similar to {@link beforeRouteUpdate} but can be used in any
* component. The guard is removed when the component is unmounted.
*
* @param updateGuard - {@link NavigationGuard}
*/
function onBeforeRouteUpdate(updateGuard) {
if ((process.env.NODE_ENV !== 'production') && !getCurrentInstance()) {
warn('onBeforeRouteUpdate must be called at the top of a setup function');
return;
}
const activeRecord = inject(matchedRouteKey, {}).value;
if (!activeRecord) {
(process.env.NODE_ENV !== 'production') &&
warn('onBeforeRouteUpdate must be called at the top of a setup function');
return;
}
registerGuard(activeRecord.updateGuards, updateGuard);
}
function guardToPromiseFn(guard, to, from, record, name) {
// keep a reference to the enterCallbackArray to prevent pushing callbacks if a new navigation took place
const enterCallbackArray = record &&
// name is defined if record is because of the function overload
(record.enterCallbacks[name] = record.enterCallbacks[name] || []);
return () => new Promise((resolve, reject) => {
const next = (valid) => {
if (valid === false)
reject(createRouterError(4 /* NAVIGATION_ABORTED */, {
from,
to,
}));
else if (valid instanceof Error) {
reject(valid);
}
else if (isRouteLocation(valid)) {
reject(createRouterError(2 /* NAVIGATION_GUARD_REDIRECT */, {
from: to,
to: valid,
}));
}
else {
if (enterCallbackArray &&
// since enterCallbackArray is truthy, both record and name also are
record.enterCallbacks[name] === enterCallbackArray &&
typeof valid === 'function')
enterCallbackArray.push(valid);
resolve();
}
};
// wrapping with Promise.resolve allows it to work with both async and sync guards
const guardReturn = guard.call(record && record.instances[name], to, from, (process.env.NODE_ENV !== 'production') ? canOnlyBeCalledOnce(next, to, from) : next);
let guardCall = Promise.resolve(guardReturn);
if (guard.length < 3)
guardCall = guardCall.then(next);
if ((process.env.NODE_ENV !== 'production') && guard.length > 2) {
const message = `The "next" callback was never called inside of ${guard.name ? '"' + guard.name + '"' : ''}:\n${guard.toString()}\n. If you are returning a value instead of calling "next", make sure to remove the "next" parameter from your function.`;
if (typeof guardReturn === 'object' && 'then' in guardReturn) {
guardCall = guardCall.then(resolvedValue => {
// @ts-ignore: _called is added at canOnlyBeCalledOnce
if (!next._called) {
warn(message);
return Promise.reject(new Error('Invalid navigation guard'));
}
return resolvedValue;
});
// TODO: test me!
}
else if (guardReturn !== undefined) {
// @ts-ignore: _called is added at canOnlyBeCalledOnce
if (!next._called) {
warn(message);
reject(new Error('Invalid navigation guard'));
return;
}
}
}
guardCall.catch(err => reject(err));
});
}
function canOnlyBeCalledOnce(next, to, from) {
let called = 0;
return function () {
if (called++ === 1)
warn(`The "next" callback was called more than once in one navigation guard when going from "${from.fullPath}" to "${to.fullPath}". It should be called exactly one time in each navigation guard. This will fail in production.`);
// @ts-ignore: we put it in the original one because it's easier to check
next._called = true;
if (called === 1)
next.apply(null, arguments);
};
}
function extractComponentsGuards(matched, guardType, to, from) {
const guards = [];
for (const record of matched) {
for (const name in record.components) {
let rawComponent = record.components[name];
if ((process.env.NODE_ENV !== 'production')) {
if (!rawComponent ||
(typeof rawComponent !== 'object' &&
typeof rawComponent !== 'function')) {
warn(`Component "${name}" in record with path "${record.path}" is not` +
` a valid component. Received "${String(rawComponent)}".`);
// throw to ensure we stop here but warn to ensure the message isn't
// missed by the user
throw new Error('Invalid route component');
}
else if ('then' in rawComponent) {
// warn if user wrote import('/component.vue') instead of () =>
// import('./component.vue')
warn(`Component "${name}" in record with path "${record.path}" is a ` +
`Promise instead of a function that returns a Promise. Did you ` +
`write "import('./MyPage.vue')" instead of ` +
`"() => import('./MyPage.vue')" ? This will break in ` +
`production if not fixed.`);
let promise = rawComponent;
rawComponent = () => promise;
}
}
// skip update and leave guards if the route component is not mounted
if (guardType !== 'beforeRouteEnter' && !record.instances[name])
continue;
if (isRouteComponent(rawComponent)) {
// __vccOpts is added by vue-class-component and contain the regular options
let options = rawComponent.__vccOpts || rawComponent;
const guard = options[guardType];
guard && guards.push(guardToPromiseFn(guard, to, from, record, name));
}
else {
// start requesting the chunk already
let componentPromise = rawComponent();
if ((process.env.NODE_ENV !== 'production') && !('catch' in componentPromise)) {
warn(`Component "${name}" in record with path "${record.path}" is a function that does not return a Promise. If you were passing a functional component, make sure to add a "displayName" to the component. This will break in production if not fixed.`);
componentPromise = Promise.resolve(componentPromise);
}
else {
// display the error if any
componentPromise = componentPromise.catch((process.env.NODE_ENV !== 'production') ? err => err && warn(err) : console.error);
}
guards.push(() => componentPromise.then(resolved => {
if (!resolved)
return Promise.reject(new Error(`Couldn't resolve component "${name}" at "${record.path}"`));
const resolvedComponent = isESModule(resolved)
? resolved.default
: resolved;
// replace the function with the resolved component
record.components[name] = resolvedComponent;
// @ts-ignore: the options types are not propagated to Component
const guard = resolvedComponent[guardType];
return guard && guardToPromiseFn(guard, to, from, record, name)();
}));
}
}
}
return guards;
}
/**
* Allows differentiating lazy components from functional components and vue-class-component
* @param component
*/
function isRouteComponent(component) {
return (typeof component === 'object' ||
'displayName' in component ||
'props' in component ||
'__vccOpts' in component);
}
// TODO: we could allow currentRoute as a prop to expose `isActive` and
// `isExactActive` behavior should go through an RFC
function useLink(props) {
const router = inject(routerKey);
const currentRoute = inject(routeLocationKey);
const route = computed(() => router.resolve(unref(props.to)));
const activeRecordIndex = computed(() => {
let { matched } = route.value;
let { length } = matched;
const routeMatched = matched[length - 1];
let currentMatched = currentRoute.matched;
if (!routeMatched || !currentMatched.length)
return -1;
let index = currentMatched.findIndex(isSameRouteRecord.bind(null, routeMatched));
if (index > -1)
return index;
// possible parent record
let parentRecordPath = getOriginalPath(matched[length - 2]);
return (
// we are dealing with nested routes
length > 1 &&
// if the parent and matched route have the same path, this link is
// referring to the empty child. Or we currently are on a different
// child of the same parent
getOriginalPath(routeMatched) === parentRecordPath &&
// avoid comparing the child with its parent
currentMatched[currentMatched.length - 1].path !== parentRecordPath
? currentMatched.findIndex(isSameRouteRecord.bind(null, matched[length - 2]))
: index);
});
const isActive = computed(() => activeRecordIndex.value > -1 &&
includesParams(currentRoute.params, route.value.params));
const isExactActive = computed(() => activeRecordIndex.value > -1 &&
activeRecordIndex.value === currentRoute.matched.length - 1 &&
isSameRouteLocationParams(currentRoute.params, route.value.params));
function navigate(e = {}) {
if (guardEvent(e))
return router[unref(props.replace) ? 'replace' : 'push'](unref(props.to));
return Promise.resolve();
}
return {
route,
href: computed(() => route.value.href),
isActive,
isExactActive,
navigate,
};
}
const RouterLinkImpl = /*#__PURE__*/ defineComponent({
name: 'RouterLink',
props: {
to: {
type: [String, Object],
required: true,
},
activeClass: String,
// inactiveClass: String,
exactActiveClass: String,
custom: Boolean,
ariaCurrentValue: {
type: String,
default: 'page',
},
},
setup(props, { slots, attrs }) {
const link = reactive(useLink(props));
const { options } = inject(routerKey);
const elClass = computed(() => ({
[getLinkClass(props.activeClass, options.linkActiveClass, 'router-link-active')]: link.isActive,
// [getLinkClass(
// props.inactiveClass,
// options.linkInactiveClass,
// 'router-link-inactive'
// )]: !link.isExactActive,
[getLinkClass(props.exactActiveClass, options.linkExactActiveClass, 'router-link-exact-active')]: link.isExactActive,
}));
return () => {
const children = slots.default && slots.default(link);
return props.custom
? children
: h('a', assign({
'aria-current': link.isExactActive
? props.ariaCurrentValue
: null,
onClick: link.navigate,
href: link.href,
}, attrs, {
class: elClass.value,
}), children);
};
},
});
// export the public type for h/tsx inference
// also to avoid inline import() in generated d.ts files
/**
* Component to render a link that triggers a navigation on click.
*/
const RouterLink = RouterLinkImpl;
function guardEvent(e) {
// don't redirect with control keys
if (e.metaKey || e.altKey || e.ctrlKey || e.shiftKey)
return;
// don't redirect when preventDefault called
if (e.defaultPrevented)
return;
// don't redirect on right click
if (e.button !== undefined && e.button !== 0)
return;
// don't redirect if `target="_blank"`
// @ts-ignore getAttribute does exist
if (e.currentTarget && e.currentTarget.getAttribute) {
// @ts-ignore getAttribute exists
const target = e.currentTarget.getAttribute('target');
if (/\b_blank\b/i.test(target))
return;
}
// this may be a Weex event which doesn't have this method
if (e.preventDefault)
e.preventDefault();
return true;
}
function includesParams(outer, inner) {
for (let key in inner) {
let innerValue = inner[key];
let outerValue = outer[key];
if (typeof innerValue === 'string') {
if (innerValue !== outerValue)
return false;
}
else {
if (!Array.isArray(outerValue) ||
outerValue.length !== innerValue.length ||
innerValue.some((value, i) => value !== outerValue[i]))
return false;
}
}
return true;
}
/**
* Get the original path value of a record by following its aliasOf
* @param record
*/
function getOriginalPath(record) {
return record ? (record.aliasOf ? record.aliasOf.path : record.path) : '';
}
/**
* Utility class to get the active class based on defaults.
* @param propClass
* @param globalClass
* @param defaultClass
*/
const getLinkClass = (propClass, globalClass, defaultClass) => propClass != null
? propClass
: globalClass != null
? globalClass
: defaultClass;
const RouterViewImpl = /*#__PURE__*/ defineComponent({
name: 'RouterView',
props: {
name: {
type: String,
default: 'default',
},
route: Object,
},
setup(props, { attrs, slots }) {
(process.env.NODE_ENV !== 'production') && warnDeprecatedUsage();
const injectedRoute = inject(routeLocationKey);
const depth = inject(viewDepthKey, 0);
const matchedRouteRef = computed(() => (props.route || injectedRoute).matched[depth]);
provide(viewDepthKey, depth + 1);
provide(matchedRouteKey, matchedRouteRef);
const viewRef = ref();
// watch at the same time the component instance, the route record we are
// rendering, and the name
watch(() => [viewRef.value, matchedRouteRef.value, props.name], ([instance, to, name], [oldInstance, from, oldName]) => {
// copy reused instances
if (to) {
// this will update the instance for new instances as well as reused
// instances when navigating to a new route
to.instances[name] = instance;
// the component instance is reused for a different route or name so
// we copy any saved update or leave guards
if (from && instance === oldInstance) {
to.leaveGuards = from.leaveGuards;
to.updateGuards = from.updateGuards;
}
}
// trigger beforeRouteEnter next callbacks
if (instance &&
to &&
// if there is no instance but to and from are the same this might be
// the first visit
(!from || !isSameRouteRecord(to, from) || !oldInstance)) {
(to.enterCallbacks[name] || []).forEach(callback => callback(instance));
}
}, { flush: 'post' });
return () => {
const route = props.route || injectedRoute;
const matchedRoute = matchedRouteRef.value;
const ViewComponent = matchedRoute && matchedRoute.components[props.name];
// we need the value at the time we render because when we unmount, we
// navigated to a different location so the value is different
const currentName = props.name;
if (!ViewComponent) {
return slots.default
? slots.default({ Component: ViewComponent, route })
: null;
}
// props from route configuration
const routePropsOption = matchedRoute.props[props.name];
const routeProps = routePropsOption
? routePropsOption === true
? route.params
: typeof routePropsOption === 'function'
? routePropsOption(route)
: routePropsOption
: null;
const onVnodeUnmounted = vnode => {
// remove the instance reference to prevent leak
if (vnode.component.isUnmounted) {
matchedRoute.instances[currentName] = null;
}
};
const component = h(ViewComponent, assign({}, routeProps, attrs, {
onVnodeUnmounted,
ref: viewRef,
}));
return (
// pass the vnode to the slot as a prop.
// h and <component :is="..."> both accept vnodes
slots.default
? slots.default({ Component: component, route })
: component);
};
},
});
// export the public type for h/tsx inference
// also to avoid inline import() in generated d.ts files
/**
* Component to display the current route the user is at.
*/
const RouterView = RouterViewImpl;
// warn against deprecated usage with <transition> & <keep-alive>
// due to functional component being no longer eager in Vue 3
function warnDeprecatedUsage() {
const instance = getCurrentInstance();
const parentName = instance.parent && instance.parent.type.name;
if (parentName &&
(parentName === 'KeepAlive' || parentName.includes('Transition'))) {
const comp = parentName === 'KeepAlive' ? 'keep-alive' : 'transition';
warn(`<router-view> can no longer be used directly inside <transition> or <keep-alive>.\n` +
`Use slot props instead:\n\n` +
`<router-view v-slot="{ Component }">\n` +
` <${comp}>\n` +
` <component :is="Component" />\n` +
` </${comp}>\n` +
`</router-view>`);
}
}
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
function createCommonjsModule(fn, basedir, module) {
return module = {
path: basedir,
exports: {},
require: function (path, base) {
return commonjsRequire(path, (base === undefined || base === null) ? module.path : base);
}
}, fn(module, module.exports), module.exports;
}
function commonjsRequire () {
throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');
}
var env = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", { value: true });
exports.hook = exports.target = exports.isBrowser = void 0;
exports.isBrowser = typeof navigator !== 'undefined';
exports.target = exports.isBrowser
? window
: typeof commonjsGlobal !== 'undefined'
? commonjsGlobal
: {};
exports.hook = exports.target.__VUE_DEVTOOLS_GLOBAL_HOOK__;
});
var _const = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", { value: true });
exports.ApiHookEvents = void 0;
var ApiHookEvents;
(function (ApiHookEvents) {
ApiHookEvents["SETUP_DEVTOOLS_PLUGIN"] = "devtools-plugin:setup";
})(ApiHookEvents = exports.ApiHookEvents || (exports.ApiHookEvents = {}));
});
var api = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", { value: true });
});
var app = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", { value: true });
});
var component = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", { value: true });
});
var context = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", { value: true });
});
var hooks = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", { value: true });
exports.Hooks = void 0;
var Hooks;
(function (Hooks) {
Hooks["TRANSFORM_CALL"] = "transformCall";
Hooks["GET_APP_RECORD_NAME"] = "getAppRecordName";
Hooks["GET_APP_ROOT_INSTANCE"] = "getAppRootInstance";
Hooks["REGISTER_APPLICATION"] = "registerApplication";
Hooks["WALK_COMPONENT_TREE"] = "walkComponentTree";
Hooks["WALK_COMPONENT_PARENTS"] = "walkComponentParents";
Hooks["INSPECT_COMPONENT"] = "inspectComponent";
Hooks["GET_COMPONENT_BOUNDS"] = "getComponentBounds";
Hooks["GET_COMPONENT_NAME"] = "getComponentName";
Hooks["GET_ELEMENT_COMPONENT"] = "getElementComponent";
Hooks["GET_INSPECTOR_TREE"] = "getInspectorTree";
Hooks["GET_INSPECTOR_STATE"] = "getInspectorState";
})(Hooks = exports.Hooks || (exports.Hooks = {}));
});
var api$1 = createCommonjsModule(function (module, exports) {
var __createBinding = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (commonjsGlobal && commonjsGlobal.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(api, exports);
__exportStar(app, exports);
__exportStar(component, exports);
__exportStar(context, exports);
__exportStar(hooks, exports);
});
var lib = createCommonjsModule(function (module, exports) {
var __createBinding = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (commonjsGlobal && commonjsGlobal.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.setupDevtoolsPlugin = void 0;
__exportStar(api$1, exports);
function setupDevtoolsPlugin(pluginDescriptor, setupFn) {
if (env.hook) {
env.hook.emit(_const.ApiHookEvents.SETUP_DEVTOOLS_PLUGIN, pluginDescriptor, setupFn);
}
else {
const list = env.target.__VUE_DEVTOOLS_PLUGINS__ = env.target.__VUE_DEVTOOLS_PLUGINS__ || [];
list.push({
pluginDescriptor,
setupFn
});
}
}
exports.setupDevtoolsPlugin = setupDevtoolsPlugin;
});
function formatRouteLocation(routeLocation, tooltip) {
const copy = {
...routeLocation,
// remove variables that can contain vue instances
matched: routeLocation.matched.map(({ instances, children, aliasOf, ...rest }) => rest),
};
return {
_custom: {
type: null,
readOnly: true,
display: routeLocation.fullPath,
tooltip,
value: copy,
},
};
}
function formatDisplay(display) {
return {
_custom: {
display,
},
};
}
// to support multiple router instances
let routerId = 0;
function addDevtools(app, router, matcher) {
// Take over router.beforeEach and afterEach
// increment to support multiple router instances
const id = routerId++;
lib.setupDevtoolsPlugin({
id: 'Router' + id ? ' ' + id : '',
label: 'Router devtools',
app,
}, api => {
api.on.inspectComponent((payload, ctx) => {
if (payload.instanceData) {
payload.instanceData.state.push({
type: 'Routing',
key: '$route',
editable: false,
value: formatRouteLocation(router.currentRoute.value, 'Current Route'),
});
}
});
watch(router.currentRoute, () => {
// @ts-ignore
api.notifyComponentUpdate();
});
const navigationsLayerId = 'router:navigations:' + id;
api.addTimelineLayer({
id: navigationsLayerId,
label: `Router${id ? ' ' + id : ''} Navigations`,
color: 0x40a8c4,
});
// const errorsLayerId = 'router:errors'
// api.addTimelineLayer({
// id: errorsLayerId,
// label: 'Router Errors',
// color: 0xea5455,
// })
router.onError(error => {
api.addTimelineEvent({
layerId: navigationsLayerId,
event: {
// @ts-ignore
logType: 'error',
time: Date.now(),
data: { error },
},
});
});
router.beforeEach((to, from) => {
const data = {
guard: formatDisplay('beforeEach'),
from: formatRouteLocation(from, 'Current Location during this navigation'),
to: formatRouteLocation(to, 'Target location'),
};
api.addTimelineEvent({
layerId: navigationsLayerId,
event: {
time: Date.now(),
meta: {},
data,
},
});
});
router.afterEach((to, from, failure) => {
const data = {
guard: formatDisplay('afterEach'),
};
if (failure) {
data.failure = {
_custom: {
type: Error,
readOnly: true,
display: failure ? failure.message : '',
tooltip: 'Navigation Failure',
value: failure,
},
};
data.status = formatDisplay('❌');
}
else {
data.status = formatDisplay('✅');
}
// we set here to have the right order
data.from = formatRouteLocation(from, 'Current Location during this navigation');
data.to = formatRouteLocation(to, 'Target location');
api.addTimelineEvent({
layerId: navigationsLayerId,
event: {
time: Date.now(),
data,
// @ts-ignore
logType: failure ? 'warning' : 'default',
meta: {},
},
});
});
const routerInspectorId = 'router-inspector:' + id;
api.addInspector({
id: routerInspectorId,
label: 'Routes' + (id ? ' ' + id : ''),
icon: 'book',
treeFilterPlaceholder: 'Search routes',
});
api.on.getInspectorTree(payload => {
if (payload.app === app && payload.inspectorId === routerInspectorId) {
let routes = matcher.getRoutes();
if (payload.filter) {
routes = routes.filter(route => !route.parent &&
// save isActive state
isRouteMatching(route, payload.filter.toLowerCase()));
}
// reset match state if no filter is provided
if (!payload.filter) {
routes.forEach(route => {
route.__vd_match = false;
});
}
payload.rootNodes = routes.map(formatRouteRecordForInspector);
}
});
api.on.getInspectorState(payload => {
if (payload.app === app && payload.inspectorId === routerInspectorId) {
const routes = matcher.getRoutes();
const route = routes.find(route => route.record.path === payload.nodeId);
if (route) {
payload.state = {
options: formatRouteRecordMatcherForStateInspector(route),
};
}
}
});
});
}
function modifierForKey(key) {
if (key.optional) {
return key.repeatable ? '*' : '?';
}
else {
return key.repeatable ? '+' : '';
}
}
function formatRouteRecordMatcherForStateInspector(route) {
const { record } = route;
const fields = [
{ editable: false, key: 'path', value: record.path },
];
if (record.name != null)
fields.push({
editable: false,
key: 'name',
value: record.name,
});
fields.push({ editable: false, key: 'regexp', value: route.re });
if (route.keys.length)
fields.push({
editable: false,
key: 'keys',
value: {
_custom: {
type: null,
readOnly: true,
display: route.keys
.map(key => `${key.name}${modifierForKey(key)}`)
.join(' '),
tooltip: 'Param keys',
value: route.keys,
},
},
});
if (record.redirect != null)
fields.push({
editable: false,
key: 'redirect',
value: record.redirect,
});
if (route.alias.length)
fields.push({
editable: false,
key: 'aliases',
value: route.alias.map(alias => alias.record.path),
});
fields.push({
key: 'score',
editable: false,
value: {
_custom: {
type: null,
readOnly: true,
display: route.score.map(score => score.join(', ')).join(' | '),
tooltip: 'Score used to sort routes',
value: route.score,
},
},
});
return fields;
}
function formatRouteRecordForInspector(route) {
const tags = [];
const { record } = route;
if (record.name != null) {
tags.push({
label: String(record.name),
textColor: 0,
backgroundColor: 0x00bcd4,
});
}
if (record.aliasOf) {
tags.push({
label: 'alias',
textColor: 0,
backgroundColor: 0xff984f,
});
}
if (route.__vd_match) {
tags.push({
label: 'matches',
textColor: 0,
backgroundColor: 0xf4f4f4,
});
}
if (record.redirect) {
tags.push({
label: 'redirect: ' +
(typeof record.redirect === 'string' ? record.redirect : 'Object'),
textColor: 0xffffff,
backgroundColor: 0x666666,
});
}
return {
id: record.path,
label: record.path,
tags,
// @ts-ignore
children: route.children.map(formatRouteRecordForInspector),
};
}
const EXTRACT_REGEXP_RE = /^\/(.*)\/([a-z]*)$/;
function isRouteMatching(route, filter) {
const found = String(route.re).match(EXTRACT_REGEXP_RE);
route.__vd_match = false;
if (!found || found.length < 3)
return false;
// use a regexp without $ at the end to match nested routes better
const nonEndingRE = new RegExp(found[1].replace(/\$$/, ''), found[2]);
if (nonEndingRE.test(filter)) {
// mark children as matches
route.children.some(child => isRouteMatching(child, filter));
// exception case: `/`
if (route.record.path !== '/' || filter === '/') {
route.__vd_match = route.re.test(filter);
return true;
}
// hide the / route
return false;
}
const path = route.record.path.toLowerCase();
const decodedPath = decode(path);
// also allow partial matching on the path
if (!filter.startsWith('/') &&
(decodedPath.includes(filter) || path.includes(filter)))
return true;
if (decodedPath.startsWith(filter) || path.startsWith(filter))
return true;
if (route.record.name && String(route.record.name).includes(filter))
return true;
return route.children.some(child => isRouteMatching(child, filter));
}
/**
* Creates a Router instance that can be used by a Vue app.
*
* @param options - {@link RouterOptions}
*/
function createRouter(options) {
const matcher = createRouterMatcher(options.routes, options);
let parseQuery$1 = options.parseQuery || parseQuery;
let stringifyQuery$1 = options.stringifyQuery || stringifyQuery;
let { scrollBehavior } = options;
let routerHistory = options.history;
const beforeGuards = useCallbacks();
const beforeResolveGuards = useCallbacks();
const afterGuards = useCallbacks();
const currentRoute = shallowRef(START_LOCATION_NORMALIZED);
let pendingLocation = START_LOCATION_NORMALIZED;
// leave the scrollRestoration if no scrollBehavior is provided
if (isBrowser && scrollBehavior && 'scrollRestoration' in history) {
history.scrollRestoration = 'manual';
}
const normalizeParams = applyToParams.bind(null, paramValue => '' + paramValue);
const encodeParams = applyToParams.bind(null, encodeParam);
const decodeParams = applyToParams.bind(null, decode);
function addRoute(parentOrRoute, route) {
let parent;
let record;
if (isRouteName(parentOrRoute)) {
parent = matcher.getRecordMatcher(parentOrRoute);
record = route;
}
else {
record = parentOrRoute;
}
return matcher.addRoute(record, parent);
}
function removeRoute(name) {
let recordMatcher = matcher.getRecordMatcher(name);
if (recordMatcher) {
matcher.removeRoute(recordMatcher);
}
else if ((process.env.NODE_ENV !== 'production')) {
warn(`Cannot remove non-existent route "${String(name)}"`);
}
}
function getRoutes() {
return matcher.getRoutes().map(routeMatcher => routeMatcher.record);
}
function hasRoute(name) {
return !!matcher.getRecordMatcher(name);
}
function resolve(rawLocation, currentLocation) {
// const objectLocation = routerLocationAsObject(rawLocation)
// we create a copy to modify it later
currentLocation = assign({}, currentLocation || currentRoute.value);
if (typeof rawLocation === 'string') {
let locationNormalized = parseURL(parseQuery$1, rawLocation, currentLocation.path);
let matchedRoute = matcher.resolve({ path: locationNormalized.path }, currentLocation);
let href = routerHistory.createHref(locationNormalized.fullPath);
if ((process.env.NODE_ENV !== 'production')) {
if (href.startsWith('//'))
warn(`Location "${rawLocation}" resolved to "${href}". A resolved location cannot start with multiple slashes.`);
else if (!matchedRoute.matched.length) {
warn(`No match found for location with path "${rawLocation}"`);
}
}
// locationNormalized is always a new object
return assign(locationNormalized, matchedRoute, {
params: decodeParams(matchedRoute.params),
hash: decode(locationNormalized.hash),
redirectedFrom: undefined,
href,
});
}
let matcherLocation;
// path could be relative in object as well
if ('path' in rawLocation) {
if ((process.env.NODE_ENV !== 'production') &&
'params' in rawLocation &&
!('name' in rawLocation) &&
Object.keys(rawLocation.params).length) {
warn(`Path "${rawLocation.path}" was passed with params but they will be ignored. Use a named route alongside params instead.`);
}
matcherLocation = assign({}, rawLocation, {
path: parseURL(parseQuery$1, rawLocation.path, currentLocation.path).path,
});
}
else {
// pass encoded values to the matcher so it can produce encoded path and fullPath
matcherLocation = assign({}, rawLocation, {
params: encodeParams(rawLocation.params),
});
// current location params are decoded, we need to encode them in case the
// matcher merges the params
currentLocation.params = encodeParams(currentLocation.params);
}
let matchedRoute = matcher.resolve(matcherLocation, currentLocation);
const hash = rawLocation.hash || '';
if ((process.env.NODE_ENV !== 'production') && hash && !hash.startsWith('#')) {
warn(`A \`hash\` should always start with the character "#". Replace "${hash}" with "#${hash}".`);
}
// decoding them) the matcher might have merged current location params so
// we need to run the decoding again
matchedRoute.params = normalizeParams(decodeParams(matchedRoute.params));
const fullPath = stringifyURL(stringifyQuery$1, assign({}, rawLocation, {
hash: encodeHash(hash),
path: matchedRoute.path,
}));
let href = routerHistory.createHref(fullPath);
if ((process.env.NODE_ENV !== 'production')) {
if (href.startsWith('//')) {
warn(`Location "${rawLocation}" resolved to "${href}". A resolved location cannot start with multiple slashes.`);
}
else if (!matchedRoute.matched.length) {
warn(`No match found for location with path "${'path' in rawLocation ? rawLocation.path : rawLocation}"`);
}
}
return assign({
fullPath,
// keep the hash encoded so fullPath is effectively path + encodedQuery +
// hash
hash,
query:
// if the user is using a custom query lib like qs, we might have
// nested objects, so we keep the query as is, meaning it can contain
// numbers at `$route.query`, but at the point, the user will have to
// use their own type anyway.
// https://github.com/vuejs/vue-router-next/issues/328#issuecomment-649481567
stringifyQuery$1 === stringifyQuery
? normalizeQuery(rawLocation.query)
: rawLocation.query,
}, matchedRoute, {
redirectedFrom: undefined,
href,
});
}
function locationAsObject(to) {
return typeof to === 'string' ? { path: to } : assign({}, to);
}
function checkCanceledNavigation(to, from) {
if (pendingLocation !== to) {
return createRouterError(8 /* NAVIGATION_CANCELLED */, {
from,
to,
});
}
}
function push(to) {
return pushWithRedirect(to);
}
function replace(to) {
return push(assign(locationAsObject(to), { replace: true }));
}
function handleRedirectRecord(to) {
const lastMatched = to.matched[to.matched.length - 1];
if (lastMatched && lastMatched.redirect) {
const { redirect } = lastMatched;
// transform it into an object to pass the original RouteLocaleOptions
let newTargetLocation = locationAsObject(typeof redirect === 'function' ? redirect(to) : redirect);
if ((process.env.NODE_ENV !== 'production') &&
!('path' in newTargetLocation) &&
!('name' in newTargetLocation)) {
warn(`Invalid redirect found:\n${JSON.stringify(newTargetLocation, null, 2)}\n when navigating to "${to.fullPath}". A redirect must contain a name or path. This will break in production.`);
throw new Error('Invalid redirect');
}
return assign({
query: to.query,
hash: to.hash,
params: to.params,
}, newTargetLocation);
}
}
function pushWithRedirect(to, redirectedFrom) {
const targetLocation = (pendingLocation = resolve(to));
const from = currentRoute.value;
const data = to.state;
const force = to.force;
// to could be a string where `replace` is a function
const replace = to.replace === true;
const shouldRedirect = handleRedirectRecord(targetLocation);
if (shouldRedirect)
return pushWithRedirect(assign(shouldRedirect, { state: data, force, replace }),
// keep original redirectedFrom if it exists
redirectedFrom || targetLocation);
// if it was a redirect we already called `pushWithRedirect` above
const toLocation = targetLocation;
toLocation.redirectedFrom = redirectedFrom;
let failure;
if (!force && isSameRouteLocation(stringifyQuery$1, from, targetLocation)) {
failure = createRouterError(16 /* NAVIGATION_DUPLICATED */, { to: toLocation, from });
// trigger scroll to allow scrolling to the same anchor
handleScroll(from, from,
// this is a push, the only way for it to be triggered from a
// history.listen is with a redirect, which makes it become a push
true,
// This cannot be the first navigation because the initial location
// cannot be manually navigated to
false);
}
return (failure ? Promise.resolve(failure) : navigate(toLocation, from))
.catch((error) => isNavigationFailure(error)
? error
: // reject any unknown error
triggerError(error))
.then((failure) => {
if (failure) {
if (isNavigationFailure(failure, 2 /* NAVIGATION_GUARD_REDIRECT */)) {
if ((process.env.NODE_ENV !== 'production') &&
// we are redirecting to the same location we were already at
isSameRouteLocation(stringifyQuery$1, resolve(failure.to), toLocation) &&
// and we have done it a couple of times
redirectedFrom &&
// @ts-ignore
(redirectedFrom._count = redirectedFrom._count
? // @ts-ignore
redirectedFrom._count + 1
: 1) > 10) {
warn(`Detected an infinite redirection in a navigation guard when going from "${from.fullPath}" to "${toLocation.fullPath}". Aborting to avoid a Stack Overflow. This will break in production if not fixed.`);
return Promise.reject(new Error('Infinite redirect in navigation guard'));
}
return pushWithRedirect(
// keep options
assign(locationAsObject(failure.to), {
state: data,
force,
replace,
}),
// preserve the original redirectedFrom if any
redirectedFrom || toLocation);
}
}
else {
// if we fail we don't finalize the navigation
failure = finalizeNavigation(toLocation, from, true, replace, data);
}
triggerAfterEach(toLocation, from, failure);
return failure;
});
}
/**
* Helper to reject and skip all navigation guards if a new navigation happened
* @param to
* @param from
*/
function checkCanceledNavigationAndReject(to, from) {
const error = checkCanceledNavigation(to, from);
return error ? Promise.reject(error) : Promise.resolve();
}
// TODO: refactor the whole before guards by internally using router.beforeEach
function navigate(to, from) {
let guards;
const [leavingRecords, updatingRecords, enteringRecords,] = extractChangingRecords(to, from);
// all components here have been resolved once because we are leaving
guards = extractComponentsGuards(leavingRecords.reverse(), 'beforeRouteLeave', to, from);
// leavingRecords is already reversed
for (const record of leavingRecords) {
for (const guard of record.leaveGuards) {
guards.push(guardToPromiseFn(guard, to, from));
}
}
const canceledNavigationCheck = checkCanceledNavigationAndReject.bind(null, to, from);
guards.push(canceledNavigationCheck);
// run the queue of per route beforeRouteLeave guards
return (runGuardQueue(guards)
.then(() => {
// check global guards beforeEach
guards = [];
for (const guard of beforeGuards.list()) {
guards.push(guardToPromiseFn(guard, to, from));
}
guards.push(canceledNavigationCheck);
return runGuardQueue(guards);
})
.then(() => {
// check in components beforeRouteUpdate
guards = extractComponentsGuards(updatingRecords, 'beforeRouteUpdate', to, from);
for (const record of updatingRecords) {
for (const guard of record.updateGuards) {
guards.push(guardToPromiseFn(guard, to, from));
}
}
guards.push(canceledNavigationCheck);
// run the queue of per route beforeEnter guards
return runGuardQueue(guards);
})
.then(() => {
// check the route beforeEnter
guards = [];
for (const record of to.matched) {
// do not trigger beforeEnter on reused views
if (record.beforeEnter && from.matched.indexOf(record) < 0) {
if (Array.isArray(record.beforeEnter)) {
for (const beforeEnter of record.beforeEnter)
guards.push(guardToPromiseFn(beforeEnter, to, from));
}
else {
guards.push(guardToPromiseFn(record.beforeEnter, to, from));
}
}
}
guards.push(canceledNavigationCheck);
// run the queue of per route beforeEnter guards
return runGuardQueue(guards);
})
.then(() => {
// NOTE: at this point to.matched is normalized and does not contain any () => Promise<Component>
// clear existing enterCallbacks, these are added by extractComponentsGuards
to.matched.forEach(record => (record.enterCallbacks = {}));
// check in-component beforeRouteEnter
guards = extractComponentsGuards(enteringRecords, 'beforeRouteEnter', to, from);
guards.push(canceledNavigationCheck);
// run the queue of per route beforeEnter guards
return runGuardQueue(guards);
})
.then(() => {
// check global guards beforeResolve
guards = [];
for (const guard of beforeResolveGuards.list()) {
guards.push(guardToPromiseFn(guard, to, from));
}
guards.push(canceledNavigationCheck);
return runGuardQueue(guards);
})
// catch any navigation canceled
.catch(err => isNavigationFailure(err, 8 /* NAVIGATION_CANCELLED */)
? err
: Promise.reject(err)));
}
function triggerAfterEach(to, from, failure) {
// navigation is confirmed, call afterGuards
// TODO: wrap with error handlers
for (const guard of afterGuards.list())
guard(to, from, failure);
}
/**
* - Cleans up any navigation guards
* - Changes the url if necessary
* - Calls the scrollBehavior
*/
function finalizeNavigation(toLocation, from, isPush, replace, data) {
// a more recent navigation took place
const error = checkCanceledNavigation(toLocation, from);
if (error)
return error;
// only consider as push if it's not the first navigation
const isFirstNavigation = from === START_LOCATION_NORMALIZED;
const state = !isBrowser ? {} : history.state;
// change URL only if the user did a push/replace and if it's not the initial navigation because
// it's just reflecting the url
if (isPush) {
// on the initial navigation, we want to reuse the scroll position from
// history state if it exists
if (replace || isFirstNavigation)
routerHistory.replace(toLocation.fullPath, assign({
scroll: isFirstNavigation && state && state.scroll,
}, data));
else
routerHistory.push(toLocation.fullPath, data);
}
// accept current navigation
currentRoute.value = toLocation;
handleScroll(toLocation, from, isPush, isFirstNavigation);
markAsReady();
}
let removeHistoryListener;
// attach listener to history to trigger navigations
function setupListeners() {
removeHistoryListener = routerHistory.listen((to, _from, info) => {
// cannot be a redirect route because it was in history
let toLocation = resolve(to);
// due to dynamic routing, and to hash history with manual navigation
// (manually changing the url or calling history.hash = '#/somewhere'),
// there could be a redirect record in history
const shouldRedirect = handleRedirectRecord(toLocation);
if (shouldRedirect) {
pushWithRedirect(assign(shouldRedirect, { replace: true }), toLocation).catch(noop);
return;
}
pendingLocation = toLocation;
const from = currentRoute.value;
// TODO: should be moved to web history?
if (isBrowser) {
saveScrollPosition(getScrollKey(from.fullPath, info.delta), computeScrollPosition());
}
navigate(toLocation, from)
.catch((error) => {
if (isNavigationFailure(error, 4 /* NAVIGATION_ABORTED */ | 8 /* NAVIGATION_CANCELLED */)) {
return error;
}
if (isNavigationFailure(error, 2 /* NAVIGATION_GUARD_REDIRECT */)) {
// do not restore history on unknown direction
if (info.delta)
routerHistory.go(-info.delta, false);
// the error is already handled by router.push we just want to avoid
// logging the error
pushWithRedirect(
// TODO: should we force replace: true
error.to, toLocation
// avoid an uncaught rejection, let push call triggerError
).catch(noop);
// avoid the then branch
return Promise.reject();
}
// do not restore history on unknown direction
if (info.delta)
routerHistory.go(-info.delta, false);
// unrecognized error, transfer to the global handler
return triggerError(error);
})
.then((failure) => {
failure =
failure ||
finalizeNavigation(
// after navigation, all matched components are resolved
toLocation, from, false);
// revert the navigation
if (failure && info.delta)
routerHistory.go(-info.delta, false);
triggerAfterEach(toLocation, from, failure);
})
.catch(noop);
});
}
// Initialization and Errors
let readyHandlers = useCallbacks();
let errorHandlers = useCallbacks();
let ready;
/**
* Trigger errorHandlers added via onError and throws the error as well
* @param error - error to throw
* @returns the error as a rejected promise
*/
function triggerError(error) {
markAsReady(error);
errorHandlers.list().forEach(handler => handler(error));
return Promise.reject(error);
}
function isReady() {
if (ready && currentRoute.value !== START_LOCATION_NORMALIZED)
return Promise.resolve();
return new Promise((resolve, reject) => {
readyHandlers.add([resolve, reject]);
});
}
/**
* Mark the router as ready, resolving the promised returned by isReady(). Can
* only be called once, otherwise does nothing.
* @param err - optional error
*/
function markAsReady(err) {
if (ready)
return;
ready = true;
setupListeners();
readyHandlers
.list()
.forEach(([resolve, reject]) => (err ? reject(err) : resolve()));
readyHandlers.reset();
}
// Scroll behavior
function handleScroll(to, from, isPush, isFirstNavigation) {
if (!isBrowser || !scrollBehavior)
return Promise.resolve();
let scrollPosition = (!isPush && getSavedScrollPosition(getScrollKey(to.fullPath, 0))) ||
((isFirstNavigation || !isPush) &&
history.state &&
history.state.scroll) ||
null;
return nextTick()
.then(() => scrollBehavior(to, from, scrollPosition))
.then(position => position && scrollToPosition(position))
.catch(triggerError);
}
const go = (delta) => routerHistory.go(delta);
let started;
const installedApps = new Set();
const router = {
currentRoute,
addRoute,
removeRoute,
hasRoute,
getRoutes,
resolve,
options,
push,
replace,
go,
back: () => go(-1),
forward: () => go(1),
beforeEach: beforeGuards.add,
beforeResolve: beforeResolveGuards.add,
afterEach: afterGuards.add,
onError: errorHandlers.add,
isReady,
install(app) {
const router = this;
app.component('RouterLink', RouterLink);
app.component('RouterView', RouterView);
app.config.globalProperties.$router = router;
Object.defineProperty(app.config.globalProperties, '$route', {
get: () => unref(currentRoute),
});
// this initial navigation is only necessary on client, on server it doesn't
// make sense because it will create an extra unnecessary navigation and could
// lead to problems
if (isBrowser &&
// used for the initial navigation client side to avoid pushing
// multiple times when the router is used in multiple apps
!started &&
currentRoute.value === START_LOCATION_NORMALIZED) {
// see above
started = true;
push(routerHistory.location).catch(err => {
if ((process.env.NODE_ENV !== 'production'))
warn('Unexpected error when starting the router:', err);
});
}
const reactiveRoute = {};
for (let key in START_LOCATION_NORMALIZED) {
// @ts-ignore: the key matches
reactiveRoute[key] = computed(() => currentRoute.value[key]);
}
app.provide(routerKey, router);
app.provide(routeLocationKey, reactive(reactiveRoute));
let unmountApp = app.unmount;
installedApps.add(app);
app.unmount = function () {
installedApps.delete(app);
if (installedApps.size < 1) {
removeHistoryListener();
currentRoute.value = START_LOCATION_NORMALIZED;
started = false;
ready = false;
}
unmountApp.call(this, arguments);
};
if (((process.env.NODE_ENV !== 'production') || __VUE_PROD_DEVTOOLS__) && true) {
addDevtools(app, router, matcher);
}
},
};
return router;
}
function runGuardQueue(guards) {
return guards.reduce((promise, guard) => promise.then(() => guard()), Promise.resolve());
}
function extractChangingRecords(to, from) {
const leavingRecords = [];
const updatingRecords = [];
const enteringRecords = [];
const len = Math.max(from.matched.length, to.matched.length);
for (let i = 0; i < len; i++) {
const recordFrom = from.matched[i];
if (recordFrom) {
if (to.matched.indexOf(recordFrom) < 0)
leavingRecords.push(recordFrom);
else
updatingRecords.push(recordFrom);
}
const recordTo = to.matched[i];
if (recordTo) {
// the type doesn't matter because we are comparing per reference
if (from.matched.indexOf(recordTo) < 0)
enteringRecords.push(recordTo);
}
}
return [leavingRecords, updatingRecords, enteringRecords];
}
/**
* Returns the router instance. Equivalent to using `$router` inside
* templates.
*/
function useRouter() {
return inject(routerKey);
}
/**
* Returns the current route location. Equivalent to using `$route` inside
* templates.
*/
function useRoute() {
return inject(routeLocationKey);
}
export { NavigationFailureType, RouterLink, RouterView, START_LOCATION_NORMALIZED as START_LOCATION, createMemoryHistory, createRouter, createRouterMatcher, createWebHashHistory, createWebHistory, isNavigationFailure, matchedRouteKey, onBeforeRouteLeave, onBeforeRouteUpdate, parseQuery, routeLocationKey, routerKey, stringifyQuery, useLink, useRoute, useRouter, viewDepthKey };
|
/*
Highstock JS v8.1.1 (2020-06-09)
Indicator series type for Highstock
(c) 2010-2019 Daniel Studencki
License: www.highcharts.com/license
*/
(function(a){"object"===typeof module&&module.exports?(a["default"]=a,module.exports=a):"function"===typeof define&&define.amd?define("highcharts/indicators/keltner-channels",["highcharts","highcharts/modules/stock"],function(d){a(d);a.Highcharts=d;return a}):a("undefined"!==typeof Highcharts?Highcharts:void 0)})(function(a){function d(a,b,d,k){a.hasOwnProperty(b)||(a[b]=k.apply(null,d))}a=a?a._modules:{};d(a,"mixins/multipe-lines.js",[a["parts/Globals.js"],a["parts/Utilities.js"]],function(a,b){var d=
b.defined,k=b.error,l=b.merge,m=a.seriesTypes.sma;return{pointArrayMap:["top","bottom"],pointValKey:"top",linesApiNames:["bottomLine"],getTranslatedLinesNames:function(g){var a=[];(this.pointArrayMap||[]).forEach(function(c){c!==g&&a.push("plot"+c.charAt(0).toUpperCase()+c.slice(1))});return a},toYData:function(g){var a=[];(this.pointArrayMap||[]).forEach(function(c){a.push(g[c])});return a},translate:function(){var a=this,b=a.pointArrayMap,c=[],e;c=a.getTranslatedLinesNames();m.prototype.translate.apply(a,
arguments);a.points.forEach(function(g){b.forEach(function(b,d){e=g[b];null!==e&&(g[c[d]]=a.yAxis.toPixels(e,!0))})})},drawGraph:function(){var a=this,b=a.linesApiNames,c=a.points,e=c.length,r=a.options,w=a.graph,x={options:{gapSize:r.gapSize}},f=[],h;a.getTranslatedLinesNames(a.pointValKey).forEach(function(a,b){for(f[b]=[];e--;)h=c[e],f[b].push({x:h.x,plotX:h.plotX,plotY:h[a],isNull:!d(h[a])});e=c.length});b.forEach(function(b,c){f[c]?(a.points=f[c],r[b]?a.options=l(r[b].styles,x):k('Error: "There is no '+
b+' in DOCS options declared. Check if linesApiNames are consistent with your DOCS line names." at mixin/multiple-line.js:34'),a.graph=a["graph"+b],m.prototype.drawGraph.call(a),a["graph"+b]=a.graph):k('Error: "'+b+" doesn't have equivalent in pointArrayMap. To many elements in linesApiNames relative to pointArrayMap.\"")});a.points=c;a.options=r;a.graph=w;m.prototype.drawGraph.call(a)}}});d(a,"indicators/keltner-channels.src.js",[a["parts/Globals.js"],a["parts/Utilities.js"],a["mixins/multipe-lines.js"]],
function(a,b,d){var k=b.correctFloat,l=b.merge;b=b.seriesType;var m=a.seriesTypes.sma,g=a.seriesTypes.ema,v=a.seriesTypes.atr;b("keltnerchannels","sma",{params:{period:20,periodATR:10,multiplierATR:2},bottomLine:{styles:{lineWidth:1,lineColor:void 0}},topLine:{styles:{lineWidth:1,lineColor:void 0}},tooltip:{pointFormat:'<span style="color:{point.color}">\u25cf</span><b> {series.name}</b><br/>Upper Channel: {point.top}<br/>EMA({series.options.params.period}): {point.middle}<br/>Lower Channel: {point.bottom}<br/>'},
marker:{enabled:!1},dataGrouping:{approximation:"averages"},lineWidth:1},l(d,{pointArrayMap:["top","middle","bottom"],pointValKey:"middle",nameBase:"Keltner Channels",nameComponents:["period","periodATR","multiplierATR"],linesApiNames:["topLine","bottomLine"],requiredIndicators:["ema","atr"],init:function(){m.prototype.init.apply(this,arguments);this.options=l({topLine:{styles:{lineColor:this.color}},bottomLine:{styles:{lineColor:this.color}}},this.options)},getValues:function(a,b){var c=b.period,
d=b.periodATR,e=b.multiplierATR,f=a.yData;f=f?f.length:0;var h=[];b=g.prototype.getValues(a,{period:c,index:b.index});var m=v.prototype.getValues(a,{period:d}),l=[],t=[],p;if(!(f<c)){for(p=c;p<=f;p++){var n=b.values[p-c];var q=m.values[p-d];var u=n[0];a=k(n[1]+e*q[1]);q=k(n[1]-e*q[1]);n=n[1];h.push([u,a,n,q]);l.push(u);t.push([a,n,q])}return{values:h,xData:l,yData:t}}}}));""});d(a,"masters/indicators/keltner-channels.src.js",[],function(){})});
//# sourceMappingURL=keltner-channels.js.map |
class TonicTemplate {
constructor (rawText, templateStrings, unsafe) {
this.isTonicTemplate = true
this.unsafe = unsafe
this.rawText = rawText
this.templateStrings = templateStrings
}
valueOf () { return this.rawText }
toString () { return this.rawText }
}
class Tonic extends window.HTMLElement {
constructor () {
super()
const state = Tonic._states[super.id]
delete Tonic._states[super.id]
this._state = state || {}
this.preventRenderOnReconnect = false
this.props = {}
this.elements = [...this.children]
this.elements.__children__ = true
this.nodes = [...this.childNodes]
this.nodes.__children__ = true
this._events()
}
static _createId () {
return `tonic${Tonic._index++}`
}
static _splitName (s) {
return s.match(/[A-Z][a-z0-9]*/g).join('-')
}
static _normalizeAttrs (o, x = {}) {
[...o].forEach(o => (x[o.name] = o.value))
return x
}
_checkId () {
const _id = super.id
if (!_id) {
const html = this.outerHTML.replace(this.innerHTML, '...')
throw new Error(`Component: ${html} has no id`)
}
return _id
}
get state () {
return (this._checkId(), this._state)
}
set state (newState) {
this._state = (this._checkId(), newState)
}
get id () { return this._checkId() }
set id (newId) { super.id = newId }
_events () {
const hp = Object.getOwnPropertyNames(window.HTMLElement.prototype)
for (const p of this._props) {
if (hp.indexOf('on' + p) === -1) continue
this.addEventListener(p, this)
}
}
_prop (o) {
const id = this._id
const p = `__${id}__${Tonic._createId()}__`
Tonic._data[id] = Tonic._data[id] || {}
Tonic._data[id][p] = o
return p
}
_placehold (r) {
const id = this._id
const ref = `placehold:${id}:${Tonic._createId()}__`
Tonic._children[id] = Tonic._children[id] || {}
Tonic._children[id][ref] = r
return ref
}
static match (el, s) {
if (!el.matches) el = el.parentElement
return el.matches(s) ? el : el.closest(s)
}
static getPropertyNames (proto) {
const props = []
while (proto && proto !== Tonic.prototype) {
props.push(...Object.getOwnPropertyNames(proto))
proto = Object.getPrototypeOf(proto)
}
return props
}
static add (c, htmlName) {
const hasValidName = htmlName || (c.name && c.name.length > 1)
if (!hasValidName) {
throw Error('Mangling. https://bit.ly/2TkJ6zP')
}
if (!htmlName) htmlName = Tonic._splitName(c.name).toLowerCase()
if (!Tonic.ssr && window.customElements.get(htmlName)) {
throw new Error(`Cannot Tonic.add(${c.name}, '${htmlName}') twice`)
}
if (!c.prototype || !c.prototype.isTonicComponent) {
const tmp = { [c.name]: class extends Tonic {} }[c.name]
tmp.prototype.render = c
c = tmp
}
c.prototype._props = Tonic.getPropertyNames(c.prototype)
Tonic._reg[htmlName] = c
Tonic._tags = Object.keys(Tonic._reg).join()
window.customElements.define(htmlName, c)
if (typeof c.stylesheet === 'function') {
Tonic.registerStyles(c.stylesheet)
}
return c
}
static registerStyles (stylesheetFn) {
if (Tonic._stylesheetRegistry.includes(stylesheetFn)) return
Tonic._stylesheetRegistry.push(stylesheetFn)
const styleNode = document.createElement('style')
if (Tonic.nonce) styleNode.setAttribute('nonce', Tonic.nonce)
styleNode.appendChild(document.createTextNode(stylesheetFn()))
if (document.head) document.head.appendChild(styleNode)
}
static escape (s) {
return s.replace(Tonic.ESC, c => Tonic.MAP[c])
}
static unsafeRawString (s, templateStrings) {
return new TonicTemplate(s, templateStrings, true)
}
dispatch (eventName, detail = null) {
const opts = { bubbles: true, detail }
this.dispatchEvent(new window.CustomEvent(eventName, opts))
}
html (strings, ...values) {
const refs = o => {
if (o && o.__children__) return this._placehold(o)
if (o && o.isTonicTemplate) return o.rawText
switch (Object.prototype.toString.call(o)) {
case '[object HTMLCollection]':
case '[object NodeList]': return this._placehold([...o])
case '[object Array]':
if (o.every(x => x.isTonicTemplate && !x.unsafe)) {
return new TonicTemplate(o.join('\n'), null, false)
}
return this._prop(o)
case '[object Object]':
case '[object Function]': return this._prop(o)
case '[object NamedNodeMap]':
return this._prop(Tonic._normalizeAttrs(o))
case '[object Number]': return `${o}__float`
case '[object String]': return Tonic.escape(o)
case '[object Boolean]': return `${o}__boolean`
case '[object Null]': return `${o}__null`
case '[object HTMLElement]':
return this._placehold([o])
}
if (
typeof o === 'object' && o && o.nodeType === 1 &&
typeof o.cloneNode === 'function'
) {
return this._placehold([o])
}
return o
}
const out = []
for (let i = 0; i < strings.length - 1; i++) {
out.push(strings[i], refs(values[i]))
}
out.push(strings[strings.length - 1])
const htmlStr = out.join('').replace(Tonic.SPREAD, (_, p) => {
const o = Tonic._data[p.split('__')[1]][p]
return Object.entries(o).map(([key, value]) => {
const k = key.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase()
if (value === true) return k
else if (value) return `${k}="${Tonic.escape(String(value))}"`
else return ''
}).filter(Boolean).join(' ')
})
return new TonicTemplate(htmlStr, strings, false)
}
scheduleReRender (oldProps) {
if (this.pendingReRender) return this.pendingReRender
this.pendingReRender = new Promise(resolve => setTimeout(() => {
if (!this.isInDocument(this.shadowRoot || this)) return
const p = this._set(this.shadowRoot || this, this.render)
this.pendingReRender = null
if (p && p.then) {
return p.then(() => {
this.updated && this.updated(oldProps)
resolve()
})
}
this.updated && this.updated(oldProps)
resolve()
}, 0))
return this.pendingReRender
}
reRender (o = this.props) {
const oldProps = { ...this.props }
this.props = typeof o === 'function' ? o(oldProps) : o
return this.scheduleReRender(oldProps)
}
handleEvent (e) {
this[e.type](e)
}
_drainIterator (target, iterator) {
return iterator.next().then((result) => {
this._set(target, null, result.value)
if (result.done) return
return this._drainIterator(target, iterator)
})
}
_set (target, render, content = '') {
for (const node of target.querySelectorAll(Tonic._tags)) {
if (!node.isTonicComponent) continue
const id = node.getAttribute('id')
if (!id || !Tonic._refIds.includes(id)) continue
Tonic._states[id] = node.state
}
if (render instanceof Tonic.AsyncFunction) {
return (render
.call(this, this.html, this.props)
.then(content => this._apply(target, content))
)
} else if (render instanceof Tonic.AsyncFunctionGenerator) {
return this._drainIterator(target, render.call(this))
} else if (render === null) {
this._apply(target, content)
} else if (render instanceof Function) {
this._apply(target, render.call(this, this.html, this.props) || '')
}
}
_apply (target, content) {
if (content && content.isTonicTemplate) {
content = content.rawText
} else if (typeof content === 'string') {
content = Tonic.escape(content)
}
if (typeof content === 'string') {
if (this.stylesheet) {
content = `<style nonce=${Tonic.nonce || ''}>${this.stylesheet()}</style>${content}`
}
target.innerHTML = content
if (this.styles) {
const styles = this.styles()
for (const node of target.querySelectorAll('[styles]')) {
for (const s of node.getAttribute('styles').split(/\s+/)) {
Object.assign(node.style, styles[s.trim()])
}
}
}
const children = Tonic._children[this._id] || {}
const walk = (node, fn) => {
if (node.nodeType === 3) {
const id = node.textContent.trim()
if (children[id]) fn(node, children[id], id)
}
const childNodes = node.childNodes
if (!childNodes) return
for (let i = 0; i < childNodes.length; i++) {
walk(childNodes[i], fn)
}
}
walk(target, (node, children, id) => {
for (const child of children) {
node.parentNode.insertBefore(child, node)
}
delete Tonic._children[this._id][id]
node.parentNode.removeChild(node)
})
} else {
target.innerHTML = ''
target.appendChild(content.cloneNode(true))
}
}
connectedCallback () {
this.root = this.shadowRoot || this // here for back compat
if (super.id && !Tonic._refIds.includes(super.id)) {
Tonic._refIds.push(super.id)
}
const cc = s => s.replace(/-(.)/g, (_, m) => m.toUpperCase())
for (const { name: _name, value } of this.attributes) {
const name = cc(_name)
const p = this.props[name] = value
if (/__\w+__\w+__/.test(p)) {
const { 1: root } = p.split('__')
this.props[name] = Tonic._data[root][p]
} else if (/\d+__float/.test(p)) {
this.props[name] = parseFloat(p, 10)
} else if (p === 'null__null') {
this.props[name] = null
} else if (/\w+__boolean/.test(p)) {
this.props[name] = p.includes('true')
} else if (/placehold:\w+:\w+__/.test(p)) {
const { 1: root } = p.split(':')
this.props[name] = Tonic._children[root][p][0]
}
}
this.props = Object.assign(
this.defaults ? this.defaults() : {},
this.props
)
this._id = this._id || Tonic._createId()
this.willConnect && this.willConnect()
if (!this.isInDocument(this.root)) return
if (!this.preventRenderOnReconnect) {
if (!this._source) {
this._source = this.innerHTML
} else {
this.innerHTML = this._source
}
const p = this._set(this.root, this.render)
if (p && p.then) return p.then(() => this.connected && this.connected())
}
this.connected && this.connected()
}
isInDocument (target) {
const root = target.getRootNode()
return root === document || root.toString() === '[object ShadowRoot]'
}
disconnectedCallback () {
this.disconnected && this.disconnected()
delete Tonic._data[this._id]
delete Tonic._children[this._id]
}
}
Tonic.prototype.isTonicComponent = true
Object.assign(Tonic, {
_tags: '',
_refIds: [],
_data: {},
_states: {},
_children: {},
_reg: {},
_stylesheetRegistry: [],
_index: 0,
version: typeof require !== 'undefined' ? require('./package').version : null,
SPREAD: /\.\.\.\s?(__\w+__\w+__)/g,
ESC: /["&'<>`/]/g,
AsyncFunctionGenerator: async function * () {}.constructor,
AsyncFunction: async function () {}.constructor,
MAP: { '"': '"', '&': '&', '\'': ''', '<': '<', '>': '>', '`': '`', '/': '/' }
})
if (typeof module === 'object') module.exports = Tonic
|
'use strict';(function(d,m){"object"===typeof exports&&"undefined"!==typeof module?m(exports,require("react"),require("history"),require("react-router")):"function"===typeof define&&define.amd?define(["exports","react","history","react-router"],m):(d=d||self,m(d.ReactRouterDOM={},d.React,d.HistoryLibrary,d.ReactRouter))})(this,function(d,m,x,k){function y(){y=Object.assign||function(a){for(var b=1;b<arguments.length;b++){var c=arguments[b],l;for(l in c)Object.prototype.hasOwnProperty.call(c,l)&&(a[l]=
c[l])}return a};return y.apply(this,arguments)}function M(a,b){if(null==a)return{};var c={},l=Object.keys(a),e;for(e=0;e<l.length;e++){var g=l[e];0<=b.indexOf(g)||(c[g]=a[g])}return c}function S(a,b){if(a){if("string"===typeof a)return N(a,b);var c=Object.prototype.toString.call(a).slice(8,-1);"Object"===c&&a.constructor&&(c=a.constructor.name);if("Map"===c||"Set"===c)return Array.from(c);if("Arguments"===c||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(c))return N(a,b)}}function N(a,b){if(null==
b||b>a.length)b=a.length;for(var c=0,l=Array(b);c<b;c++)l[c]=a[c];return l}function T(a){var b=0;if("undefined"===typeof Symbol||null==a[Symbol.iterator]){if(Array.isArray(a)||(a=S(a)))return function(){return b>=a.length?{done:!0}:{done:!1,value:a[b++]}};throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");}b=a[Symbol.iterator]();return b.next.bind(b)}function E(a,b){return b={exports:{}},a(b,
b.exports),b.exports}function F(a,b,c,l,e){for(var g in a)if(U(a,g)){try{if("function"!==typeof a[g]){var d=Error((l||"React class")+": "+c+" type `"+g+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof a[g]+"`.");d.name="Invariant Violation";throw d;}var q=a[g](b,g,l,c,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(v){q=v}!q||q instanceof Error||G((l||"React class")+": type specification of "+c+" `"+g+"` is invalid; the type checker function must return `null` or an `Error` but returned a "+
typeof q+". You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).");if(q instanceof Error&&!(q.message in H)){H[q.message]=!0;var k=e?e():"";G("Failed "+c+" type: "+q.message+(null!=k?k:""))}}}function z(){return null}function V(a,b){if(!a){"undefined"!==typeof console&&console.warn(b);try{throw Error(b);}catch(c){}}}function I(a){var b=a.children;a=a.window;var c=m.useRef();null==c.current&&(c.current=
x.createBrowserHistory({window:a}));var l=c.current;a=m.useReducer(function(a,b){return b},{action:l.action,location:l.location});c=a[0];var e=a[1];m.useLayoutEffect(function(){return l.listen(e)},[l]);return m.createElement(k.Router,{children:b,action:c.action,location:c.location,navigator:l})}function J(a){var b=a.children;a=a.window;var c=m.useRef();null==c.current&&(c.current=x.createHashHistory({window:a}));var l=c.current;a=m.useReducer(function(a,b){return b},{action:l.action,location:l.location});
c=a[0];var e=a[1];m.useLayoutEffect(function(){return l.listen(e)},[l]);return m.createElement(k.Router,{children:b,action:c.action,location:c.location,navigator:l})}function K(a){O(a.message,a.when);return null}function O(a,b){void 0===b&&(b=!0);var c=m.useCallback(function(b){window.confirm(a)&&b.retry()},[a]);k.useBlocker(c,b)}function A(a){void 0===a&&(a="");return new URLSearchParams("string"===typeof a||Array.isArray(a)||a instanceof URLSearchParams?a:Object.keys(a).reduce(function(b,c){var l=
a[c];return b.concat(Array.isArray(l)?l.map(function(a){return[c,a]}):[[c,l]])},[]))}var aa=E(function(a,b){(function(){function a(a){if("object"===typeof a&&null!==a){var b=a.$$typeof;switch(b){case g:switch(a=a.type,a){case f:case u:case k:case m:case h:case B:return a;default:switch(a=a&&a.$$typeof,a){case n:case r:case C:case D:case p:return a;default:return b}}case d:return b}}}function l(f){return a(f)===u}var e="function"===typeof Symbol&&Symbol.for,g=e?Symbol.for("react.element"):60103,d=
e?Symbol.for("react.portal"):60106,k=e?Symbol.for("react.fragment"):60107,h=e?Symbol.for("react.strict_mode"):60108,m=e?Symbol.for("react.profiler"):60114,p=e?Symbol.for("react.provider"):60109,n=e?Symbol.for("react.context"):60110,f=e?Symbol.for("react.async_mode"):60111,u=e?Symbol.for("react.concurrent_mode"):60111,r=e?Symbol.for("react.forward_ref"):60112,B=e?Symbol.for("react.suspense"):60113,W=e?Symbol.for("react.suspense_list"):60120,D=e?Symbol.for("react.memo"):60115,C=e?Symbol.for("react.lazy"):
60116,X=e?Symbol.for("react.block"):60121,Y=e?Symbol.for("react.fundamental"):60117,t=e?Symbol.for("react.responder"):60118,Z=e?Symbol.for("react.scope"):60119,P=!1;b.AsyncMode=f;b.ConcurrentMode=u;b.ContextConsumer=n;b.ContextProvider=p;b.Element=g;b.ForwardRef=r;b.Fragment=k;b.Lazy=C;b.Memo=D;b.Portal=d;b.Profiler=m;b.StrictMode=h;b.Suspense=B;b.isAsyncMode=function(b){P||(P=!0,console.warn("The ReactIs.isAsyncMode() alias has been deprecated, and will be removed in React 17+. Update your code to use ReactIs.isConcurrentMode() instead. It has the exact same API."));
return l(b)||a(b)===f};b.isConcurrentMode=l;b.isContextConsumer=function(f){return a(f)===n};b.isContextProvider=function(f){return a(f)===p};b.isElement=function(a){return"object"===typeof a&&null!==a&&a.$$typeof===g};b.isForwardRef=function(f){return a(f)===r};b.isFragment=function(f){return a(f)===k};b.isLazy=function(f){return a(f)===C};b.isMemo=function(f){return a(f)===D};b.isPortal=function(f){return a(f)===d};b.isProfiler=function(f){return a(f)===m};b.isStrictMode=function(f){return a(f)===
h};b.isSuspense=function(f){return a(f)===B};b.isValidElementType=function(a){return"string"===typeof a||"function"===typeof a||a===k||a===u||a===m||a===h||a===B||a===W||"object"===typeof a&&null!==a&&(a.$$typeof===C||a.$$typeof===D||a.$$typeof===p||a.$$typeof===n||a.$$typeof===r||a.$$typeof===Y||a.$$typeof===t||a.$$typeof===Z||a.$$typeof===X)};b.typeOf=a})()}),Q=E(function(a){a.exports=aa}),R=Object.getOwnPropertySymbols,ba=Object.prototype.hasOwnProperty,ca=Object.prototype.propertyIsEnumerable,
da=function(){try{if(!Object.assign)return!1;var a=new String("abc");a[5]="de";if("5"===Object.getOwnPropertyNames(a)[0])return!1;var b={};for(a=0;10>a;a++)b["_"+String.fromCharCode(a)]=a;if("0123456789"!==Object.getOwnPropertyNames(b).map(function(a){return b[a]}).join(""))return!1;var c={};"abcdefghijklmnopqrst".split("").forEach(function(a){c[a]=a});return"abcdefghijklmnopqrst"!==Object.keys(Object.assign({},c)).join("")?!1:!0}catch(l){return!1}}()?Object.assign:function(a,b){if(null===a||void 0===
a)throw new TypeError("Object.assign cannot be called with null or undefined");var c=Object(a);for(var l,e=1;e<arguments.length;e++){var g=Object(arguments[e]);for(var d in g)ba.call(g,d)&&(c[d]=g[d]);if(R){l=R(g);for(var k=0;k<l.length;k++)ca.call(g,l[k])&&(c[l[k]]=g[l[k]])}}return c},G=function(){},H={},U=Function.call.bind(Object.prototype.hasOwnProperty);G=function(a){a="Warning: "+a;"undefined"!==typeof console&&console.error(a);try{throw Error(a);}catch(b){}};F.resetWarningCache=function(){H=
{}};var ea=Function.call.bind(Object.prototype.hasOwnProperty),t=function(){};t=function(a){a="Warning: "+a;"undefined"!==typeof console&&console.error(a);try{throw Error(a);}catch(b){}};var fa=function(a,b){function c(a,b){return a===b?0!==a||1/a===1/b:a!==a&&b!==b}function l(a){this.message=a;this.stack=""}function e(a){function f(f,u,e,r,d,g,h){r=r||"<<anonymous>>";g=g||e;if("SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"!==h){if(b)throw f=Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use `PropTypes.checkPropTypes()` to call them. Read more at http://fb.me/use-check-prop-types"),
f.name="Invariant Violation",f;"undefined"!==typeof console&&(h=r+":"+e,!c[h]&&3>k&&(t("You are manually calling a React.PropTypes validation function for the `"+g+"` prop on `"+r+"`. This is deprecated and will throw in the standalone `prop-types` package. You may be seeing this warning due to a third-party PropTypes library. See https://fb.me/react-warning-dont-call-proptypes for details."),c[h]=!0,k++))}return null==u[e]?f?null===u[e]?new l("The "+d+" `"+g+"` is marked as required in `"+(r+"`, but its value is `null`.")):
new l("The "+d+" `"+g+"` is marked as required in `"+(r+"`, but its value is `undefined`.")):null:a(u,e,r,d,g)}var c={},k=0,e=f.bind(null,!1);e.isRequired=f.bind(null,!0);return e}function g(a){return e(function(f,b,c,e,d,g){f=f[b];return k(f)!==a?(f=h(f),new l("Invalid "+e+" `"+d+"` of type `"+(f+"` supplied to `"+c+"`, expected `")+(a+"`."))):null})}function d(f){switch(typeof f){case "number":case "string":case "undefined":return!0;case "boolean":return!f;case "object":if(Array.isArray(f))return f.every(d);
if(null===f||a(f))return!0;var b=f&&(p&&f[p]||f["@@iterator"]);var c="function"===typeof b?b:void 0;if(c)if(b=c.call(f),c!==f.entries)for(;!(f=b.next()).done;){if(!d(f.value))return!1}else for(;!(f=b.next()).done;){if((f=f.value)&&!d(f[1]))return!1}else return!1;return!0;default:return!1}}function k(a){var f=typeof a;return Array.isArray(a)?"array":a instanceof RegExp?"object":"symbol"===f||a&&("Symbol"===a["@@toStringTag"]||"function"===typeof Symbol&&a instanceof Symbol)?"symbol":f}function h(a){if("undefined"===
typeof a||null===a)return""+a;var b=k(a);if("object"===b){if(a instanceof Date)return"date";if(a instanceof RegExp)return"regexp"}return b}function m(a){a=h(a);switch(a){case "array":case "object":return"an "+a;case "boolean":case "date":case "regexp":return"a "+a;default:return a}}var p="function"===typeof Symbol&&Symbol.iterator,n={array:g("array"),bool:g("boolean"),func:g("function"),number:g("number"),object:g("object"),string:g("string"),symbol:g("symbol"),any:e(z),arrayOf:function(a){return e(function(b,
f,c,e,d){if("function"!==typeof a)return new l("Property `"+d+"` of component `"+c+"` has invalid PropType notation inside arrayOf.");b=b[f];if(!Array.isArray(b))return b=k(b),new l("Invalid "+e+" `"+d+"` of type `"+(b+"` supplied to `"+c+"`, expected an array."));for(f=0;f<b.length;f++){var g=a(b,f,c,e,d+"["+f+"]","SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED");if(g instanceof Error)return g}return null})},element:function(){return e(function(b,c,e,d,g){b=b[c];return a(b)?null:(b=k(b),new l("Invalid "+
d+" `"+g+"` of type `"+(b+"` supplied to `"+e+"`, expected a single ReactElement.")))})}(),elementType:function(){return e(function(a,b,c,e,d){a=a[b];return Q.isValidElementType(a)?null:(a=k(a),new l("Invalid "+e+" `"+d+"` of type `"+(a+"` supplied to `"+c+"`, expected a single ReactElement type.")))})}(),instanceOf:function(a){return e(function(b,f,c,e,d){if(!(b[f]instanceof a)){var g=a.name||"<<anonymous>>";b=b[f];b=b.constructor&&b.constructor.name?b.constructor.name:"<<anonymous>>";return new l("Invalid "+
e+" `"+d+"` of type `"+(b+"` supplied to `"+c+"`, expected instance of `")+(g+"`."))}return null})},node:function(){return e(function(a,b,c,e,g){return d(a[b])?null:new l("Invalid "+e+" `"+g+"` supplied to `"+(c+"`, expected a ReactNode."))})}(),objectOf:function(a){return e(function(b,c,f,e,d){if("function"!==typeof a)return new l("Property `"+d+"` of component `"+f+"` has invalid PropType notation inside objectOf.");b=b[c];c=k(b);if("object"!==c)return new l("Invalid "+e+" `"+d+"` of type `"+(c+
"` supplied to `"+f+"`, expected an object."));for(var g in b)if(ea(b,g)&&(c=a(b,g,f,e,d+"."+g,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"),c instanceof Error))return c;return null})},oneOf:function(a){return Array.isArray(a)?e(function(b,f,e,d,g){b=b[f];for(f=0;f<a.length;f++)if(c(b,a[f]))return null;f=JSON.stringify(a,function(a,b){return"symbol"===h(b)?String(b):b});return new l("Invalid "+d+" `"+g+"` of value `"+String(b)+"` supplied to `"+(e+"`, expected one of "+f+"."))}):(1<arguments.length?
t("Invalid arguments supplied to oneOf, expected an array, got "+arguments.length+" arguments. A common mistake is to write oneOf(x, y, z) instead of oneOf([x, y, z])."):t("Invalid argument supplied to oneOf, expected an array."),z)},oneOfType:function(a){if(!Array.isArray(a))return t("Invalid argument supplied to oneOfType, expected an instance of array."),z;for(var b=0;b<a.length;b++){var c=a[b];if("function"!==typeof c)return t("Invalid argument supplied to oneOfType. Expected an array of check functions, but received "+
m(c)+" at index "+b+"."),z}return e(function(b,c,f,e,d){for(var g=0;g<a.length;g++)if(null==(0,a[g])(b,c,f,e,d,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"))return null;return new l("Invalid "+e+" `"+d+"` supplied to `"+(f+"`."))})},shape:function(a){return e(function(b,c,f,e,d){b=b[c];c=k(b);if("object"!==c)return new l("Invalid "+e+" `"+d+"` of type `"+c+"` supplied to `"+(f+"`, expected `object`."));for(var g in a)if(c=a[g])if(c=c(b,g,f,e,d+"."+g,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"))return c;
return null})},exact:function(a){return e(function(b,c,f,e,d){var g=b[c],h=k(g);if("object"!==h)return new l("Invalid "+e+" `"+d+"` of type `"+h+"` supplied to `"+(f+"`, expected `object`."));h=da({},b[c],a);for(var m in h){h=a[m];if(!h)return new l("Invalid "+e+" `"+d+"` key `"+m+"` supplied to `"+f+"`.\nBad object: "+JSON.stringify(b[c],null," ")+"\nValid keys: "+JSON.stringify(Object.keys(a),null," "));if(h=h(g,m,f,e,d+"."+m,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"))return h}return null})}};
l.prototype=Error.prototype;n.checkPropTypes=F;n.resetWarningCache=F.resetWarningCache;return n.PropTypes=n},h=E(function(a){a.exports=fa(Q.isElement,!0)});I.displayName="BrowserRouter";I.propTypes={children:h.node,window:h.object};J.displayName="HashRouter";J.propTypes={children:h.node,window:h.object};var w=m.forwardRef(function(a,b){var c=a.onClick,d=a.replace,e=void 0===d?!1:d,g=a.state,h=a.target,q=a.to;a=M(a,["onClick","replace","state","target","to"]);d=k.useHref(q);var t=k.useNavigate(),v=
k.useLocation(),p=k.useResolvedPath(q);return m.createElement("a",Object.assign({},a,{href:d,onClick:function(a){c&&c(a);a.defaultPrevented||0!==a.button||h&&"_self"!==h||a.metaKey||a.altKey||a.ctrlKey||a.shiftKey||(a.preventDefault(),a=!!e||x.createPath(v)===x.createPath(p),t(q,{replace:a,state:g}))},ref:b,target:h}))});w.displayName="Link";w.propTypes={onClick:h.func,replace:h.bool,state:h.object,target:h.string,to:h.oneOfType([h.string,h.shape({pathname:h.string,search:h.string,hash:h.string})]).isRequired};
var L=m.forwardRef(function(a,b){var c=a["aria-current"],d=void 0===c?"page":c;c=a.activeClassName;var e=void 0===c?"active":c;c=a.activeStyle;var g=a.caseSensitive,h=void 0===g?!1:g;g=a.className;var q=void 0===g?"":g;g=a.end;var t=void 0===g?!1:g,v=a.style;g=a.to;a=M(a,"aria-current activeClassName activeStyle caseSensitive className end style to".split(" "));var p=k.useLocation(),n=k.useResolvedPath(g);p=p.pathname;n=n.pathname;h||(p=p.toLowerCase(),n=n.toLowerCase());d=(h=t?p===n:p.startsWith(n))?
d:void 0;e=[q,h?e:null].filter(Boolean).join(" ");c=y({},v,{},h?c:null);return m.createElement(w,Object.assign({},a,{"aria-current":d,className:e,ref:b,style:c,to:g}))});L.displayName="NavLink";L.propTypes=y({},w.propTypes,{"aria-current":h.oneOf("page step location date time true".split(" ")),activeClassName:h.string,activeStyle:h.object,className:h.string,style:h.object,to:h.oneOfType([h.string,h.shape({pathname:h.string,search:h.string,hash:h.string})]).isRequired});K.displayName="Prompt";K.propTypes=
{message:h.string,when:h.bool};Object.defineProperty(d,"MemoryRouter",{enumerable:!0,get:function(){return k.MemoryRouter}});Object.defineProperty(d,"Navigate",{enumerable:!0,get:function(){return k.Navigate}});Object.defineProperty(d,"Outlet",{enumerable:!0,get:function(){return k.Outlet}});Object.defineProperty(d,"Route",{enumerable:!0,get:function(){return k.Route}});Object.defineProperty(d,"Router",{enumerable:!0,get:function(){return k.Router}});Object.defineProperty(d,"Routes",{enumerable:!0,
get:function(){return k.Routes}});Object.defineProperty(d,"createRoutesFromArray",{enumerable:!0,get:function(){return k.createRoutesFromArray}});Object.defineProperty(d,"createRoutesFromChildren",{enumerable:!0,get:function(){return k.createRoutesFromChildren}});Object.defineProperty(d,"generatePath",{enumerable:!0,get:function(){return k.generatePath}});Object.defineProperty(d,"matchPath",{enumerable:!0,get:function(){return k.matchPath}});Object.defineProperty(d,"matchRoutes",{enumerable:!0,get:function(){return k.matchRoutes}});
Object.defineProperty(d,"resolvePath",{enumerable:!0,get:function(){return k.resolvePath}});Object.defineProperty(d,"useBlocker",{enumerable:!0,get:function(){return k.useBlocker}});Object.defineProperty(d,"useHref",{enumerable:!0,get:function(){return k.useHref}});Object.defineProperty(d,"useInRouterContext",{enumerable:!0,get:function(){return k.useInRouterContext}});Object.defineProperty(d,"useLocation",{enumerable:!0,get:function(){return k.useLocation}});Object.defineProperty(d,"useMatch",{enumerable:!0,
get:function(){return k.useMatch}});Object.defineProperty(d,"useNavigate",{enumerable:!0,get:function(){return k.useNavigate}});Object.defineProperty(d,"useOutlet",{enumerable:!0,get:function(){return k.useOutlet}});Object.defineProperty(d,"useParams",{enumerable:!0,get:function(){return k.useParams}});Object.defineProperty(d,"useResolvedPath",{enumerable:!0,get:function(){return k.useResolvedPath}});Object.defineProperty(d,"useRoutes",{enumerable:!0,get:function(){return k.useRoutes}});d.BrowserRouter=
I;d.HashRouter=J;d.Link=w;d.NavLink=L;d.Prompt=K;d.createSearchParams=A;d.usePrompt=O;d.useSearchParams=function(a){V("undefined"!==typeof URLSearchParams,"You cannot use the `useSearchParams` hook in a browser that does not support the URLSearchParams API. If you need to support Internet Explorer 11, we recommend you load a polyfill such as https://github.com/ungap/url-search-params\n\nIf you're unsure how to load polyfills, we recommend you check out https://polyfill.io/v3/ which provides some recommendations about how to load polyfills only for users that need them, instead of for every user.");
var b=m.useRef(A(a)),c=k.useLocation();a=m.useMemo(function(){for(var a=A(c.search),d=function(){var c=h.value;a.has(c)||b.current.getAll(c).forEach(function(b){a.append(c,b)})},e=T(b.current.keys()),h;!(h=e()).done;)d();return a},[c.search]);var d=k.useNavigate(),e=m.useCallback(function(a,b){d("?"+A(a),b)},[d]);return[a,e]};Object.defineProperty(d,"__esModule",{value:!0})});
//# sourceMappingURL=react-router-dom.development.js.map
|
typeof window !== "undefined" &&
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else if(typeof exports === 'object')
exports["Hls"] = factory();
else
root["Hls"] = factory();
})(this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "/dist/";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = "./src/hls.ts");
/******/ })
/************************************************************************/
/******/ ({
/***/ "./node_modules/eventemitter3/index.js":
/*!*********************************************!*\
!*** ./node_modules/eventemitter3/index.js ***!
\*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var has = Object.prototype.hasOwnProperty
, prefix = '~';
/**
* Constructor to create a storage for our `EE` objects.
* An `Events` instance is a plain object whose properties are event names.
*
* @constructor
* @private
*/
function Events() {}
//
// We try to not inherit from `Object.prototype`. In some engines creating an
// instance in this way is faster than calling `Object.create(null)` directly.
// If `Object.create(null)` is not supported we prefix the event names with a
// character to make sure that the built-in object properties are not
// overridden or used as an attack vector.
//
if (Object.create) {
Events.prototype = Object.create(null);
//
// This hack is needed because the `__proto__` property is still inherited in
// some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.
//
if (!new Events().__proto__) prefix = false;
}
/**
* Representation of a single event listener.
*
* @param {Function} fn The listener function.
* @param {*} context The context to invoke the listener with.
* @param {Boolean} [once=false] Specify if the listener is a one-time listener.
* @constructor
* @private
*/
function EE(fn, context, once) {
this.fn = fn;
this.context = context;
this.once = once || false;
}
/**
* Add a listener for a given event.
*
* @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
* @param {(String|Symbol)} event The event name.
* @param {Function} fn The listener function.
* @param {*} context The context to invoke the listener with.
* @param {Boolean} once Specify if the listener is a one-time listener.
* @returns {EventEmitter}
* @private
*/
function addListener(emitter, event, fn, context, once) {
if (typeof fn !== 'function') {
throw new TypeError('The listener must be a function');
}
var listener = new EE(fn, context || emitter, once)
, evt = prefix ? prefix + event : event;
if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;
else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);
else emitter._events[evt] = [emitter._events[evt], listener];
return emitter;
}
/**
* Clear event by name.
*
* @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
* @param {(String|Symbol)} evt The Event name.
* @private
*/
function clearEvent(emitter, evt) {
if (--emitter._eventsCount === 0) emitter._events = new Events();
else delete emitter._events[evt];
}
/**
* Minimal `EventEmitter` interface that is molded against the Node.js
* `EventEmitter` interface.
*
* @constructor
* @public
*/
function EventEmitter() {
this._events = new Events();
this._eventsCount = 0;
}
/**
* Return an array listing the events for which the emitter has registered
* listeners.
*
* @returns {Array}
* @public
*/
EventEmitter.prototype.eventNames = function eventNames() {
var names = []
, events
, name;
if (this._eventsCount === 0) return names;
for (name in (events = this._events)) {
if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);
}
if (Object.getOwnPropertySymbols) {
return names.concat(Object.getOwnPropertySymbols(events));
}
return names;
};
/**
* Return the listeners registered for a given event.
*
* @param {(String|Symbol)} event The event name.
* @returns {Array} The registered listeners.
* @public
*/
EventEmitter.prototype.listeners = function listeners(event) {
var evt = prefix ? prefix + event : event
, handlers = this._events[evt];
if (!handlers) return [];
if (handlers.fn) return [handlers.fn];
for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
ee[i] = handlers[i].fn;
}
return ee;
};
/**
* Return the number of listeners listening to a given event.
*
* @param {(String|Symbol)} event The event name.
* @returns {Number} The number of listeners.
* @public
*/
EventEmitter.prototype.listenerCount = function listenerCount(event) {
var evt = prefix ? prefix + event : event
, listeners = this._events[evt];
if (!listeners) return 0;
if (listeners.fn) return 1;
return listeners.length;
};
/**
* Calls each of the listeners registered for a given event.
*
* @param {(String|Symbol)} event The event name.
* @returns {Boolean} `true` if the event had listeners, else `false`.
* @public
*/
EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
var evt = prefix ? prefix + event : event;
if (!this._events[evt]) return false;
var listeners = this._events[evt]
, len = arguments.length
, args
, i;
if (listeners.fn) {
if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);
switch (len) {
case 1: return listeners.fn.call(listeners.context), true;
case 2: return listeners.fn.call(listeners.context, a1), true;
case 3: return listeners.fn.call(listeners.context, a1, a2), true;
case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;
case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
}
for (i = 1, args = new Array(len -1); i < len; i++) {
args[i - 1] = arguments[i];
}
listeners.fn.apply(listeners.context, args);
} else {
var length = listeners.length
, j;
for (i = 0; i < length; i++) {
if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);
switch (len) {
case 1: listeners[i].fn.call(listeners[i].context); break;
case 2: listeners[i].fn.call(listeners[i].context, a1); break;
case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;
case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;
default:
if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {
args[j - 1] = arguments[j];
}
listeners[i].fn.apply(listeners[i].context, args);
}
}
}
return true;
};
/**
* Add a listener for a given event.
*
* @param {(String|Symbol)} event The event name.
* @param {Function} fn The listener function.
* @param {*} [context=this] The context to invoke the listener with.
* @returns {EventEmitter} `this`.
* @public
*/
EventEmitter.prototype.on = function on(event, fn, context) {
return addListener(this, event, fn, context, false);
};
/**
* Add a one-time listener for a given event.
*
* @param {(String|Symbol)} event The event name.
* @param {Function} fn The listener function.
* @param {*} [context=this] The context to invoke the listener with.
* @returns {EventEmitter} `this`.
* @public
*/
EventEmitter.prototype.once = function once(event, fn, context) {
return addListener(this, event, fn, context, true);
};
/**
* Remove the listeners of a given event.
*
* @param {(String|Symbol)} event The event name.
* @param {Function} fn Only remove the listeners that match this function.
* @param {*} context Only remove the listeners that have this context.
* @param {Boolean} once Only remove one-time listeners.
* @returns {EventEmitter} `this`.
* @public
*/
EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
var evt = prefix ? prefix + event : event;
if (!this._events[evt]) return this;
if (!fn) {
clearEvent(this, evt);
return this;
}
var listeners = this._events[evt];
if (listeners.fn) {
if (
listeners.fn === fn &&
(!once || listeners.once) &&
(!context || listeners.context === context)
) {
clearEvent(this, evt);
}
} else {
for (var i = 0, events = [], length = listeners.length; i < length; i++) {
if (
listeners[i].fn !== fn ||
(once && !listeners[i].once) ||
(context && listeners[i].context !== context)
) {
events.push(listeners[i]);
}
}
//
// Reset the array, or remove it completely if we have no more listeners.
//
if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;
else clearEvent(this, evt);
}
return this;
};
/**
* Remove all listeners, or those of the specified event.
*
* @param {(String|Symbol)} [event] The event name.
* @returns {EventEmitter} `this`.
* @public
*/
EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
var evt;
if (event) {
evt = prefix ? prefix + event : event;
if (this._events[evt]) clearEvent(this, evt);
} else {
this._events = new Events();
this._eventsCount = 0;
}
return this;
};
//
// Alias methods names because people roll like that.
//
EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
EventEmitter.prototype.addListener = EventEmitter.prototype.on;
//
// Expose the prefix.
//
EventEmitter.prefixed = prefix;
//
// Allow `EventEmitter` to be imported as module namespace.
//
EventEmitter.EventEmitter = EventEmitter;
//
// Expose the module.
//
if (true) {
module.exports = EventEmitter;
}
/***/ }),
/***/ "./node_modules/url-toolkit/src/url-toolkit.js":
/*!*****************************************************!*\
!*** ./node_modules/url-toolkit/src/url-toolkit.js ***!
\*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
// see https://tools.ietf.org/html/rfc1808
(function (root) {
var URL_REGEX =
/^((?:[a-zA-Z0-9+\-.]+:)?)(\/\/[^\/?#]*)?((?:[^\/?#]*\/)*[^;?#]*)?(;[^?#]*)?(\?[^#]*)?(#[^]*)?$/;
var FIRST_SEGMENT_REGEX = /^([^\/?#]*)([^]*)$/;
var SLASH_DOT_REGEX = /(?:\/|^)\.(?=\/)/g;
var SLASH_DOT_DOT_REGEX = /(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g;
var URLToolkit = {
// If opts.alwaysNormalize is true then the path will always be normalized even when it starts with / or //
// E.g
// With opts.alwaysNormalize = false (default, spec compliant)
// http://a.com/b/cd + /e/f/../g => http://a.com/e/f/../g
// With opts.alwaysNormalize = true (not spec compliant)
// http://a.com/b/cd + /e/f/../g => http://a.com/e/g
buildAbsoluteURL: function (baseURL, relativeURL, opts) {
opts = opts || {};
// remove any remaining space and CRLF
baseURL = baseURL.trim();
relativeURL = relativeURL.trim();
if (!relativeURL) {
// 2a) If the embedded URL is entirely empty, it inherits the
// entire base URL (i.e., is set equal to the base URL)
// and we are done.
if (!opts.alwaysNormalize) {
return baseURL;
}
var basePartsForNormalise = URLToolkit.parseURL(baseURL);
if (!basePartsForNormalise) {
throw new Error('Error trying to parse base URL.');
}
basePartsForNormalise.path = URLToolkit.normalizePath(
basePartsForNormalise.path
);
return URLToolkit.buildURLFromParts(basePartsForNormalise);
}
var relativeParts = URLToolkit.parseURL(relativeURL);
if (!relativeParts) {
throw new Error('Error trying to parse relative URL.');
}
if (relativeParts.scheme) {
// 2b) If the embedded URL starts with a scheme name, it is
// interpreted as an absolute URL and we are done.
if (!opts.alwaysNormalize) {
return relativeURL;
}
relativeParts.path = URLToolkit.normalizePath(relativeParts.path);
return URLToolkit.buildURLFromParts(relativeParts);
}
var baseParts = URLToolkit.parseURL(baseURL);
if (!baseParts) {
throw new Error('Error trying to parse base URL.');
}
if (!baseParts.netLoc && baseParts.path && baseParts.path[0] !== '/') {
// If netLoc missing and path doesn't start with '/', assume everthing before the first '/' is the netLoc
// This causes 'example.com/a' to be handled as '//example.com/a' instead of '/example.com/a'
var pathParts = FIRST_SEGMENT_REGEX.exec(baseParts.path);
baseParts.netLoc = pathParts[1];
baseParts.path = pathParts[2];
}
if (baseParts.netLoc && !baseParts.path) {
baseParts.path = '/';
}
var builtParts = {
// 2c) Otherwise, the embedded URL inherits the scheme of
// the base URL.
scheme: baseParts.scheme,
netLoc: relativeParts.netLoc,
path: null,
params: relativeParts.params,
query: relativeParts.query,
fragment: relativeParts.fragment,
};
if (!relativeParts.netLoc) {
// 3) If the embedded URL's <net_loc> is non-empty, we skip to
// Step 7. Otherwise, the embedded URL inherits the <net_loc>
// (if any) of the base URL.
builtParts.netLoc = baseParts.netLoc;
// 4) If the embedded URL path is preceded by a slash "/", the
// path is not relative and we skip to Step 7.
if (relativeParts.path[0] !== '/') {
if (!relativeParts.path) {
// 5) If the embedded URL path is empty (and not preceded by a
// slash), then the embedded URL inherits the base URL path
builtParts.path = baseParts.path;
// 5a) if the embedded URL's <params> is non-empty, we skip to
// step 7; otherwise, it inherits the <params> of the base
// URL (if any) and
if (!relativeParts.params) {
builtParts.params = baseParts.params;
// 5b) if the embedded URL's <query> is non-empty, we skip to
// step 7; otherwise, it inherits the <query> of the base
// URL (if any) and we skip to step 7.
if (!relativeParts.query) {
builtParts.query = baseParts.query;
}
}
} else {
// 6) The last segment of the base URL's path (anything
// following the rightmost slash "/", or the entire path if no
// slash is present) is removed and the embedded URL's path is
// appended in its place.
var baseURLPath = baseParts.path;
var newPath =
baseURLPath.substring(0, baseURLPath.lastIndexOf('/') + 1) +
relativeParts.path;
builtParts.path = URLToolkit.normalizePath(newPath);
}
}
}
if (builtParts.path === null) {
builtParts.path = opts.alwaysNormalize
? URLToolkit.normalizePath(relativeParts.path)
: relativeParts.path;
}
return URLToolkit.buildURLFromParts(builtParts);
},
parseURL: function (url) {
var parts = URL_REGEX.exec(url);
if (!parts) {
return null;
}
return {
scheme: parts[1] || '',
netLoc: parts[2] || '',
path: parts[3] || '',
params: parts[4] || '',
query: parts[5] || '',
fragment: parts[6] || '',
};
},
normalizePath: function (path) {
// The following operations are
// then applied, in order, to the new path:
// 6a) All occurrences of "./", where "." is a complete path
// segment, are removed.
// 6b) If the path ends with "." as a complete path segment,
// that "." is removed.
path = path.split('').reverse().join('').replace(SLASH_DOT_REGEX, '');
// 6c) All occurrences of "<segment>/../", where <segment> is a
// complete path segment not equal to "..", are removed.
// Removal of these path segments is performed iteratively,
// removing the leftmost matching pattern on each iteration,
// until no matching pattern remains.
// 6d) If the path ends with "<segment>/..", where <segment> is a
// complete path segment not equal to "..", that
// "<segment>/.." is removed.
while (
path.length !== (path = path.replace(SLASH_DOT_DOT_REGEX, '')).length
) {}
return path.split('').reverse().join('');
},
buildURLFromParts: function (parts) {
return (
parts.scheme +
parts.netLoc +
parts.path +
parts.params +
parts.query +
parts.fragment
);
},
};
if (true)
module.exports = URLToolkit;
else {}
})(this);
/***/ }),
/***/ "./node_modules/webworkify-webpack/index.js":
/*!**************************************************!*\
!*** ./node_modules/webworkify-webpack/index.js ***!
\**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
function webpackBootstrapFunc (modules) {
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // identity function for calling harmony imports with the correct context
/******/ __webpack_require__.i = function(value) { return value; };
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "/";
/******/ // on error function for async loading
/******/ __webpack_require__.oe = function(err) { console.error(err); throw err; };
var f = __webpack_require__(__webpack_require__.s = ENTRY_MODULE)
return f.default || f // try to call default if defined to also support babel esmodule exports
}
var moduleNameReqExp = '[\\.|\\-|\\+|\\w|\/|@]+'
var dependencyRegExp = '\\(\\s*(\/\\*.*?\\*\/)?\\s*.*?(' + moduleNameReqExp + ').*?\\)' // additional chars when output.pathinfo is true
// http://stackoverflow.com/a/2593661/130442
function quoteRegExp (str) {
return (str + '').replace(/[.?*+^$[\]\\(){}|-]/g, '\\$&')
}
function isNumeric(n) {
return !isNaN(1 * n); // 1 * n converts integers, integers as string ("123"), 1e3 and "1e3" to integers and strings to NaN
}
function getModuleDependencies (sources, module, queueName) {
var retval = {}
retval[queueName] = []
var fnString = module.toString()
var wrapperSignature = fnString.match(/^function\s?\w*\(\w+,\s*\w+,\s*(\w+)\)/)
if (!wrapperSignature) return retval
var webpackRequireName = wrapperSignature[1]
// main bundle deps
var re = new RegExp('(\\\\n|\\W)' + quoteRegExp(webpackRequireName) + dependencyRegExp, 'g')
var match
while ((match = re.exec(fnString))) {
if (match[3] === 'dll-reference') continue
retval[queueName].push(match[3])
}
// dll deps
re = new RegExp('\\(' + quoteRegExp(webpackRequireName) + '\\("(dll-reference\\s(' + moduleNameReqExp + '))"\\)\\)' + dependencyRegExp, 'g')
while ((match = re.exec(fnString))) {
if (!sources[match[2]]) {
retval[queueName].push(match[1])
sources[match[2]] = __webpack_require__(match[1]).m
}
retval[match[2]] = retval[match[2]] || []
retval[match[2]].push(match[4])
}
// convert 1e3 back to 1000 - this can be important after uglify-js converted 1000 to 1e3
var keys = Object.keys(retval);
for (var i = 0; i < keys.length; i++) {
for (var j = 0; j < retval[keys[i]].length; j++) {
if (isNumeric(retval[keys[i]][j])) {
retval[keys[i]][j] = 1 * retval[keys[i]][j];
}
}
}
return retval
}
function hasValuesInQueues (queues) {
var keys = Object.keys(queues)
return keys.reduce(function (hasValues, key) {
return hasValues || queues[key].length > 0
}, false)
}
function getRequiredModules (sources, moduleId) {
var modulesQueue = {
main: [moduleId]
}
var requiredModules = {
main: []
}
var seenModules = {
main: {}
}
while (hasValuesInQueues(modulesQueue)) {
var queues = Object.keys(modulesQueue)
for (var i = 0; i < queues.length; i++) {
var queueName = queues[i]
var queue = modulesQueue[queueName]
var moduleToCheck = queue.pop()
seenModules[queueName] = seenModules[queueName] || {}
if (seenModules[queueName][moduleToCheck] || !sources[queueName][moduleToCheck]) continue
seenModules[queueName][moduleToCheck] = true
requiredModules[queueName] = requiredModules[queueName] || []
requiredModules[queueName].push(moduleToCheck)
var newModules = getModuleDependencies(sources, sources[queueName][moduleToCheck], queueName)
var newModulesKeys = Object.keys(newModules)
for (var j = 0; j < newModulesKeys.length; j++) {
modulesQueue[newModulesKeys[j]] = modulesQueue[newModulesKeys[j]] || []
modulesQueue[newModulesKeys[j]] = modulesQueue[newModulesKeys[j]].concat(newModules[newModulesKeys[j]])
}
}
}
return requiredModules
}
module.exports = function (moduleId, options) {
options = options || {}
var sources = {
main: __webpack_require__.m
}
var requiredModules = options.all ? { main: Object.keys(sources.main) } : getRequiredModules(sources, moduleId)
var src = ''
Object.keys(requiredModules).filter(function (m) { return m !== 'main' }).forEach(function (module) {
var entryModule = 0
while (requiredModules[module][entryModule]) {
entryModule++
}
requiredModules[module].push(entryModule)
sources[module][entryModule] = '(function(module, exports, __webpack_require__) { module.exports = __webpack_require__; })'
src = src + 'var ' + module + ' = (' + webpackBootstrapFunc.toString().replace('ENTRY_MODULE', JSON.stringify(entryModule)) + ')({' + requiredModules[module].map(function (id) { return '' + JSON.stringify(id) + ': ' + sources[module][id].toString() }).join(',') + '});\n'
})
src = src + 'new ((' + webpackBootstrapFunc.toString().replace('ENTRY_MODULE', JSON.stringify(moduleId)) + ')({' + requiredModules.main.map(function (id) { return '' + JSON.stringify(id) + ': ' + sources.main[id].toString() }).join(',') + '}))(self);'
var blob = new window.Blob([src], { type: 'text/javascript' })
if (options.bare) { return blob }
var URL = window.URL || window.webkitURL || window.mozURL || window.msURL
var workerUrl = URL.createObjectURL(blob)
var worker = new window.Worker(workerUrl)
worker.objectURL = workerUrl
return worker
}
/***/ }),
/***/ "./src/config.ts":
/*!***********************!*\
!*** ./src/config.ts ***!
\***********************/
/*! exports provided: hlsDefaultConfig, mergeConfig, enableStreamingMode */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hlsDefaultConfig", function() { return hlsDefaultConfig; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mergeConfig", function() { return mergeConfig; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "enableStreamingMode", function() { return enableStreamingMode; });
/* harmony import */ var _controller_abr_controller__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./controller/abr-controller */ "./src/controller/abr-controller.ts");
/* harmony import */ var _controller_audio_stream_controller__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./controller/audio-stream-controller */ "./src/empty.js");
/* harmony import */ var _controller_audio_stream_controller__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_controller_audio_stream_controller__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _controller_buffer_controller__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./controller/buffer-controller */ "./src/controller/buffer-controller.ts");
/* harmony import */ var _controller_cap_level_controller__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./controller/cap-level-controller */ "./src/controller/cap-level-controller.ts");
/* harmony import */ var _controller_fps_controller__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./controller/fps-controller */ "./src/controller/fps-controller.ts");
/* harmony import */ var _utils_xhr_loader__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./utils/xhr-loader */ "./src/utils/xhr-loader.ts");
/* harmony import */ var _utils_fetch_loader__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./utils/fetch-loader */ "./src/utils/fetch-loader.ts");
/* harmony import */ var _utils_mediakeys_helper__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./utils/mediakeys-helper */ "./src/utils/mediakeys-helper.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./utils/logger */ "./src/utils/logger.ts");
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
// If possible, keep hlsDefaultConfig shallow
// It is cloned whenever a new Hls instance is created, by keeping the config
// shallow the properties are cloned, and we don't end up manipulating the default
var hlsDefaultConfig = _objectSpread(_objectSpread({
autoStartLoad: true,
// used by stream-controller
startPosition: -1,
// used by stream-controller
defaultAudioCodec: undefined,
// used by stream-controller
debug: false,
// used by logger
capLevelOnFPSDrop: false,
// used by fps-controller
capLevelToPlayerSize: false,
// used by cap-level-controller
initialLiveManifestSize: 1,
// used by stream-controller
maxBufferLength: 30,
// used by stream-controller
backBufferLength: Infinity,
// used by buffer-controller
maxBufferSize: 60 * 1000 * 1000,
// used by stream-controller
maxBufferHole: 0.1,
// used by stream-controller
highBufferWatchdogPeriod: 2,
// used by stream-controller
nudgeOffset: 0.1,
// used by stream-controller
nudgeMaxRetry: 3,
// used by stream-controller
maxFragLookUpTolerance: 0.25,
// used by stream-controller
liveSyncDurationCount: 3,
// used by latency-controller
liveMaxLatencyDurationCount: Infinity,
// used by latency-controller
liveSyncDuration: undefined,
// used by latency-controller
liveMaxLatencyDuration: undefined,
// used by latency-controller
maxLiveSyncPlaybackRate: 1,
// used by latency-controller
liveDurationInfinity: false,
// used by buffer-controller
liveBackBufferLength: null,
// used by buffer-controller
maxMaxBufferLength: 600,
// used by stream-controller
enableWorker: true,
// used by demuxer
enableSoftwareAES: true,
// used by decrypter
manifestLoadingTimeOut: 10000,
// used by playlist-loader
manifestLoadingMaxRetry: 1,
// used by playlist-loader
manifestLoadingRetryDelay: 1000,
// used by playlist-loader
manifestLoadingMaxRetryTimeout: 64000,
// used by playlist-loader
startLevel: undefined,
// used by level-controller
levelLoadingTimeOut: 10000,
// used by playlist-loader
levelLoadingMaxRetry: 4,
// used by playlist-loader
levelLoadingRetryDelay: 1000,
// used by playlist-loader
levelLoadingMaxRetryTimeout: 64000,
// used by playlist-loader
fragLoadingTimeOut: 20000,
// used by fragment-loader
fragLoadingMaxRetry: 6,
// used by fragment-loader
fragLoadingRetryDelay: 1000,
// used by fragment-loader
fragLoadingMaxRetryTimeout: 64000,
// used by fragment-loader
startFragPrefetch: false,
// used by stream-controller
fpsDroppedMonitoringPeriod: 5000,
// used by fps-controller
fpsDroppedMonitoringThreshold: 0.2,
// used by fps-controller
appendErrorMaxRetry: 3,
// used by buffer-controller
loader: _utils_xhr_loader__WEBPACK_IMPORTED_MODULE_5__["default"],
// loader: FetchLoader,
fLoader: undefined,
// used by fragment-loader
pLoader: undefined,
// used by playlist-loader
xhrSetup: undefined,
// used by xhr-loader
licenseXhrSetup: undefined,
// used by eme-controller
licenseResponseCallback: undefined,
// used by eme-controller
abrController: _controller_abr_controller__WEBPACK_IMPORTED_MODULE_0__["default"],
bufferController: _controller_buffer_controller__WEBPACK_IMPORTED_MODULE_2__["default"],
capLevelController: _controller_cap_level_controller__WEBPACK_IMPORTED_MODULE_3__["default"],
fpsController: _controller_fps_controller__WEBPACK_IMPORTED_MODULE_4__["default"],
stretchShortVideoTrack: false,
// used by mp4-remuxer
maxAudioFramesDrift: 1,
// used by mp4-remuxer
forceKeyFrameOnDiscontinuity: true,
// used by ts-demuxer
abrEwmaFastLive: 3,
// used by abr-controller
abrEwmaSlowLive: 9,
// used by abr-controller
abrEwmaFastVoD: 3,
// used by abr-controller
abrEwmaSlowVoD: 9,
// used by abr-controller
abrEwmaDefaultEstimate: 5e5,
// 500 kbps // used by abr-controller
abrBandWidthFactor: 0.95,
// used by abr-controller
abrBandWidthUpFactor: 0.7,
// used by abr-controller
abrMaxWithRealBitrate: false,
// used by abr-controller
maxStarvationDelay: 4,
// used by abr-controller
maxLoadingDelay: 4,
// used by abr-controller
minAutoBitrate: 0,
// used by hls
emeEnabled: false,
// used by eme-controller
widevineLicenseUrl: undefined,
// used by eme-controller
drmSystemOptions: {},
// used by eme-controller
requestMediaKeySystemAccessFunc: _utils_mediakeys_helper__WEBPACK_IMPORTED_MODULE_7__["requestMediaKeySystemAccess"],
// used by eme-controller
testBandwidth: true,
progressive: false,
lowLatencyMode: true,
cmcd: undefined
}, timelineConfig()), {}, {
subtitleStreamController: false ? undefined : undefined,
subtitleTrackController: false ? undefined : undefined,
timelineController: false ? undefined : undefined,
audioStreamController: false ? undefined : undefined,
audioTrackController: false ? undefined : undefined,
emeController: false ? undefined : undefined,
cmcdController: false ? undefined : undefined
});
function timelineConfig() {
return {
cueHandler: _controller_audio_stream_controller__WEBPACK_IMPORTED_MODULE_1___default.a,
// used by timeline-controller
enableCEA708Captions: false,
// used by timeline-controller
enableWebVTT: false,
// used by timeline-controller
enableIMSC1: false,
// used by timeline-controller
captionsTextTrack1Label: 'English',
// used by timeline-controller
captionsTextTrack1LanguageCode: 'en',
// used by timeline-controller
captionsTextTrack2Label: 'Spanish',
// used by timeline-controller
captionsTextTrack2LanguageCode: 'es',
// used by timeline-controller
captionsTextTrack3Label: 'Unknown CC',
// used by timeline-controller
captionsTextTrack3LanguageCode: '',
// used by timeline-controller
captionsTextTrack4Label: 'Unknown CC',
// used by timeline-controller
captionsTextTrack4LanguageCode: '',
// used by timeline-controller
renderTextTracksNatively: true
};
}
function mergeConfig(defaultConfig, userConfig) {
if ((userConfig.liveSyncDurationCount || userConfig.liveMaxLatencyDurationCount) && (userConfig.liveSyncDuration || userConfig.liveMaxLatencyDuration)) {
throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");
}
if (userConfig.liveMaxLatencyDurationCount !== undefined && (userConfig.liveSyncDurationCount === undefined || userConfig.liveMaxLatencyDurationCount <= userConfig.liveSyncDurationCount)) {
throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');
}
if (userConfig.liveMaxLatencyDuration !== undefined && (userConfig.liveSyncDuration === undefined || userConfig.liveMaxLatencyDuration <= userConfig.liveSyncDuration)) {
throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');
}
return _extends({}, defaultConfig, userConfig);
}
function enableStreamingMode(config) {
var currentLoader = config.loader;
if (currentLoader !== _utils_fetch_loader__WEBPACK_IMPORTED_MODULE_6__["default"] && currentLoader !== _utils_xhr_loader__WEBPACK_IMPORTED_MODULE_5__["default"]) {
// If a developer has configured their own loader, respect that choice
_utils_logger__WEBPACK_IMPORTED_MODULE_8__["logger"].log('[config]: Custom loader detected, cannot enable progressive streaming');
config.progressive = false;
} else {
var canStreamProgressively = Object(_utils_fetch_loader__WEBPACK_IMPORTED_MODULE_6__["fetchSupported"])();
if (canStreamProgressively) {
config.loader = _utils_fetch_loader__WEBPACK_IMPORTED_MODULE_6__["default"];
config.progressive = true;
config.enableSoftwareAES = true;
_utils_logger__WEBPACK_IMPORTED_MODULE_8__["logger"].log('[config]: Progressive streaming enabled, using FetchLoader');
}
}
}
/***/ }),
/***/ "./src/controller/abr-controller.ts":
/*!******************************************!*\
!*** ./src/controller/abr-controller.ts ***!
\******************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var _utils_ewma_bandwidth_estimator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/ewma-bandwidth-estimator */ "./src/utils/ewma-bandwidth-estimator.ts");
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/buffer-helper */ "./src/utils/buffer-helper.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
/* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
var AbrController = /*#__PURE__*/function () {
function AbrController(hls) {
this.hls = void 0;
this.lastLoadedFragLevel = 0;
this._nextAutoLevel = -1;
this.timer = void 0;
this.onCheck = this._abandonRulesCheck.bind(this);
this.fragCurrent = null;
this.partCurrent = null;
this.bitrateTestDelay = 0;
this.bwEstimator = void 0;
this.hls = hls;
var config = hls.config;
this.bwEstimator = new _utils_ewma_bandwidth_estimator__WEBPACK_IMPORTED_MODULE_1__["default"](config.abrEwmaSlowVoD, config.abrEwmaFastVoD, config.abrEwmaDefaultEstimate);
this.registerListeners();
}
var _proto = AbrController.prototype;
_proto.registerListeners = function registerListeners() {
var hls = this.hls;
hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_LOADING, this.onFragLoading, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_LOADED, this.onFragLoaded, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_BUFFERED, this.onFragBuffered, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].LEVEL_LOADED, this.onLevelLoaded, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].ERROR, this.onError, this);
};
_proto.unregisterListeners = function unregisterListeners() {
var hls = this.hls;
hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_LOADING, this.onFragLoading, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_LOADED, this.onFragLoaded, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_BUFFERED, this.onFragBuffered, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].LEVEL_LOADED, this.onLevelLoaded, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].ERROR, this.onError, this);
};
_proto.destroy = function destroy() {
this.unregisterListeners();
this.clearTimer(); // @ts-ignore
this.hls = this.onCheck = null;
this.fragCurrent = this.partCurrent = null;
};
_proto.onFragLoading = function onFragLoading(event, data) {
var frag = data.frag;
if (frag.type === _types_loader__WEBPACK_IMPORTED_MODULE_5__["PlaylistLevelType"].MAIN) {
if (!this.timer) {
var _data$part;
this.fragCurrent = frag;
this.partCurrent = (_data$part = data.part) != null ? _data$part : null;
this.timer = self.setInterval(this.onCheck, 100);
}
}
};
_proto.onLevelLoaded = function onLevelLoaded(event, data) {
var config = this.hls.config;
if (data.details.live) {
this.bwEstimator.update(config.abrEwmaSlowLive, config.abrEwmaFastLive);
} else {
this.bwEstimator.update(config.abrEwmaSlowVoD, config.abrEwmaFastVoD);
}
}
/*
This method monitors the download rate of the current fragment, and will downswitch if that fragment will not load
quickly enough to prevent underbuffering
*/
;
_proto._abandonRulesCheck = function _abandonRulesCheck() {
var frag = this.fragCurrent,
part = this.partCurrent,
hls = this.hls;
var autoLevelEnabled = hls.autoLevelEnabled,
config = hls.config,
media = hls.media;
if (!frag || !media) {
return;
}
var stats = part ? part.stats : frag.stats;
var duration = part ? part.duration : frag.duration; // If loading has been aborted and not in lowLatencyMode, stop timer and return
if (stats.aborted) {
_utils_logger__WEBPACK_IMPORTED_MODULE_6__["logger"].warn('frag loader destroy or aborted, disarm abandonRules');
this.clearTimer(); // reset forced auto level value so that next level will be selected
this._nextAutoLevel = -1;
return;
} // This check only runs if we're in ABR mode and actually playing
if (!autoLevelEnabled || media.paused || !media.playbackRate || !media.readyState) {
return;
}
var requestDelay = performance.now() - stats.loading.start;
var playbackRate = Math.abs(media.playbackRate); // In order to work with a stable bandwidth, only begin monitoring bandwidth after half of the fragment has been loaded
if (requestDelay <= 500 * duration / playbackRate) {
return;
}
var levels = hls.levels,
minAutoLevel = hls.minAutoLevel;
var level = levels[frag.level];
var expectedLen = stats.total || Math.max(stats.loaded, Math.round(duration * level.maxBitrate / 8));
var loadRate = Math.max(1, stats.bwEstimate ? stats.bwEstimate / 8 : stats.loaded * 1000 / requestDelay); // fragLoadDelay is an estimate of the time (in seconds) it will take to buffer the entire fragment
var fragLoadedDelay = (expectedLen - stats.loaded) / loadRate;
var pos = media.currentTime; // bufferStarvationDelay is an estimate of the amount time (in seconds) it will take to exhaust the buffer
var bufferStarvationDelay = (_utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].bufferInfo(media, pos, config.maxBufferHole).end - pos) / playbackRate; // Attempt an emergency downswitch only if less than 2 fragment lengths are buffered, and the time to finish loading
// the current fragment is greater than the amount of buffer we have left
if (bufferStarvationDelay >= 2 * duration / playbackRate || fragLoadedDelay <= bufferStarvationDelay) {
return;
}
var fragLevelNextLoadedDelay = Number.POSITIVE_INFINITY;
var nextLoadLevel; // Iterate through lower level and try to find the largest one that avoids rebuffering
for (nextLoadLevel = frag.level - 1; nextLoadLevel > minAutoLevel; nextLoadLevel--) {
// compute time to load next fragment at lower level
// 0.8 : consider only 80% of current bw to be conservative
// 8 = bits per byte (bps/Bps)
var levelNextBitrate = levels[nextLoadLevel].maxBitrate;
fragLevelNextLoadedDelay = duration * levelNextBitrate / (8 * 0.8 * loadRate);
if (fragLevelNextLoadedDelay < bufferStarvationDelay) {
break;
}
} // Only emergency switch down if it takes less time to load a new fragment at lowest level instead of continuing
// to load the current one
if (fragLevelNextLoadedDelay >= fragLoadedDelay) {
return;
}
var bwEstimate = this.bwEstimator.getEstimate();
_utils_logger__WEBPACK_IMPORTED_MODULE_6__["logger"].warn("Fragment " + frag.sn + (part ? ' part ' + part.index : '') + " of level " + frag.level + " is loading too slowly and will cause an underbuffer; aborting and switching to level " + nextLoadLevel + "\n Current BW estimate: " + (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(bwEstimate) ? (bwEstimate / 1024).toFixed(3) : 'Unknown') + " Kb/s\n Estimated load time for current fragment: " + fragLoadedDelay.toFixed(3) + " s\n Estimated load time for the next fragment: " + fragLevelNextLoadedDelay.toFixed(3) + " s\n Time to underbuffer: " + bufferStarvationDelay.toFixed(3) + " s");
hls.nextLoadLevel = nextLoadLevel;
this.bwEstimator.sample(requestDelay, stats.loaded);
this.clearTimer();
if (frag.loader) {
this.fragCurrent = this.partCurrent = null;
frag.loader.abort();
}
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_LOAD_EMERGENCY_ABORTED, {
frag: frag,
part: part,
stats: stats
});
};
_proto.onFragLoaded = function onFragLoaded(event, _ref) {
var frag = _ref.frag,
part = _ref.part;
if (frag.type === _types_loader__WEBPACK_IMPORTED_MODULE_5__["PlaylistLevelType"].MAIN && Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(frag.sn)) {
var stats = part ? part.stats : frag.stats;
var duration = part ? part.duration : frag.duration; // stop monitoring bw once frag loaded
this.clearTimer(); // store level id after successful fragment load
this.lastLoadedFragLevel = frag.level; // reset forced auto level value so that next level will be selected
this._nextAutoLevel = -1; // compute level average bitrate
if (this.hls.config.abrMaxWithRealBitrate) {
var level = this.hls.levels[frag.level];
var loadedBytes = (level.loaded ? level.loaded.bytes : 0) + stats.loaded;
var loadedDuration = (level.loaded ? level.loaded.duration : 0) + duration;
level.loaded = {
bytes: loadedBytes,
duration: loadedDuration
};
level.realBitrate = Math.round(8 * loadedBytes / loadedDuration);
}
if (frag.bitrateTest) {
var fragBufferedData = {
stats: stats,
frag: frag,
part: part,
id: frag.type
};
this.onFragBuffered(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_BUFFERED, fragBufferedData);
frag.bitrateTest = false;
}
}
};
_proto.onFragBuffered = function onFragBuffered(event, data) {
var frag = data.frag,
part = data.part;
var stats = part ? part.stats : frag.stats;
if (stats.aborted) {
return;
} // Only count non-alt-audio frags which were actually buffered in our BW calculations
if (frag.type !== _types_loader__WEBPACK_IMPORTED_MODULE_5__["PlaylistLevelType"].MAIN || frag.sn === 'initSegment') {
return;
} // Use the difference between parsing and request instead of buffering and request to compute fragLoadingProcessing;
// rationale is that buffer appending only happens once media is attached. This can happen when config.startFragPrefetch
// is used. If we used buffering in that case, our BW estimate sample will be very large.
var processingMs = stats.parsing.end - stats.loading.start;
this.bwEstimator.sample(processingMs, stats.loaded);
stats.bwEstimate = this.bwEstimator.getEstimate();
if (frag.bitrateTest) {
this.bitrateTestDelay = processingMs / 1000;
} else {
this.bitrateTestDelay = 0;
}
};
_proto.onError = function onError(event, data) {
// stop timer in case of frag loading error
switch (data.details) {
case _errors__WEBPACK_IMPORTED_MODULE_4__["ErrorDetails"].FRAG_LOAD_ERROR:
case _errors__WEBPACK_IMPORTED_MODULE_4__["ErrorDetails"].FRAG_LOAD_TIMEOUT:
this.clearTimer();
break;
default:
break;
}
};
_proto.clearTimer = function clearTimer() {
self.clearInterval(this.timer);
this.timer = undefined;
} // return next auto level
;
_proto.getNextABRAutoLevel = function getNextABRAutoLevel() {
var fragCurrent = this.fragCurrent,
partCurrent = this.partCurrent,
hls = this.hls;
var maxAutoLevel = hls.maxAutoLevel,
config = hls.config,
minAutoLevel = hls.minAutoLevel,
media = hls.media;
var currentFragDuration = partCurrent ? partCurrent.duration : fragCurrent ? fragCurrent.duration : 0;
var pos = media ? media.currentTime : 0; // playbackRate is the absolute value of the playback rate; if media.playbackRate is 0, we use 1 to load as
// if we're playing back at the normal rate.
var playbackRate = media && media.playbackRate !== 0 ? Math.abs(media.playbackRate) : 1.0;
var avgbw = this.bwEstimator ? this.bwEstimator.getEstimate() : config.abrEwmaDefaultEstimate; // bufferStarvationDelay is the wall-clock time left until the playback buffer is exhausted.
var bufferStarvationDelay = (_utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].bufferInfo(media, pos, config.maxBufferHole).end - pos) / playbackRate; // First, look to see if we can find a level matching with our avg bandwidth AND that could also guarantee no rebuffering at all
var bestLevel = this.findBestLevel(avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, config.abrBandWidthFactor, config.abrBandWidthUpFactor);
if (bestLevel >= 0) {
return bestLevel;
}
_utils_logger__WEBPACK_IMPORTED_MODULE_6__["logger"].trace((bufferStarvationDelay ? 'rebuffering expected' : 'buffer is empty') + ", finding optimal quality level"); // not possible to get rid of rebuffering ... let's try to find level that will guarantee less than maxStarvationDelay of rebuffering
// if no matching level found, logic will return 0
var maxStarvationDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxStarvationDelay) : config.maxStarvationDelay;
var bwFactor = config.abrBandWidthFactor;
var bwUpFactor = config.abrBandWidthUpFactor;
if (!bufferStarvationDelay) {
// in case buffer is empty, let's check if previous fragment was loaded to perform a bitrate test
var bitrateTestDelay = this.bitrateTestDelay;
if (bitrateTestDelay) {
// if it is the case, then we need to adjust our max starvation delay using maxLoadingDelay config value
// max video loading delay used in automatic start level selection :
// in that mode ABR controller will ensure that video loading time (ie the time to fetch the first fragment at lowest quality level +
// the time to fetch the fragment at the appropriate quality level is less than ```maxLoadingDelay``` )
// cap maxLoadingDelay and ensure it is not bigger 'than bitrate test' frag duration
var maxLoadingDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxLoadingDelay) : config.maxLoadingDelay;
maxStarvationDelay = maxLoadingDelay - bitrateTestDelay;
_utils_logger__WEBPACK_IMPORTED_MODULE_6__["logger"].trace("bitrate test took " + Math.round(1000 * bitrateTestDelay) + "ms, set first fragment max fetchDuration to " + Math.round(1000 * maxStarvationDelay) + " ms"); // don't use conservative factor on bitrate test
bwFactor = bwUpFactor = 1;
}
}
bestLevel = this.findBestLevel(avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay + maxStarvationDelay, bwFactor, bwUpFactor);
return Math.max(bestLevel, 0);
};
_proto.findBestLevel = function findBestLevel(currentBw, minAutoLevel, maxAutoLevel, maxFetchDuration, bwFactor, bwUpFactor) {
var _level$details;
var fragCurrent = this.fragCurrent,
partCurrent = this.partCurrent,
currentLevel = this.lastLoadedFragLevel;
var levels = this.hls.levels;
var level = levels[currentLevel];
var live = !!(level !== null && level !== void 0 && (_level$details = level.details) !== null && _level$details !== void 0 && _level$details.live);
var currentCodecSet = level === null || level === void 0 ? void 0 : level.codecSet;
var currentFragDuration = partCurrent ? partCurrent.duration : fragCurrent ? fragCurrent.duration : 0;
for (var i = maxAutoLevel; i >= minAutoLevel; i--) {
var levelInfo = levels[i];
if (!levelInfo || currentCodecSet && levelInfo.codecSet !== currentCodecSet) {
continue;
}
var levelDetails = levelInfo.details;
var avgDuration = (partCurrent ? levelDetails === null || levelDetails === void 0 ? void 0 : levelDetails.partTarget : levelDetails === null || levelDetails === void 0 ? void 0 : levelDetails.averagetargetduration) || currentFragDuration;
var adjustedbw = void 0; // follow algorithm captured from stagefright :
// https://android.googlesource.com/platform/frameworks/av/+/master/media/libstagefright/httplive/LiveSession.cpp
// Pick the highest bandwidth stream below or equal to estimated bandwidth.
// consider only 80% of the available bandwidth, but if we are switching up,
// be even more conservative (70%) to avoid overestimating and immediately
// switching back.
if (i <= currentLevel) {
adjustedbw = bwFactor * currentBw;
} else {
adjustedbw = bwUpFactor * currentBw;
}
var bitrate = levels[i].maxBitrate;
var fetchDuration = bitrate * avgDuration / adjustedbw;
_utils_logger__WEBPACK_IMPORTED_MODULE_6__["logger"].trace("level/adjustedbw/bitrate/avgDuration/maxFetchDuration/fetchDuration: " + i + "/" + Math.round(adjustedbw) + "/" + bitrate + "/" + avgDuration + "/" + maxFetchDuration + "/" + fetchDuration); // if adjusted bw is greater than level bitrate AND
if (adjustedbw > bitrate && ( // fragment fetchDuration unknown OR live stream OR fragment fetchDuration less than max allowed fetch duration, then this level matches
// we don't account for max Fetch Duration for live streams, this is to avoid switching down when near the edge of live sliding window ...
// special case to support startLevel = -1 (bitrateTest) on live streams : in that case we should not exit loop so that findBestLevel will return -1
!fetchDuration || live && !this.bitrateTestDelay || fetchDuration < maxFetchDuration)) {
// as we are looping from highest to lowest, this will return the best achievable quality level
return i;
}
} // not enough time budget even with quality level 0 ... rebuffering might happen
return -1;
};
_createClass(AbrController, [{
key: "nextAutoLevel",
get: function get() {
var forcedAutoLevel = this._nextAutoLevel;
var bwEstimator = this.bwEstimator; // in case next auto level has been forced, and bw not available or not reliable, return forced value
if (forcedAutoLevel !== -1 && (!bwEstimator || !bwEstimator.canEstimate())) {
return forcedAutoLevel;
} // compute next level using ABR logic
var nextABRAutoLevel = this.getNextABRAutoLevel(); // if forced auto level has been defined, use it to cap ABR computed quality level
if (forcedAutoLevel !== -1) {
nextABRAutoLevel = Math.min(forcedAutoLevel, nextABRAutoLevel);
}
return nextABRAutoLevel;
},
set: function set(nextLevel) {
this._nextAutoLevel = nextLevel;
}
}]);
return AbrController;
}();
/* harmony default export */ __webpack_exports__["default"] = (AbrController);
/***/ }),
/***/ "./src/controller/base-playlist-controller.ts":
/*!****************************************************!*\
!*** ./src/controller/base-playlist-controller.ts ***!
\****************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return BasePlaylistController; });
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var _types_level__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../types/level */ "./src/types/level.ts");
/* harmony import */ var _level_helper__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./level-helper */ "./src/controller/level-helper.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
var BasePlaylistController = /*#__PURE__*/function () {
function BasePlaylistController(hls, logPrefix) {
this.hls = void 0;
this.timer = -1;
this.canLoad = false;
this.retryCount = 0;
this.log = void 0;
this.warn = void 0;
this.log = _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].log.bind(_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"], logPrefix + ":");
this.warn = _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn.bind(_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"], logPrefix + ":");
this.hls = hls;
}
var _proto = BasePlaylistController.prototype;
_proto.destroy = function destroy() {
this.clearTimer(); // @ts-ignore
this.hls = this.log = this.warn = null;
};
_proto.onError = function onError(event, data) {
if (data.fatal && data.type === _errors__WEBPACK_IMPORTED_MODULE_4__["ErrorTypes"].NETWORK_ERROR) {
this.clearTimer();
}
};
_proto.clearTimer = function clearTimer() {
clearTimeout(this.timer);
this.timer = -1;
};
_proto.startLoad = function startLoad() {
this.canLoad = true;
this.retryCount = 0;
this.loadPlaylist();
};
_proto.stopLoad = function stopLoad() {
this.canLoad = false;
this.clearTimer();
};
_proto.switchParams = function switchParams(playlistUri, previous) {
var renditionReports = previous === null || previous === void 0 ? void 0 : previous.renditionReports;
if (renditionReports) {
for (var i = 0; i < renditionReports.length; i++) {
var attr = renditionReports[i];
var uri = '' + attr.URI;
if (uri === playlistUri.substr(-uri.length)) {
var msn = parseInt(attr['LAST-MSN']);
var part = parseInt(attr['LAST-PART']);
if (previous && this.hls.config.lowLatencyMode) {
var currentGoal = Math.min(previous.age - previous.partTarget, previous.targetduration);
if (part !== undefined && currentGoal > previous.partTarget) {
part += 1;
}
}
if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(msn)) {
return new _types_level__WEBPACK_IMPORTED_MODULE_1__["HlsUrlParameters"](msn, Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(part) ? part : undefined, _types_level__WEBPACK_IMPORTED_MODULE_1__["HlsSkip"].No);
}
}
}
}
};
_proto.loadPlaylist = function loadPlaylist(hlsUrlParameters) {};
_proto.shouldLoadTrack = function shouldLoadTrack(track) {
return this.canLoad && track && !!track.url && (!track.details || track.details.live);
};
_proto.playlistLoaded = function playlistLoaded(index, data, previousDetails) {
var _this = this;
var details = data.details,
stats = data.stats; // Set last updated date-time
var elapsed = stats.loading.end ? Math.max(0, self.performance.now() - stats.loading.end) : 0;
details.advancedDateTime = Date.now() - elapsed; // if current playlist is a live playlist, arm a timer to reload it
if (details.live || previousDetails !== null && previousDetails !== void 0 && previousDetails.live) {
details.reloaded(previousDetails);
if (previousDetails) {
this.log("live playlist " + index + " " + (details.advanced ? 'REFRESHED ' + details.lastPartSn + '-' + details.lastPartIndex : 'MISSED'));
} // Merge live playlists to adjust fragment starts and fill in delta playlist skipped segments
if (previousDetails && details.fragments.length > 0) {
Object(_level_helper__WEBPACK_IMPORTED_MODULE_2__["mergeDetails"])(previousDetails, details);
}
if (!this.canLoad || !details.live) {
return;
}
var deliveryDirectives;
var msn = undefined;
var part = undefined;
if (details.canBlockReload && details.endSN && details.advanced) {
// Load level with LL-HLS delivery directives
var lowLatencyMode = this.hls.config.lowLatencyMode;
var lastPartSn = details.lastPartSn;
var endSn = details.endSN;
var lastPartIndex = details.lastPartIndex;
var hasParts = lastPartIndex !== -1;
var lastPart = lastPartSn === endSn; // When low latency mode is disabled, we'll skip part requests once the last part index is found
var nextSnStartIndex = lowLatencyMode ? 0 : lastPartIndex;
if (hasParts) {
msn = lastPart ? endSn + 1 : lastPartSn;
part = lastPart ? nextSnStartIndex : lastPartIndex + 1;
} else {
msn = endSn + 1;
} // Low-Latency CDN Tune-in: "age" header and time since load indicates we're behind by more than one part
// Update directives to obtain the Playlist that has the estimated additional duration of media
var lastAdvanced = details.age;
var cdnAge = lastAdvanced + details.ageHeader;
var currentGoal = Math.min(cdnAge - details.partTarget, details.targetduration * 1.5);
if (currentGoal > 0) {
if (previousDetails && currentGoal > previousDetails.tuneInGoal) {
// If we attempted to get the next or latest playlist update, but currentGoal increased,
// then we either can't catchup, or the "age" header cannot be trusted.
this.warn("CDN Tune-in goal increased from: " + previousDetails.tuneInGoal + " to: " + currentGoal + " with playlist age: " + details.age);
currentGoal = 0;
} else {
var segments = Math.floor(currentGoal / details.targetduration);
msn += segments;
if (part !== undefined) {
var parts = Math.round(currentGoal % details.targetduration / details.partTarget);
part += parts;
}
this.log("CDN Tune-in age: " + details.ageHeader + "s last advanced " + lastAdvanced.toFixed(2) + "s goal: " + currentGoal + " skip sn " + segments + " to part " + part);
}
details.tuneInGoal = currentGoal;
}
deliveryDirectives = this.getDeliveryDirectives(details, data.deliveryDirectives, msn, part);
if (lowLatencyMode || !lastPart) {
this.loadPlaylist(deliveryDirectives);
return;
}
} else {
deliveryDirectives = this.getDeliveryDirectives(details, data.deliveryDirectives, msn, part);
}
var reloadInterval = Object(_level_helper__WEBPACK_IMPORTED_MODULE_2__["computeReloadInterval"])(details, stats);
if (msn !== undefined && details.canBlockReload) {
reloadInterval -= details.partTarget || 1;
}
this.log("reload live playlist " + index + " in " + Math.round(reloadInterval) + " ms");
this.timer = self.setTimeout(function () {
return _this.loadPlaylist(deliveryDirectives);
}, reloadInterval);
} else {
this.clearTimer();
}
};
_proto.getDeliveryDirectives = function getDeliveryDirectives(details, previousDeliveryDirectives, msn, part) {
var skip = Object(_types_level__WEBPACK_IMPORTED_MODULE_1__["getSkipValue"])(details, msn);
if (previousDeliveryDirectives !== null && previousDeliveryDirectives !== void 0 && previousDeliveryDirectives.skip && details.deltaUpdateFailed) {
msn = previousDeliveryDirectives.msn;
part = previousDeliveryDirectives.part;
skip = _types_level__WEBPACK_IMPORTED_MODULE_1__["HlsSkip"].No;
}
return new _types_level__WEBPACK_IMPORTED_MODULE_1__["HlsUrlParameters"](msn, part, skip);
};
_proto.retryLoadingOrFail = function retryLoadingOrFail(errorEvent) {
var _this2 = this;
var config = this.hls.config;
var retry = this.retryCount < config.levelLoadingMaxRetry;
if (retry) {
var _errorEvent$context;
this.retryCount++;
if (errorEvent.details.indexOf('LoadTimeOut') > -1 && (_errorEvent$context = errorEvent.context) !== null && _errorEvent$context !== void 0 && _errorEvent$context.deliveryDirectives) {
// The LL-HLS request already timed out so retry immediately
this.warn("retry playlist loading #" + this.retryCount + " after \"" + errorEvent.details + "\"");
this.loadPlaylist();
} else {
// exponential backoff capped to max retry timeout
var delay = Math.min(Math.pow(2, this.retryCount) * config.levelLoadingRetryDelay, config.levelLoadingMaxRetryTimeout); // Schedule level/track reload
this.timer = self.setTimeout(function () {
return _this2.loadPlaylist();
}, delay);
this.warn("retry playlist loading #" + this.retryCount + " in " + delay + " ms after \"" + errorEvent.details + "\"");
}
} else {
this.warn("cannot recover from error \"" + errorEvent.details + "\""); // stopping live reloading timer if any
this.clearTimer(); // switch error to fatal
errorEvent.fatal = true;
}
return retry;
};
return BasePlaylistController;
}();
/***/ }),
/***/ "./src/controller/base-stream-controller.ts":
/*!**************************************************!*\
!*** ./src/controller/base-stream-controller.ts ***!
\**************************************************/
/*! exports provided: State, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "State", function() { return State; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return BaseStreamController; });
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var _task_loop__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../task-loop */ "./src/task-loop.ts");
/* harmony import */ var _fragment_tracker__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./fragment-tracker */ "./src/controller/fragment-tracker.ts");
/* harmony import */ var _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/buffer-helper */ "./src/utils/buffer-helper.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
/* harmony import */ var _types_transmuxer__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../types/transmuxer */ "./src/types/transmuxer.ts");
/* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../utils/mp4-tools */ "./src/utils/mp4-tools.ts");
/* harmony import */ var _utils_discontinuities__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../utils/discontinuities */ "./src/utils/discontinuities.ts");
/* harmony import */ var _fragment_finders__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./fragment-finders */ "./src/controller/fragment-finders.ts");
/* harmony import */ var _level_helper__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./level-helper */ "./src/controller/level-helper.ts");
/* harmony import */ var _loader_fragment_loader__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../loader/fragment-loader */ "./src/loader/fragment-loader.ts");
/* harmony import */ var _crypt_decrypter__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../crypt/decrypter */ "./src/crypt/decrypter.ts");
/* harmony import */ var _utils_time_ranges__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../utils/time-ranges */ "./src/utils/time-ranges.ts");
/* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts");
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
var State = {
STOPPED: 'STOPPED',
IDLE: 'IDLE',
KEY_LOADING: 'KEY_LOADING',
FRAG_LOADING: 'FRAG_LOADING',
FRAG_LOADING_WAITING_RETRY: 'FRAG_LOADING_WAITING_RETRY',
WAITING_TRACK: 'WAITING_TRACK',
PARSING: 'PARSING',
PARSED: 'PARSED',
BACKTRACKING: 'BACKTRACKING',
ENDED: 'ENDED',
ERROR: 'ERROR',
WAITING_INIT_PTS: 'WAITING_INIT_PTS',
WAITING_LEVEL: 'WAITING_LEVEL'
};
var BaseStreamController = /*#__PURE__*/function (_TaskLoop) {
_inheritsLoose(BaseStreamController, _TaskLoop);
function BaseStreamController(hls, fragmentTracker, logPrefix) {
var _this;
_this = _TaskLoop.call(this) || this;
_this.hls = void 0;
_this.fragPrevious = null;
_this.fragCurrent = null;
_this.fragmentTracker = void 0;
_this.transmuxer = null;
_this._state = State.STOPPED;
_this.media = void 0;
_this.mediaBuffer = void 0;
_this.config = void 0;
_this.bitrateTest = false;
_this.lastCurrentTime = 0;
_this.nextLoadPosition = 0;
_this.startPosition = 0;
_this.loadedmetadata = false;
_this.fragLoadError = 0;
_this.retryDate = 0;
_this.levels = null;
_this.fragmentLoader = void 0;
_this.levelLastLoaded = null;
_this.startFragRequested = false;
_this.decrypter = void 0;
_this.initPTS = [];
_this.onvseeking = null;
_this.onvended = null;
_this.logPrefix = '';
_this.log = void 0;
_this.warn = void 0;
_this.logPrefix = logPrefix;
_this.log = _utils_logger__WEBPACK_IMPORTED_MODULE_4__["logger"].log.bind(_utils_logger__WEBPACK_IMPORTED_MODULE_4__["logger"], logPrefix + ":");
_this.warn = _utils_logger__WEBPACK_IMPORTED_MODULE_4__["logger"].warn.bind(_utils_logger__WEBPACK_IMPORTED_MODULE_4__["logger"], logPrefix + ":");
_this.hls = hls;
_this.fragmentLoader = new _loader_fragment_loader__WEBPACK_IMPORTED_MODULE_12__["default"](hls.config);
_this.fragmentTracker = fragmentTracker;
_this.config = hls.config;
_this.decrypter = new _crypt_decrypter__WEBPACK_IMPORTED_MODULE_13__["default"](hls, hls.config);
hls.on(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].KEY_LOADED, _this.onKeyLoaded, _assertThisInitialized(_this));
return _this;
}
var _proto = BaseStreamController.prototype;
_proto.doTick = function doTick() {
this.onTickEnd();
};
_proto.onTickEnd = function onTickEnd() {} // eslint-disable-next-line @typescript-eslint/no-unused-vars
;
_proto.startLoad = function startLoad(startPosition) {};
_proto.stopLoad = function stopLoad() {
this.fragmentLoader.abort();
var frag = this.fragCurrent;
if (frag) {
this.fragmentTracker.removeFragment(frag);
}
this.resetTransmuxer();
this.fragCurrent = null;
this.fragPrevious = null;
this.clearInterval();
this.clearNextTick();
this.state = State.STOPPED;
};
_proto._streamEnded = function _streamEnded(bufferInfo, levelDetails) {
var fragCurrent = this.fragCurrent,
fragmentTracker = this.fragmentTracker; // we just got done loading the final fragment and there is no other buffered range after ...
// rationale is that in case there are any buffered ranges after, it means that there are unbuffered portion in between
// so we should not switch to ENDED in that case, to be able to buffer them
if (!levelDetails.live && fragCurrent && fragCurrent.sn === levelDetails.endSN && !bufferInfo.nextStart) {
var fragState = fragmentTracker.getState(fragCurrent);
return fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_2__["FragmentState"].PARTIAL || fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_2__["FragmentState"].OK;
}
return false;
};
_proto.onMediaAttached = function onMediaAttached(event, data) {
var media = this.media = this.mediaBuffer = data.media;
this.onvseeking = this.onMediaSeeking.bind(this);
this.onvended = this.onMediaEnded.bind(this);
media.addEventListener('seeking', this.onvseeking);
media.addEventListener('ended', this.onvended);
var config = this.config;
if (this.levels && config.autoStartLoad && this.state === State.STOPPED) {
this.startLoad(config.startPosition);
}
};
_proto.onMediaDetaching = function onMediaDetaching() {
var media = this.media;
if (media !== null && media !== void 0 && media.ended) {
this.log('MSE detaching and video ended, reset startPosition');
this.startPosition = this.lastCurrentTime = 0;
} // remove video listeners
if (media) {
media.removeEventListener('seeking', this.onvseeking);
media.removeEventListener('ended', this.onvended);
this.onvseeking = this.onvended = null;
}
this.media = this.mediaBuffer = null;
this.loadedmetadata = false;
this.fragmentTracker.removeAllFragments();
this.stopLoad();
};
_proto.onMediaSeeking = function onMediaSeeking() {
var config = this.config,
fragCurrent = this.fragCurrent,
media = this.media,
mediaBuffer = this.mediaBuffer,
state = this.state;
var currentTime = media ? media.currentTime : 0;
var bufferInfo = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].bufferInfo(mediaBuffer || media, currentTime, config.maxBufferHole);
this.log("media seeking to " + (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(currentTime) ? currentTime.toFixed(3) : currentTime) + ", state: " + state);
if (state === State.ENDED) {
this.resetLoadingState();
} else if (fragCurrent && !bufferInfo.len) {
// check if we are seeking to a unbuffered area AND if frag loading is in progress
var tolerance = config.maxFragLookUpTolerance;
var fragStartOffset = fragCurrent.start - tolerance;
var fragEndOffset = fragCurrent.start + fragCurrent.duration + tolerance;
var pastFragment = currentTime > fragEndOffset; // check if the seek position is past current fragment, and if so abort loading
if (currentTime < fragStartOffset || pastFragment) {
if (pastFragment && fragCurrent.loader) {
this.log('seeking outside of buffer while fragment load in progress, cancel fragment load');
fragCurrent.loader.abort();
}
this.resetLoadingState();
}
}
if (media) {
this.lastCurrentTime = currentTime;
} // in case seeking occurs although no media buffered, adjust startPosition and nextLoadPosition to seek target
if (!this.loadedmetadata && !bufferInfo.len) {
this.nextLoadPosition = this.startPosition = currentTime;
} // Async tick to speed up processing
this.tickImmediate();
};
_proto.onMediaEnded = function onMediaEnded() {
// reset startPosition and lastCurrentTime to restart playback @ stream beginning
this.startPosition = this.lastCurrentTime = 0;
};
_proto.onKeyLoaded = function onKeyLoaded(event, data) {
if (this.state !== State.KEY_LOADING || data.frag !== this.fragCurrent || !this.levels) {
return;
}
this.state = State.IDLE;
var levelDetails = this.levels[data.frag.level].details;
if (levelDetails) {
this.loadFragment(data.frag, levelDetails, data.frag.start);
}
};
_proto.onHandlerDestroying = function onHandlerDestroying() {
this.stopLoad();
_TaskLoop.prototype.onHandlerDestroying.call(this);
};
_proto.onHandlerDestroyed = function onHandlerDestroyed() {
this.state = State.STOPPED;
this.hls.off(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].KEY_LOADED, this.onKeyLoaded, this);
if (this.fragmentLoader) {
this.fragmentLoader.destroy();
}
if (this.decrypter) {
this.decrypter.destroy();
}
this.hls = this.log = this.warn = this.decrypter = this.fragmentLoader = this.fragmentTracker = null;
_TaskLoop.prototype.onHandlerDestroyed.call(this);
};
_proto.loadKey = function loadKey(frag, details) {
this.log("Loading key for " + frag.sn + " of [" + details.startSN + "-" + details.endSN + "], " + (this.logPrefix === '[stream-controller]' ? 'level' : 'track') + " " + frag.level);
this.state = State.KEY_LOADING;
this.fragCurrent = frag;
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].KEY_LOADING, {
frag: frag
});
};
_proto.loadFragment = function loadFragment(frag, levelDetails, targetBufferTime) {
this._loadFragForPlayback(frag, levelDetails, targetBufferTime);
};
_proto._loadFragForPlayback = function _loadFragForPlayback(frag, levelDetails, targetBufferTime) {
var _this2 = this;
var progressCallback = function progressCallback(data) {
if (_this2.fragContextChanged(frag)) {
_this2.warn("Fragment " + frag.sn + (data.part ? ' p: ' + data.part.index : '') + " of level " + frag.level + " was dropped during download.");
_this2.fragmentTracker.removeFragment(frag);
return;
}
frag.stats.chunkCount++;
_this2._handleFragmentLoadProgress(data);
};
this._doFragLoad(frag, levelDetails, targetBufferTime, progressCallback).then(function (data) {
if (!data) {
// if we're here we probably needed to backtrack or are waiting for more parts
return;
}
_this2.fragLoadError = 0;
var state = _this2.state;
if (_this2.fragContextChanged(frag)) {
if (state === State.FRAG_LOADING || state === State.BACKTRACKING || !_this2.fragCurrent && state === State.PARSING) {
_this2.fragmentTracker.removeFragment(frag);
_this2.state = State.IDLE;
}
return;
}
if ('payload' in data) {
_this2.log("Loaded fragment " + frag.sn + " of level " + frag.level);
_this2.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].FRAG_LOADED, data); // Tracker backtrack must be called after onFragLoaded to update the fragment entity state to BACKTRACKED
// This happens after handleTransmuxComplete when the worker or progressive is disabled
if (_this2.state === State.BACKTRACKING) {
_this2.fragmentTracker.backtrack(frag, data);
_this2.resetFragmentLoading(frag);
return;
}
} // Pass through the whole payload; controllers not implementing progressive loading receive data from this callback
_this2._handleFragmentLoadComplete(data);
}).catch(function (reason) {
_this2.warn(reason);
_this2.resetFragmentLoading(frag);
});
};
_proto.flushMainBuffer = function flushMainBuffer(startOffset, endOffset, type) {
if (type === void 0) {
type = null;
}
if (!(startOffset - endOffset)) {
return;
} // When alternate audio is playing, the audio-stream-controller is responsible for the audio buffer. Otherwise,
// passing a null type flushes both buffers
var flushScope = {
startOffset: startOffset,
endOffset: endOffset,
type: type
}; // Reset load errors on flush
this.fragLoadError = 0;
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].BUFFER_FLUSHING, flushScope);
};
_proto._loadInitSegment = function _loadInitSegment(frag) {
var _this3 = this;
this._doFragLoad(frag).then(function (data) {
if (!data || _this3.fragContextChanged(frag) || !_this3.levels) {
throw new Error('init load aborted');
}
return data;
}).then(function (data) {
var hls = _this3.hls;
var payload = data.payload;
var decryptData = frag.decryptdata; // check to see if the payload needs to be decrypted
if (payload && payload.byteLength > 0 && decryptData && decryptData.key && decryptData.iv && decryptData.method === 'AES-128') {
var startTime = self.performance.now(); // decrypt the subtitles
return _this3.decrypter.webCryptoDecrypt(new Uint8Array(payload), decryptData.key.buffer, decryptData.iv.buffer).then(function (decryptedData) {
var endTime = self.performance.now();
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].FRAG_DECRYPTED, {
frag: frag,
payload: decryptedData,
stats: {
tstart: startTime,
tdecrypt: endTime
}
});
data.payload = decryptedData;
return data;
});
}
return data;
}).then(function (data) {
var fragCurrent = _this3.fragCurrent,
hls = _this3.hls,
levels = _this3.levels;
if (!levels) {
throw new Error('init load aborted, missing levels');
}
var details = levels[frag.level].details;
console.assert(details, 'Level details are defined when init segment is loaded');
var stats = frag.stats;
_this3.state = State.IDLE;
_this3.fragLoadError = 0;
frag.data = new Uint8Array(data.payload);
stats.parsing.start = stats.buffering.start = self.performance.now();
stats.parsing.end = stats.buffering.end = self.performance.now(); // Silence FRAG_BUFFERED event if fragCurrent is null
if (data.frag === fragCurrent) {
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].FRAG_BUFFERED, {
stats: stats,
frag: fragCurrent,
part: null,
id: frag.type
});
}
_this3.tick();
}).catch(function (reason) {
_this3.warn(reason);
_this3.resetFragmentLoading(frag);
});
};
_proto.fragContextChanged = function fragContextChanged(frag) {
var fragCurrent = this.fragCurrent;
return !frag || !fragCurrent || frag.level !== fragCurrent.level || frag.sn !== fragCurrent.sn || frag.urlId !== fragCurrent.urlId;
};
_proto.fragBufferedComplete = function fragBufferedComplete(frag, part) {
var media = this.mediaBuffer ? this.mediaBuffer : this.media;
this.log("Buffered " + frag.type + " sn: " + frag.sn + (part ? ' part: ' + part.index : '') + " of " + (this.logPrefix === '[stream-controller]' ? 'level' : 'track') + " " + frag.level + " " + _utils_time_ranges__WEBPACK_IMPORTED_MODULE_14__["default"].toString(_utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].getBuffered(media)));
this.state = State.IDLE;
this.tick();
};
_proto._handleFragmentLoadComplete = function _handleFragmentLoadComplete(fragLoadedEndData) {
var transmuxer = this.transmuxer;
if (!transmuxer) {
return;
}
var frag = fragLoadedEndData.frag,
part = fragLoadedEndData.part,
partsLoaded = fragLoadedEndData.partsLoaded; // If we did not load parts, or loaded all parts, we have complete (not partial) fragment data
var complete = !partsLoaded || partsLoaded.length === 0 || partsLoaded.some(function (fragLoaded) {
return !fragLoaded;
});
var chunkMeta = new _types_transmuxer__WEBPACK_IMPORTED_MODULE_7__["ChunkMetadata"](frag.level, frag.sn, frag.stats.chunkCount + 1, 0, part ? part.index : -1, !complete);
transmuxer.flush(chunkMeta);
} // eslint-disable-next-line @typescript-eslint/no-unused-vars
;
_proto._handleFragmentLoadProgress = function _handleFragmentLoadProgress(frag) {};
_proto._doFragLoad = function _doFragLoad(frag, details, targetBufferTime, progressCallback) {
var _this4 = this;
if (targetBufferTime === void 0) {
targetBufferTime = null;
}
if (!this.levels) {
throw new Error('frag load aborted, missing levels');
}
targetBufferTime = Math.max(frag.start, targetBufferTime || 0);
if (this.config.lowLatencyMode && details) {
var partList = details.partList;
if (partList && progressCallback) {
if (targetBufferTime > frag.end && details.fragmentHint) {
frag = details.fragmentHint;
}
var partIndex = this.getNextPart(partList, frag, targetBufferTime);
if (partIndex > -1) {
var part = partList[partIndex];
this.log("Loading part sn: " + frag.sn + " p: " + part.index + " cc: " + frag.cc + " of playlist [" + details.startSN + "-" + details.endSN + "] parts [0-" + partIndex + "-" + (partList.length - 1) + "] " + (this.logPrefix === '[stream-controller]' ? 'level' : 'track') + ": " + frag.level + ", target: " + parseFloat(targetBufferTime.toFixed(3)));
this.nextLoadPosition = part.start + part.duration;
this.state = State.FRAG_LOADING;
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].FRAG_LOADING, {
frag: frag,
part: partList[partIndex],
targetBufferTime: targetBufferTime
});
return this.doFragPartsLoad(frag, partList, partIndex, progressCallback).catch(function (error) {
return _this4.handleFragLoadError(error);
});
} else if (!frag.url || this.loadedEndOfParts(partList, targetBufferTime)) {
// Fragment hint has no parts
return Promise.resolve(null);
}
}
}
this.log("Loading fragment " + frag.sn + " cc: " + frag.cc + " " + (details ? 'of [' + details.startSN + '-' + details.endSN + '] ' : '') + (this.logPrefix === '[stream-controller]' ? 'level' : 'track') + ": " + frag.level + ", target: " + parseFloat(targetBufferTime.toFixed(3))); // Don't update nextLoadPosition for fragments which are not buffered
if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(frag.sn) && !this.bitrateTest) {
this.nextLoadPosition = frag.start + frag.duration;
}
this.state = State.FRAG_LOADING;
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].FRAG_LOADING, {
frag: frag,
targetBufferTime: targetBufferTime
});
return this.fragmentLoader.load(frag, progressCallback).catch(function (error) {
return _this4.handleFragLoadError(error);
});
};
_proto.doFragPartsLoad = function doFragPartsLoad(frag, partList, partIndex, progressCallback) {
var _this5 = this;
return new Promise(function (resolve, reject) {
var partsLoaded = [];
var loadPartIndex = function loadPartIndex(index) {
var part = partList[index];
_this5.fragmentLoader.loadPart(frag, part, progressCallback).then(function (partLoadedData) {
partsLoaded[part.index] = partLoadedData;
var loadedPart = partLoadedData.part;
_this5.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].FRAG_LOADED, partLoadedData);
var nextPart = partList[index + 1];
if (nextPart && nextPart.fragment === frag) {
loadPartIndex(index + 1);
} else {
return resolve({
frag: frag,
part: loadedPart,
partsLoaded: partsLoaded
});
}
}).catch(reject);
};
loadPartIndex(partIndex);
});
};
_proto.handleFragLoadError = function handleFragLoadError(_ref) {
var data = _ref.data;
if (data && data.details === _errors__WEBPACK_IMPORTED_MODULE_6__["ErrorDetails"].INTERNAL_ABORTED) {
this.handleFragLoadAborted(data.frag, data.part);
} else {
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].ERROR, data);
}
return null;
};
_proto._handleTransmuxerFlush = function _handleTransmuxerFlush(chunkMeta) {
var context = this.getCurrentContext(chunkMeta);
if (!context || this.state !== State.PARSING) {
if (!this.fragCurrent) {
this.state = State.IDLE;
}
return;
}
var frag = context.frag,
part = context.part,
level = context.level;
var now = self.performance.now();
frag.stats.parsing.end = now;
if (part) {
part.stats.parsing.end = now;
}
this.updateLevelTiming(frag, part, level, chunkMeta.partial);
};
_proto.getCurrentContext = function getCurrentContext(chunkMeta) {
var levels = this.levels;
var levelIndex = chunkMeta.level,
sn = chunkMeta.sn,
partIndex = chunkMeta.part;
if (!levels || !levels[levelIndex]) {
this.warn("Levels object was unset while buffering fragment " + sn + " of level " + levelIndex + ". The current chunk will not be buffered.");
return null;
}
var level = levels[levelIndex];
var part = partIndex > -1 ? Object(_level_helper__WEBPACK_IMPORTED_MODULE_11__["getPartWith"])(level, sn, partIndex) : null;
var frag = part ? part.fragment : Object(_level_helper__WEBPACK_IMPORTED_MODULE_11__["getFragmentWithSN"])(level, sn, this.fragCurrent);
if (!frag) {
return null;
}
return {
frag: frag,
part: part,
level: level
};
};
_proto.bufferFragmentData = function bufferFragmentData(data, frag, part, chunkMeta) {
if (!data || this.state !== State.PARSING) {
return;
}
var data1 = data.data1,
data2 = data.data2;
var buffer = data1;
if (data1 && data2) {
// Combine the moof + mdat so that we buffer with a single append
buffer = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_8__["appendUint8Array"])(data1, data2);
}
if (!buffer || !buffer.length) {
return;
}
var segment = {
type: data.type,
frag: frag,
part: part,
chunkMeta: chunkMeta,
parent: frag.type,
data: buffer
};
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].BUFFER_APPENDING, segment);
if (data.dropped && data.independent && !part) {
// Clear buffer so that we reload previous segments sequentially if required
this.flushBufferGap(frag);
}
};
_proto.flushBufferGap = function flushBufferGap(frag) {
var media = this.media;
if (!media) {
return;
} // If currentTime is not buffered, clear the back buffer so that we can backtrack as much as needed
if (!_utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].isBuffered(media, media.currentTime)) {
this.flushMainBuffer(0, frag.start);
return;
} // Remove back-buffer without interrupting playback to allow back tracking
var currentTime = media.currentTime;
var bufferInfo = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].bufferInfo(media, currentTime, 0);
var fragDuration = frag.duration;
var segmentFraction = Math.min(this.config.maxFragLookUpTolerance * 2, fragDuration * 0.25);
var start = Math.max(Math.min(frag.start - segmentFraction, bufferInfo.end - segmentFraction), currentTime + segmentFraction);
if (frag.start - start > segmentFraction) {
this.flushMainBuffer(start, frag.start);
}
};
_proto.getFwdBufferInfo = function getFwdBufferInfo(bufferable, type) {
var config = this.config;
var pos = this.getLoadPosition();
if (!Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(pos)) {
return null;
}
var bufferInfo = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].bufferInfo(bufferable, pos, config.maxBufferHole); // Workaround flaw in getting forward buffer when maxBufferHole is smaller than gap at current pos
if (bufferInfo.len === 0 && bufferInfo.nextStart !== undefined) {
var bufferedFragAtPos = this.fragmentTracker.getBufferedFrag(pos, type);
if (bufferedFragAtPos && bufferInfo.nextStart < bufferedFragAtPos.end) {
return _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].bufferInfo(bufferable, pos, Math.max(bufferInfo.nextStart, config.maxBufferHole));
}
}
return bufferInfo;
};
_proto.getMaxBufferLength = function getMaxBufferLength(levelBitrate) {
var config = this.config;
var maxBufLen;
if (levelBitrate) {
maxBufLen = Math.max(8 * config.maxBufferSize / levelBitrate, config.maxBufferLength);
} else {
maxBufLen = config.maxBufferLength;
}
return Math.min(maxBufLen, config.maxMaxBufferLength);
};
_proto.reduceMaxBufferLength = function reduceMaxBufferLength(threshold) {
var config = this.config;
var minLength = threshold || config.maxBufferLength;
if (config.maxMaxBufferLength >= minLength) {
// reduce max buffer length as it might be too high. we do this to avoid loop flushing ...
config.maxMaxBufferLength /= 2;
this.warn("Reduce max buffer length to " + config.maxMaxBufferLength + "s");
return true;
}
return false;
};
_proto.getNextFragment = function getNextFragment(pos, levelDetails) {
var _frag, _frag2;
var fragments = levelDetails.fragments;
var fragLen = fragments.length;
if (!fragLen) {
return null;
} // find fragment index, contiguous with end of buffer position
var config = this.config;
var start = fragments[0].start;
var frag;
if (levelDetails.live) {
var initialLiveManifestSize = config.initialLiveManifestSize;
if (fragLen < initialLiveManifestSize) {
this.warn("Not enough fragments to start playback (have: " + fragLen + ", need: " + initialLiveManifestSize + ")");
return null;
} // The real fragment start times for a live stream are only known after the PTS range for that level is known.
// In order to discover the range, we load the best matching fragment for that level and demux it.
// Do not load using live logic if the starting frag is requested - we want to use getFragmentAtPosition() so that
// we get the fragment matching that start time
if (!levelDetails.PTSKnown && !this.startFragRequested && this.startPosition === -1) {
frag = this.getInitialLiveFragment(levelDetails, fragments);
this.startPosition = frag ? this.hls.liveSyncPosition || frag.start : pos;
}
} else if (pos <= start) {
// VoD playlist: if loadPosition before start of playlist, load first fragment
frag = fragments[0];
} // If we haven't run into any special cases already, just load the fragment most closely matching the requested position
if (!frag) {
var end = config.lowLatencyMode ? levelDetails.partEnd : levelDetails.fragmentEnd;
frag = this.getFragmentAtPosition(pos, end, levelDetails);
} // If an initSegment is present, it must be buffered first
if ((_frag = frag) !== null && _frag !== void 0 && _frag.initSegment && !((_frag2 = frag) !== null && _frag2 !== void 0 && _frag2.initSegment.data) && !this.bitrateTest) {
frag = frag.initSegment;
}
return frag;
};
_proto.getNextPart = function getNextPart(partList, frag, targetBufferTime) {
var nextPart = -1;
var contiguous = false;
var independentAttrOmitted = true;
for (var i = 0, len = partList.length; i < len; i++) {
var part = partList[i];
independentAttrOmitted = independentAttrOmitted && !part.independent;
if (nextPart > -1 && targetBufferTime < part.start) {
break;
}
var loaded = part.loaded;
if (!loaded && (contiguous || part.independent || independentAttrOmitted) && part.fragment === frag) {
nextPart = i;
}
contiguous = loaded;
}
return nextPart;
};
_proto.loadedEndOfParts = function loadedEndOfParts(partList, targetBufferTime) {
var lastPart = partList[partList.length - 1];
return lastPart && targetBufferTime > lastPart.start && lastPart.loaded;
}
/*
This method is used find the best matching first fragment for a live playlist. This fragment is used to calculate the
"sliding" of the playlist, which is its offset from the start of playback. After sliding we can compute the real
start and end times for each fragment in the playlist (after which this method will not need to be called).
*/
;
_proto.getInitialLiveFragment = function getInitialLiveFragment(levelDetails, fragments) {
var fragPrevious = this.fragPrevious;
var frag = null;
if (fragPrevious) {
if (levelDetails.hasProgramDateTime) {
// Prefer using PDT, because it can be accurate enough to choose the correct fragment without knowing the level sliding
this.log("Live playlist, switching playlist, load frag with same PDT: " + fragPrevious.programDateTime);
frag = Object(_fragment_finders__WEBPACK_IMPORTED_MODULE_10__["findFragmentByPDT"])(fragments, fragPrevious.endProgramDateTime, this.config.maxFragLookUpTolerance);
}
if (!frag) {
// SN does not need to be accurate between renditions, but depending on the packaging it may be so.
var targetSN = fragPrevious.sn + 1;
if (targetSN >= levelDetails.startSN && targetSN <= levelDetails.endSN) {
var fragNext = fragments[targetSN - levelDetails.startSN]; // Ensure that we're staying within the continuity range, since PTS resets upon a new range
if (fragPrevious.cc === fragNext.cc) {
frag = fragNext;
this.log("Live playlist, switching playlist, load frag with next SN: " + frag.sn);
}
} // It's important to stay within the continuity range if available; otherwise the fragments in the playlist
// will have the wrong start times
if (!frag) {
frag = Object(_fragment_finders__WEBPACK_IMPORTED_MODULE_10__["findFragWithCC"])(fragments, fragPrevious.cc);
if (frag) {
this.log("Live playlist, switching playlist, load frag with same CC: " + frag.sn);
}
}
}
} else {
// Find a new start fragment when fragPrevious is null
var liveStart = this.hls.liveSyncPosition;
if (liveStart !== null) {
frag = this.getFragmentAtPosition(liveStart, this.bitrateTest ? levelDetails.fragmentEnd : levelDetails.edge, levelDetails);
}
}
return frag;
}
/*
This method finds the best matching fragment given the provided position.
*/
;
_proto.getFragmentAtPosition = function getFragmentAtPosition(bufferEnd, end, levelDetails) {
var config = this.config,
fragPrevious = this.fragPrevious;
var fragments = levelDetails.fragments,
endSN = levelDetails.endSN;
var fragmentHint = levelDetails.fragmentHint;
var tolerance = config.maxFragLookUpTolerance;
var loadingParts = !!(config.lowLatencyMode && levelDetails.partList && fragmentHint);
if (loadingParts && fragmentHint && !this.bitrateTest) {
// Include incomplete fragment with parts at end
fragments = fragments.concat(fragmentHint);
endSN = fragmentHint.sn;
}
var frag;
if (bufferEnd < end) {
var lookupTolerance = bufferEnd > end - tolerance ? 0 : tolerance; // Remove the tolerance if it would put the bufferEnd past the actual end of stream
// Uses buffer and sequence number to calculate switch segment (required if using EXT-X-DISCONTINUITY-SEQUENCE)
frag = Object(_fragment_finders__WEBPACK_IMPORTED_MODULE_10__["findFragmentByPTS"])(fragPrevious, fragments, bufferEnd, lookupTolerance);
} else {
// reach end of playlist
frag = fragments[fragments.length - 1];
}
if (frag) {
var curSNIdx = frag.sn - levelDetails.startSN;
var sameLevel = fragPrevious && frag.level === fragPrevious.level;
var nextFrag = fragments[curSNIdx + 1];
var fragState = this.fragmentTracker.getState(frag);
if (fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_2__["FragmentState"].BACKTRACKED) {
frag = null;
var i = curSNIdx;
while (fragments[i] && this.fragmentTracker.getState(fragments[i]) === _fragment_tracker__WEBPACK_IMPORTED_MODULE_2__["FragmentState"].BACKTRACKED) {
// When fragPrevious is null, backtrack to first the first fragment is not BACKTRACKED for loading
// When fragPrevious is set, we want the first BACKTRACKED fragment for parsing and buffering
if (!fragPrevious) {
frag = fragments[--i];
} else {
frag = fragments[i--];
}
}
if (!frag) {
frag = nextFrag;
}
} else if (fragPrevious && frag.sn === fragPrevious.sn && !loadingParts) {
// Force the next fragment to load if the previous one was already selected. This can occasionally happen with
// non-uniform fragment durations
if (sameLevel) {
if (frag.sn < endSN && this.fragmentTracker.getState(nextFrag) !== _fragment_tracker__WEBPACK_IMPORTED_MODULE_2__["FragmentState"].OK) {
this.log("SN " + frag.sn + " just loaded, load next one: " + nextFrag.sn);
frag = nextFrag;
} else {
frag = null;
}
}
}
}
return frag;
};
_proto.synchronizeToLiveEdge = function synchronizeToLiveEdge(levelDetails) {
var config = this.config,
media = this.media;
if (!media) {
return;
}
var liveSyncPosition = this.hls.liveSyncPosition;
var currentTime = media.currentTime;
var start = levelDetails.fragments[0].start;
var end = levelDetails.edge;
var withinSlidingWindow = currentTime >= start - config.maxFragLookUpTolerance && currentTime <= end; // Continue if we can seek forward to sync position or if current time is outside of sliding window
if (liveSyncPosition !== null && media.duration > liveSyncPosition && (currentTime < liveSyncPosition || !withinSlidingWindow)) {
// Continue if buffer is starving or if current time is behind max latency
var maxLatency = config.liveMaxLatencyDuration !== undefined ? config.liveMaxLatencyDuration : config.liveMaxLatencyDurationCount * levelDetails.targetduration;
if (!withinSlidingWindow && media.readyState < 4 || currentTime < end - maxLatency) {
if (!this.loadedmetadata) {
this.nextLoadPosition = liveSyncPosition;
} // Only seek if ready and there is not a significant forward buffer available for playback
if (media.readyState) {
this.warn("Playback: " + currentTime.toFixed(3) + " is located too far from the end of live sliding playlist: " + end + ", reset currentTime to : " + liveSyncPosition.toFixed(3));
media.currentTime = liveSyncPosition;
}
}
}
};
_proto.alignPlaylists = function alignPlaylists(details, previousDetails) {
var levels = this.levels,
levelLastLoaded = this.levelLastLoaded,
fragPrevious = this.fragPrevious;
var lastLevel = levelLastLoaded !== null ? levels[levelLastLoaded] : null; // FIXME: If not for `shouldAlignOnDiscontinuities` requiring fragPrevious.cc,
// this could all go in level-helper mergeDetails()
var length = details.fragments.length;
if (!length) {
this.warn("No fragments in live playlist");
return 0;
}
var slidingStart = details.fragments[0].start;
var firstLevelLoad = !previousDetails;
var aligned = details.alignedSliding && Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(slidingStart);
if (firstLevelLoad || !aligned && !slidingStart) {
Object(_utils_discontinuities__WEBPACK_IMPORTED_MODULE_9__["alignStream"])(fragPrevious, lastLevel, details);
var alignedSlidingStart = details.fragments[0].start;
this.log("Live playlist sliding: " + alignedSlidingStart.toFixed(2) + " start-sn: " + (previousDetails ? previousDetails.startSN : 'na') + "->" + details.startSN + " prev-sn: " + (fragPrevious ? fragPrevious.sn : 'na') + " fragments: " + length);
return alignedSlidingStart;
}
return slidingStart;
};
_proto.waitForCdnTuneIn = function waitForCdnTuneIn(details) {
// Wait for Low-Latency CDN Tune-in to get an updated playlist
var advancePartLimit = 3;
return details.live && details.canBlockReload && details.tuneInGoal > Math.max(details.partHoldBack, details.partTarget * advancePartLimit);
};
_proto.setStartPosition = function setStartPosition(details, sliding) {
// compute start position if set to -1. use it straight away if value is defined
var startPosition = this.startPosition;
if (startPosition < sliding) {
startPosition = -1;
}
if (startPosition === -1 || this.lastCurrentTime === -1) {
// first, check if start time offset has been set in playlist, if yes, use this value
var startTimeOffset = details.startTimeOffset;
if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(startTimeOffset)) {
startPosition = sliding + startTimeOffset;
if (startTimeOffset < 0) {
startPosition += details.totalduration;
}
startPosition = Math.min(Math.max(sliding, startPosition), sliding + details.totalduration);
this.log("Start time offset " + startTimeOffset + " found in playlist, adjust startPosition to " + startPosition);
this.startPosition = startPosition;
} else if (details.live) {
// Leave this.startPosition at -1, so that we can use `getInitialLiveFragment` logic when startPosition has
// not been specified via the config or an as an argument to startLoad (#3736).
startPosition = this.hls.liveSyncPosition || sliding;
} else {
this.startPosition = startPosition = 0;
}
this.lastCurrentTime = startPosition;
}
this.nextLoadPosition = startPosition;
};
_proto.getLoadPosition = function getLoadPosition() {
var media = this.media; // if we have not yet loaded any fragment, start loading from start position
var pos = 0;
if (this.loadedmetadata && media) {
pos = media.currentTime;
} else if (this.nextLoadPosition) {
pos = this.nextLoadPosition;
}
return pos;
};
_proto.handleFragLoadAborted = function handleFragLoadAborted(frag, part) {
if (this.transmuxer && frag.sn !== 'initSegment' && frag.stats.aborted) {
this.warn("Fragment " + frag.sn + (part ? ' part' + part.index : '') + " of level " + frag.level + " was aborted");
this.resetFragmentLoading(frag);
}
};
_proto.resetFragmentLoading = function resetFragmentLoading(frag) {
if (!this.fragCurrent || !this.fragContextChanged(frag)) {
this.state = State.IDLE;
}
};
_proto.onFragmentOrKeyLoadError = function onFragmentOrKeyLoadError(filterType, data) {
if (data.fatal) {
return;
}
var frag = data.frag; // Handle frag error related to caller's filterType
if (!frag || frag.type !== filterType) {
return;
}
var fragCurrent = this.fragCurrent;
console.assert(fragCurrent && frag.sn === fragCurrent.sn && frag.level === fragCurrent.level && frag.urlId === fragCurrent.urlId, 'Frag load error must match current frag to retry');
var config = this.config; // keep retrying until the limit will be reached
if (this.fragLoadError + 1 <= config.fragLoadingMaxRetry) {
if (this.resetLiveStartWhenNotLoaded(frag.level)) {
return;
} // exponential backoff capped to config.fragLoadingMaxRetryTimeout
var delay = Math.min(Math.pow(2, this.fragLoadError) * config.fragLoadingRetryDelay, config.fragLoadingMaxRetryTimeout);
this.warn("Fragment " + frag.sn + " of " + filterType + " " + frag.level + " failed to load, retrying in " + delay + "ms");
this.retryDate = self.performance.now() + delay;
this.fragLoadError++;
this.state = State.FRAG_LOADING_WAITING_RETRY;
} else if (data.levelRetry) {
if (filterType === _types_loader__WEBPACK_IMPORTED_MODULE_15__["PlaylistLevelType"].AUDIO) {
// Reset current fragment since audio track audio is essential and may not have a fail-over track
this.fragCurrent = null;
} // Fragment errors that result in a level switch or redundant fail-over
// should reset the stream controller state to idle
this.fragLoadError = 0;
this.state = State.IDLE;
} else {
_utils_logger__WEBPACK_IMPORTED_MODULE_4__["logger"].error(data.details + " reaches max retry, redispatch as fatal ..."); // switch error to fatal
data.fatal = true;
this.hls.stopLoad();
this.state = State.ERROR;
}
};
_proto.afterBufferFlushed = function afterBufferFlushed(media, bufferType, playlistType) {
if (!media) {
return;
} // After successful buffer flushing, filter flushed fragments from bufferedFrags use mediaBuffered instead of media
// (so that we will check against video.buffered ranges in case of alt audio track)
var bufferedTimeRanges = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].getBuffered(media);
this.fragmentTracker.detectEvictedFragments(bufferType, bufferedTimeRanges, playlistType);
if (this.state === State.ENDED) {
this.resetLoadingState();
}
};
_proto.resetLoadingState = function resetLoadingState() {
this.fragCurrent = null;
this.fragPrevious = null;
this.state = State.IDLE;
};
_proto.resetLiveStartWhenNotLoaded = function resetLiveStartWhenNotLoaded(level) {
// if loadedmetadata is not set, it means that we are emergency switch down on first frag
// in that case, reset startFragRequested flag
if (!this.loadedmetadata) {
this.startFragRequested = false;
var details = this.levels ? this.levels[level].details : null;
if (details !== null && details !== void 0 && details.live) {
// We can't afford to retry after a delay in a live scenario. Update the start position and return to IDLE.
this.startPosition = -1;
this.setStartPosition(details, 0);
this.resetLoadingState();
return true;
}
this.nextLoadPosition = this.startPosition;
}
return false;
};
_proto.updateLevelTiming = function updateLevelTiming(frag, part, level, partial) {
var _this6 = this;
var details = level.details;
console.assert(!!details, 'level.details must be defined');
var parsed = Object.keys(frag.elementaryStreams).reduce(function (result, type) {
var info = frag.elementaryStreams[type];
if (info) {
var parsedDuration = info.endPTS - info.startPTS;
if (parsedDuration <= 0) {
// Destroy the transmuxer after it's next time offset failed to advance because duration was <= 0.
// The new transmuxer will be configured with a time offset matching the next fragment start,
// preventing the timeline from shifting.
_this6.warn("Could not parse fragment " + frag.sn + " " + type + " duration reliably (" + parsedDuration + ") resetting transmuxer to fallback to playlist timing");
_this6.resetTransmuxer();
return result || false;
}
var drift = partial ? 0 : Object(_level_helper__WEBPACK_IMPORTED_MODULE_11__["updateFragPTSDTS"])(details, frag, info.startPTS, info.endPTS, info.startDTS, info.endDTS);
_this6.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].LEVEL_PTS_UPDATED, {
details: details,
level: level,
drift: drift,
type: type,
frag: frag,
start: info.startPTS,
end: info.endPTS
});
return true;
}
return result;
}, false);
if (parsed) {
this.state = State.PARSED;
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].FRAG_PARSED, {
frag: frag,
part: part
});
} else {
this.resetLoadingState();
}
};
_proto.resetTransmuxer = function resetTransmuxer() {
if (this.transmuxer) {
this.transmuxer.destroy();
this.transmuxer = null;
}
};
_createClass(BaseStreamController, [{
key: "state",
get: function get() {
return this._state;
},
set: function set(nextState) {
var previousState = this._state;
if (previousState !== nextState) {
this._state = nextState;
this.log(previousState + "->" + nextState);
}
}
}]);
return BaseStreamController;
}(_task_loop__WEBPACK_IMPORTED_MODULE_1__["default"]);
/***/ }),
/***/ "./src/controller/buffer-controller.ts":
/*!*********************************************!*\
!*** ./src/controller/buffer-controller.ts ***!
\*********************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return BufferController; });
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
/* harmony import */ var _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/buffer-helper */ "./src/utils/buffer-helper.ts");
/* harmony import */ var _utils_mediasource_helper__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/mediasource-helper */ "./src/utils/mediasource-helper.ts");
/* harmony import */ var _loader_fragment__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../loader/fragment */ "./src/loader/fragment.ts");
/* harmony import */ var _buffer_operation_queue__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./buffer-operation-queue */ "./src/controller/buffer-operation-queue.ts");
var MediaSource = Object(_utils_mediasource_helper__WEBPACK_IMPORTED_MODULE_5__["getMediaSource"])();
var VIDEO_CODEC_PROFILE_REPACE = /([ha]vc.)(?:\.[^.,]+)+/;
var BufferController = /*#__PURE__*/function () {
// The level details used to determine duration, target-duration and live
// cache the self generated object url to detect hijack of video tag
// A queue of buffer operations which require the SourceBuffer to not be updating upon execution
// References to event listeners for each SourceBuffer, so that they can be referenced for event removal
// The number of BUFFER_CODEC events received before any sourceBuffers are created
// The total number of BUFFER_CODEC events received
// A reference to the attached media element
// A reference to the active media source
// counters
function BufferController(_hls) {
var _this = this;
this.details = null;
this._objectUrl = null;
this.operationQueue = void 0;
this.listeners = void 0;
this.hls = void 0;
this.bufferCodecEventsExpected = 0;
this._bufferCodecEventsTotal = 0;
this.media = null;
this.mediaSource = null;
this.appendError = 0;
this.tracks = {};
this.pendingTracks = {};
this.sourceBuffer = void 0;
this._onMediaSourceOpen = function () {
var hls = _this.hls,
media = _this.media,
mediaSource = _this.mediaSource;
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('[buffer-controller]: Media source opened');
if (media) {
_this.updateMediaElementDuration();
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_ATTACHED, {
media: media
});
}
if (mediaSource) {
// once received, don't listen anymore to sourceopen event
mediaSource.removeEventListener('sourceopen', _this._onMediaSourceOpen);
}
_this.checkPendingTracks();
};
this._onMediaSourceClose = function () {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('[buffer-controller]: Media source closed');
};
this._onMediaSourceEnded = function () {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('[buffer-controller]: Media source ended');
};
this.hls = _hls;
this._initSourceBuffer();
this.registerListeners();
}
var _proto = BufferController.prototype;
_proto.hasSourceTypes = function hasSourceTypes() {
return this.getSourceBufferTypes().length > 0 || Object.keys(this.pendingTracks).length > 0;
};
_proto.destroy = function destroy() {
this.unregisterListeners();
this.details = null;
};
_proto.registerListeners = function registerListeners() {
var hls = this.hls;
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_ATTACHING, this.onMediaAttaching, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_PARSED, this.onManifestParsed, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_RESET, this.onBufferReset, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_APPENDING, this.onBufferAppending, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_CODECS, this.onBufferCodecs, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_EOS, this.onBufferEos, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_FLUSHING, this.onBufferFlushing, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_UPDATED, this.onLevelUpdated, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_PARSED, this.onFragParsed, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_CHANGED, this.onFragChanged, this);
};
_proto.unregisterListeners = function unregisterListeners() {
var hls = this.hls;
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_ATTACHING, this.onMediaAttaching, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_PARSED, this.onManifestParsed, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_RESET, this.onBufferReset, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_APPENDING, this.onBufferAppending, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_CODECS, this.onBufferCodecs, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_EOS, this.onBufferEos, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_FLUSHING, this.onBufferFlushing, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_UPDATED, this.onLevelUpdated, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_PARSED, this.onFragParsed, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_CHANGED, this.onFragChanged, this);
};
_proto._initSourceBuffer = function _initSourceBuffer() {
this.sourceBuffer = {};
this.operationQueue = new _buffer_operation_queue__WEBPACK_IMPORTED_MODULE_7__["default"](this.sourceBuffer);
this.listeners = {
audio: [],
video: [],
audiovideo: []
};
};
_proto.onManifestParsed = function onManifestParsed(event, data) {
// in case of alt audio 2 BUFFER_CODECS events will be triggered, one per stream controller
// sourcebuffers will be created all at once when the expected nb of tracks will be reached
// in case alt audio is not used, only one BUFFER_CODEC event will be fired from main stream controller
// it will contain the expected nb of source buffers, no need to compute it
var codecEvents = 2;
if (data.audio && !data.video || !data.altAudio) {
codecEvents = 1;
}
this.bufferCodecEventsExpected = this._bufferCodecEventsTotal = codecEvents;
this.details = null;
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log(this.bufferCodecEventsExpected + " bufferCodec event(s) expected");
};
_proto.onMediaAttaching = function onMediaAttaching(event, data) {
var media = this.media = data.media;
if (media && MediaSource) {
var ms = this.mediaSource = new MediaSource(); // MediaSource listeners are arrow functions with a lexical scope, and do not need to be bound
ms.addEventListener('sourceopen', this._onMediaSourceOpen);
ms.addEventListener('sourceended', this._onMediaSourceEnded);
ms.addEventListener('sourceclose', this._onMediaSourceClose); // link video and media Source
media.src = self.URL.createObjectURL(ms); // cache the locally generated object url
this._objectUrl = media.src;
}
};
_proto.onMediaDetaching = function onMediaDetaching() {
var media = this.media,
mediaSource = this.mediaSource,
_objectUrl = this._objectUrl;
if (mediaSource) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('[buffer-controller]: media source detaching');
if (mediaSource.readyState === 'open') {
try {
// endOfStream could trigger exception if any sourcebuffer is in updating state
// we don't really care about checking sourcebuffer state here,
// as we are anyway detaching the MediaSource
// let's just avoid this exception to propagate
mediaSource.endOfStream();
} catch (err) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn("[buffer-controller]: onMediaDetaching: " + err.message + " while calling endOfStream");
}
} // Clean up the SourceBuffers by invoking onBufferReset
this.onBufferReset();
mediaSource.removeEventListener('sourceopen', this._onMediaSourceOpen);
mediaSource.removeEventListener('sourceended', this._onMediaSourceEnded);
mediaSource.removeEventListener('sourceclose', this._onMediaSourceClose); // Detach properly the MediaSource from the HTMLMediaElement as
// suggested in https://github.com/w3c/media-source/issues/53.
if (media) {
if (_objectUrl) {
self.URL.revokeObjectURL(_objectUrl);
} // clean up video tag src only if it's our own url. some external libraries might
// hijack the video tag and change its 'src' without destroying the Hls instance first
if (media.src === _objectUrl) {
media.removeAttribute('src');
media.load();
} else {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn('[buffer-controller]: media.src was changed by a third party - skip cleanup');
}
}
this.mediaSource = null;
this.media = null;
this._objectUrl = null;
this.bufferCodecEventsExpected = this._bufferCodecEventsTotal;
this.pendingTracks = {};
this.tracks = {};
}
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_DETACHED, undefined);
};
_proto.onBufferReset = function onBufferReset() {
var _this2 = this;
this.getSourceBufferTypes().forEach(function (type) {
var sb = _this2.sourceBuffer[type];
try {
if (sb) {
_this2.removeBufferListeners(type);
if (_this2.mediaSource) {
_this2.mediaSource.removeSourceBuffer(sb);
} // Synchronously remove the SB from the map before the next call in order to prevent an async function from
// accessing it
_this2.sourceBuffer[type] = undefined;
}
} catch (err) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn("[buffer-controller]: Failed to reset the " + type + " buffer", err);
}
});
this._initSourceBuffer();
};
_proto.onBufferCodecs = function onBufferCodecs(event, data) {
var _this3 = this;
var sourceBufferCount = this.getSourceBufferTypes().length;
Object.keys(data).forEach(function (trackName) {
if (sourceBufferCount) {
// check if SourceBuffer codec needs to change
var track = _this3.tracks[trackName];
if (track && typeof track.buffer.changeType === 'function') {
var _data$trackName = data[trackName],
codec = _data$trackName.codec,
levelCodec = _data$trackName.levelCodec,
container = _data$trackName.container;
var currentCodec = (track.levelCodec || track.codec).replace(VIDEO_CODEC_PROFILE_REPACE, '$1');
var nextCodec = (levelCodec || codec).replace(VIDEO_CODEC_PROFILE_REPACE, '$1');
if (currentCodec !== nextCodec) {
var mimeType = container + ";codecs=" + (levelCodec || codec);
_this3.appendChangeType(trackName, mimeType);
}
}
} else {
// if source buffer(s) not created yet, appended buffer tracks in this.pendingTracks
_this3.pendingTracks[trackName] = data[trackName];
}
}); // if sourcebuffers already created, do nothing ...
if (sourceBufferCount) {
return;
}
this.bufferCodecEventsExpected = Math.max(this.bufferCodecEventsExpected - 1, 0);
if (this.mediaSource && this.mediaSource.readyState === 'open') {
this.checkPendingTracks();
}
};
_proto.appendChangeType = function appendChangeType(type, mimeType) {
var _this4 = this;
var operationQueue = this.operationQueue;
var operation = {
execute: function execute() {
var sb = _this4.sourceBuffer[type];
if (sb) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("[buffer-controller]: changing " + type + " sourceBuffer type to " + mimeType);
sb.changeType(mimeType);
}
operationQueue.shiftAndExecuteNext(type);
},
onStart: function onStart() {},
onComplete: function onComplete() {},
onError: function onError(e) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn("[buffer-controller]: Failed to change " + type + " SourceBuffer type", e);
}
};
operationQueue.append(operation, type);
};
_proto.onBufferAppending = function onBufferAppending(event, eventData) {
var _this5 = this;
var hls = this.hls,
operationQueue = this.operationQueue,
tracks = this.tracks;
var data = eventData.data,
type = eventData.type,
frag = eventData.frag,
part = eventData.part,
chunkMeta = eventData.chunkMeta;
var chunkStats = chunkMeta.buffering[type];
var bufferAppendingStart = self.performance.now();
chunkStats.start = bufferAppendingStart;
var fragBuffering = frag.stats.buffering;
var partBuffering = part ? part.stats.buffering : null;
if (fragBuffering.start === 0) {
fragBuffering.start = bufferAppendingStart;
}
if (partBuffering && partBuffering.start === 0) {
partBuffering.start = bufferAppendingStart;
} // TODO: Only update timestampOffset when audio/mpeg fragment or part is not contiguous with previously appended
// Adjusting `SourceBuffer.timestampOffset` (desired point in the timeline where the next frames should be appended)
// in Chrome browser when we detect MPEG audio container and time delta between level PTS and `SourceBuffer.timestampOffset`
// is greater than 100ms (this is enough to handle seek for VOD or level change for LIVE videos).
// More info here: https://github.com/video-dev/hls.js/issues/332#issuecomment-257986486
var audioTrack = tracks.audio;
var checkTimestampOffset = type === 'audio' && chunkMeta.id === 1 && (audioTrack === null || audioTrack === void 0 ? void 0 : audioTrack.container) === 'audio/mpeg';
var operation = {
execute: function execute() {
chunkStats.executeStart = self.performance.now();
if (checkTimestampOffset) {
var sb = _this5.sourceBuffer[type];
if (sb) {
var delta = frag.start - sb.timestampOffset;
if (Math.abs(delta) >= 0.1) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("[buffer-controller]: Updating audio SourceBuffer timestampOffset to " + frag.start + " (delta: " + delta + ") sn: " + frag.sn + ")");
sb.timestampOffset = frag.start;
}
}
}
_this5.appendExecutor(data, type);
},
onStart: function onStart() {// logger.debug(`[buffer-controller]: ${type} SourceBuffer updatestart`);
},
onComplete: function onComplete() {
// logger.debug(`[buffer-controller]: ${type} SourceBuffer updateend`);
var end = self.performance.now();
chunkStats.executeEnd = chunkStats.end = end;
if (fragBuffering.first === 0) {
fragBuffering.first = end;
}
if (partBuffering && partBuffering.first === 0) {
partBuffering.first = end;
}
var sourceBuffer = _this5.sourceBuffer;
var timeRanges = {};
for (var _type in sourceBuffer) {
timeRanges[_type] = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__["BufferHelper"].getBuffered(sourceBuffer[_type]);
}
_this5.appendError = 0;
_this5.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_APPENDED, {
type: type,
frag: frag,
part: part,
chunkMeta: chunkMeta,
parent: frag.type,
timeRanges: timeRanges
});
},
onError: function onError(err) {
// in case any error occured while appending, put back segment in segments table
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error("[buffer-controller]: Error encountered while trying to append to the " + type + " SourceBuffer", err);
var event = {
type: _errors__WEBPACK_IMPORTED_MODULE_3__["ErrorTypes"].MEDIA_ERROR,
parent: frag.type,
details: _errors__WEBPACK_IMPORTED_MODULE_3__["ErrorDetails"].BUFFER_APPEND_ERROR,
err: err,
fatal: false
};
if (err.code === DOMException.QUOTA_EXCEEDED_ERR) {
// QuotaExceededError: http://www.w3.org/TR/html5/infrastructure.html#quotaexceedederror
// let's stop appending any segments, and report BUFFER_FULL_ERROR error
event.details = _errors__WEBPACK_IMPORTED_MODULE_3__["ErrorDetails"].BUFFER_FULL_ERROR;
} else {
_this5.appendError++;
event.details = _errors__WEBPACK_IMPORTED_MODULE_3__["ErrorDetails"].BUFFER_APPEND_ERROR;
/* with UHD content, we could get loop of quota exceeded error until
browser is able to evict some data from sourcebuffer. Retrying can help recover.
*/
if (_this5.appendError > hls.config.appendErrorMaxRetry) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error("[buffer-controller]: Failed " + hls.config.appendErrorMaxRetry + " times to append segment in sourceBuffer");
event.fatal = true;
}
}
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, event);
}
};
operationQueue.append(operation, type);
};
_proto.onBufferFlushing = function onBufferFlushing(event, data) {
var _this6 = this;
var operationQueue = this.operationQueue;
var flushOperation = function flushOperation(type) {
return {
execute: _this6.removeExecutor.bind(_this6, type, data.startOffset, data.endOffset),
onStart: function onStart() {// logger.debug(`[buffer-controller]: Started flushing ${data.startOffset} -> ${data.endOffset} for ${type} Source Buffer`);
},
onComplete: function onComplete() {
// logger.debug(`[buffer-controller]: Finished flushing ${data.startOffset} -> ${data.endOffset} for ${type} Source Buffer`);
_this6.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_FLUSHED, {
type: type
});
},
onError: function onError(e) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn("[buffer-controller]: Failed to remove from " + type + " SourceBuffer", e);
}
};
};
if (data.type) {
operationQueue.append(flushOperation(data.type), data.type);
} else {
this.getSourceBufferTypes().forEach(function (type) {
operationQueue.append(flushOperation(type), type);
});
}
};
_proto.onFragParsed = function onFragParsed(event, data) {
var _this7 = this;
var frag = data.frag,
part = data.part;
var buffersAppendedTo = [];
var elementaryStreams = part ? part.elementaryStreams : frag.elementaryStreams;
if (elementaryStreams[_loader_fragment__WEBPACK_IMPORTED_MODULE_6__["ElementaryStreamTypes"].AUDIOVIDEO]) {
buffersAppendedTo.push('audiovideo');
} else {
if (elementaryStreams[_loader_fragment__WEBPACK_IMPORTED_MODULE_6__["ElementaryStreamTypes"].AUDIO]) {
buffersAppendedTo.push('audio');
}
if (elementaryStreams[_loader_fragment__WEBPACK_IMPORTED_MODULE_6__["ElementaryStreamTypes"].VIDEO]) {
buffersAppendedTo.push('video');
}
}
var onUnblocked = function onUnblocked() {
var now = self.performance.now();
frag.stats.buffering.end = now;
if (part) {
part.stats.buffering.end = now;
}
var stats = part ? part.stats : frag.stats;
_this7.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_BUFFERED, {
frag: frag,
part: part,
stats: stats,
id: frag.type
});
};
if (buffersAppendedTo.length === 0) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn("Fragments must have at least one ElementaryStreamType set. type: " + frag.type + " level: " + frag.level + " sn: " + frag.sn);
}
this.blockBuffers(onUnblocked, buffersAppendedTo);
};
_proto.onFragChanged = function onFragChanged(event, data) {
this.flushBackBuffer();
} // on BUFFER_EOS mark matching sourcebuffer(s) as ended and trigger checkEos()
// an undefined data.type will mark all buffers as EOS.
;
_proto.onBufferEos = function onBufferEos(event, data) {
var _this8 = this;
var ended = this.getSourceBufferTypes().reduce(function (acc, type) {
var sb = _this8.sourceBuffer[type];
if (!data.type || data.type === type) {
if (sb && !sb.ended) {
sb.ended = true;
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("[buffer-controller]: " + type + " sourceBuffer now EOS");
}
}
return acc && !!(!sb || sb.ended);
}, true);
if (ended) {
this.blockBuffers(function () {
var mediaSource = _this8.mediaSource;
if (!mediaSource || mediaSource.readyState !== 'open') {
return;
} // Allow this to throw and be caught by the enqueueing function
mediaSource.endOfStream();
});
}
};
_proto.onLevelUpdated = function onLevelUpdated(event, _ref) {
var details = _ref.details;
if (!details.fragments.length) {
return;
}
this.details = details;
if (this.getSourceBufferTypes().length) {
this.blockBuffers(this.updateMediaElementDuration.bind(this));
} else {
this.updateMediaElementDuration();
}
};
_proto.flushBackBuffer = function flushBackBuffer() {
var hls = this.hls,
details = this.details,
media = this.media,
sourceBuffer = this.sourceBuffer;
if (!media || details === null) {
return;
}
var sourceBufferTypes = this.getSourceBufferTypes();
if (!sourceBufferTypes.length) {
return;
} // Support for deprecated liveBackBufferLength
var backBufferLength = details.live && hls.config.liveBackBufferLength !== null ? hls.config.liveBackBufferLength : hls.config.backBufferLength;
if (!Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(backBufferLength) || backBufferLength < 0) {
return;
}
var currentTime = media.currentTime;
var targetDuration = details.levelTargetDuration;
var maxBackBufferLength = Math.max(backBufferLength, targetDuration);
var targetBackBufferPosition = Math.floor(currentTime / targetDuration) * targetDuration - maxBackBufferLength;
sourceBufferTypes.forEach(function (type) {
var sb = sourceBuffer[type];
if (sb) {
var buffered = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__["BufferHelper"].getBuffered(sb); // when target buffer start exceeds actual buffer start
if (buffered.length > 0 && targetBackBufferPosition > buffered.start(0)) {
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BACK_BUFFER_REACHED, {
bufferEnd: targetBackBufferPosition
}); // Support for deprecated event:
if (details.live) {
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LIVE_BACK_BUFFER_REACHED, {
bufferEnd: targetBackBufferPosition
});
}
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_FLUSHING, {
startOffset: 0,
endOffset: targetBackBufferPosition,
type: type
});
}
}
});
}
/**
* Update Media Source duration to current level duration or override to Infinity if configuration parameter
* 'liveDurationInfinity` is set to `true`
* More details: https://github.com/video-dev/hls.js/issues/355
*/
;
_proto.updateMediaElementDuration = function updateMediaElementDuration() {
if (!this.details || !this.media || !this.mediaSource || this.mediaSource.readyState !== 'open') {
return;
}
var details = this.details,
hls = this.hls,
media = this.media,
mediaSource = this.mediaSource;
var levelDuration = details.fragments[0].start + details.totalduration;
var mediaDuration = media.duration;
var msDuration = Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(mediaSource.duration) ? mediaSource.duration : 0;
if (details.live && hls.config.liveDurationInfinity) {
// Override duration to Infinity
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('[buffer-controller]: Media Source duration is set to Infinity');
mediaSource.duration = Infinity;
this.updateSeekableRange(details);
} else if (levelDuration > msDuration && levelDuration > mediaDuration || !Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(mediaDuration)) {
// levelDuration was the last value we set.
// not using mediaSource.duration as the browser may tweak this value
// only update Media Source duration if its value increase, this is to avoid
// flushing already buffered portion when switching between quality level
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("[buffer-controller]: Updating Media Source duration to " + levelDuration.toFixed(3));
mediaSource.duration = levelDuration;
}
};
_proto.updateSeekableRange = function updateSeekableRange(levelDetails) {
var mediaSource = this.mediaSource;
var fragments = levelDetails.fragments;
var len = fragments.length;
if (len && levelDetails.live && mediaSource !== null && mediaSource !== void 0 && mediaSource.setLiveSeekableRange) {
var start = Math.max(0, fragments[0].start);
var end = Math.max(start, start + levelDetails.totalduration);
mediaSource.setLiveSeekableRange(start, end);
}
};
_proto.checkPendingTracks = function checkPendingTracks() {
var bufferCodecEventsExpected = this.bufferCodecEventsExpected,
operationQueue = this.operationQueue,
pendingTracks = this.pendingTracks; // Check if we've received all of the expected bufferCodec events. When none remain, create all the sourceBuffers at once.
// This is important because the MSE spec allows implementations to throw QuotaExceededErrors if creating new sourceBuffers after
// data has been appended to existing ones.
// 2 tracks is the max (one for audio, one for video). If we've reach this max go ahead and create the buffers.
var pendingTracksCount = Object.keys(pendingTracks).length;
if (pendingTracksCount && !bufferCodecEventsExpected || pendingTracksCount === 2) {
// ok, let's create them now !
this.createSourceBuffers(pendingTracks);
this.pendingTracks = {}; // append any pending segments now !
var buffers = this.getSourceBufferTypes();
if (buffers.length === 0) {
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_3__["ErrorTypes"].MEDIA_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_3__["ErrorDetails"].BUFFER_INCOMPATIBLE_CODECS_ERROR,
fatal: true,
reason: 'could not create source buffer for media codec(s)'
});
return;
}
buffers.forEach(function (type) {
operationQueue.executeNext(type);
});
}
};
_proto.createSourceBuffers = function createSourceBuffers(tracks) {
var sourceBuffer = this.sourceBuffer,
mediaSource = this.mediaSource;
if (!mediaSource) {
throw Error('createSourceBuffers called when mediaSource was null');
}
var tracksCreated = 0;
for (var trackName in tracks) {
if (!sourceBuffer[trackName]) {
var track = tracks[trackName];
if (!track) {
throw Error("source buffer exists for track " + trackName + ", however track does not");
} // use levelCodec as first priority
var codec = track.levelCodec || track.codec;
var mimeType = track.container + ";codecs=" + codec;
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("[buffer-controller]: creating sourceBuffer(" + mimeType + ")");
try {
var sb = sourceBuffer[trackName] = mediaSource.addSourceBuffer(mimeType);
var sbName = trackName;
this.addBufferListener(sbName, 'updatestart', this._onSBUpdateStart);
this.addBufferListener(sbName, 'updateend', this._onSBUpdateEnd);
this.addBufferListener(sbName, 'error', this._onSBUpdateError);
this.tracks[trackName] = {
buffer: sb,
codec: codec,
container: track.container,
levelCodec: track.levelCodec,
id: track.id
};
tracksCreated++;
} catch (err) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error("[buffer-controller]: error while trying to add sourceBuffer: " + err.message);
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_3__["ErrorTypes"].MEDIA_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_3__["ErrorDetails"].BUFFER_ADD_CODEC_ERROR,
fatal: false,
error: err,
mimeType: mimeType
});
}
}
}
if (tracksCreated) {
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_CREATED, {
tracks: this.tracks
});
}
} // Keep as arrow functions so that we can directly reference these functions directly as event listeners
;
_proto._onSBUpdateStart = function _onSBUpdateStart(type) {
var operationQueue = this.operationQueue;
var operation = operationQueue.current(type);
operation.onStart();
};
_proto._onSBUpdateEnd = function _onSBUpdateEnd(type) {
var operationQueue = this.operationQueue;
var operation = operationQueue.current(type);
operation.onComplete();
operationQueue.shiftAndExecuteNext(type);
};
_proto._onSBUpdateError = function _onSBUpdateError(type, event) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error("[buffer-controller]: " + type + " SourceBuffer error", event); // according to http://www.w3.org/TR/media-source/#sourcebuffer-append-error
// SourceBuffer errors are not necessarily fatal; if so, the HTMLMediaElement will fire an error event
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_3__["ErrorTypes"].MEDIA_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_3__["ErrorDetails"].BUFFER_APPENDING_ERROR,
fatal: false
}); // updateend is always fired after error, so we'll allow that to shift the current operation off of the queue
var operation = this.operationQueue.current(type);
if (operation) {
operation.onError(event);
}
} // This method must result in an updateend event; if remove is not called, _onSBUpdateEnd must be called manually
;
_proto.removeExecutor = function removeExecutor(type, startOffset, endOffset) {
var media = this.media,
mediaSource = this.mediaSource,
operationQueue = this.operationQueue,
sourceBuffer = this.sourceBuffer;
var sb = sourceBuffer[type];
if (!media || !mediaSource || !sb) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn("[buffer-controller]: Attempting to remove from the " + type + " SourceBuffer, but it does not exist");
operationQueue.shiftAndExecuteNext(type);
return;
}
var mediaDuration = Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(media.duration) ? media.duration : Infinity;
var msDuration = Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(mediaSource.duration) ? mediaSource.duration : Infinity;
var removeStart = Math.max(0, startOffset);
var removeEnd = Math.min(endOffset, mediaDuration, msDuration);
if (removeEnd > removeStart) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("[buffer-controller]: Removing [" + removeStart + "," + removeEnd + "] from the " + type + " SourceBuffer");
console.assert(!sb.updating, type + " sourceBuffer must not be updating");
sb.remove(removeStart, removeEnd);
} else {
// Cycle the queue
operationQueue.shiftAndExecuteNext(type);
}
} // This method must result in an updateend event; if append is not called, _onSBUpdateEnd must be called manually
;
_proto.appendExecutor = function appendExecutor(data, type) {
var operationQueue = this.operationQueue,
sourceBuffer = this.sourceBuffer;
var sb = sourceBuffer[type];
if (!sb) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn("[buffer-controller]: Attempting to append to the " + type + " SourceBuffer, but it does not exist");
operationQueue.shiftAndExecuteNext(type);
return;
}
sb.ended = false;
console.assert(!sb.updating, type + " sourceBuffer must not be updating");
sb.appendBuffer(data);
} // Enqueues an operation to each SourceBuffer queue which, upon execution, resolves a promise. When all promises
// resolve, the onUnblocked function is executed. Functions calling this method do not need to unblock the queue
// upon completion, since we already do it here
;
_proto.blockBuffers = function blockBuffers(onUnblocked, buffers) {
var _this9 = this;
if (buffers === void 0) {
buffers = this.getSourceBufferTypes();
}
if (!buffers.length) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('[buffer-controller]: Blocking operation requested, but no SourceBuffers exist');
Promise.resolve(onUnblocked);
return;
}
var operationQueue = this.operationQueue; // logger.debug(`[buffer-controller]: Blocking ${buffers} SourceBuffer`);
var blockingOperations = buffers.map(function (type) {
return operationQueue.appendBlocker(type);
});
Promise.all(blockingOperations).then(function () {
// logger.debug(`[buffer-controller]: Blocking operation resolved; unblocking ${buffers} SourceBuffer`);
onUnblocked();
buffers.forEach(function (type) {
var sb = _this9.sourceBuffer[type]; // Only cycle the queue if the SB is not updating. There's a bug in Chrome which sets the SB updating flag to
// true when changing the MediaSource duration (https://bugs.chromium.org/p/chromium/issues/detail?id=959359&can=2&q=mediasource%20duration)
// While this is a workaround, it's probably useful to have around
if (!sb || !sb.updating) {
operationQueue.shiftAndExecuteNext(type);
}
});
});
};
_proto.getSourceBufferTypes = function getSourceBufferTypes() {
return Object.keys(this.sourceBuffer);
};
_proto.addBufferListener = function addBufferListener(type, event, fn) {
var buffer = this.sourceBuffer[type];
if (!buffer) {
return;
}
var listener = fn.bind(this, type);
this.listeners[type].push({
event: event,
listener: listener
});
buffer.addEventListener(event, listener);
};
_proto.removeBufferListeners = function removeBufferListeners(type) {
var buffer = this.sourceBuffer[type];
if (!buffer) {
return;
}
this.listeners[type].forEach(function (l) {
buffer.removeEventListener(l.event, l.listener);
});
};
return BufferController;
}();
/***/ }),
/***/ "./src/controller/buffer-operation-queue.ts":
/*!**************************************************!*\
!*** ./src/controller/buffer-operation-queue.ts ***!
\**************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return BufferOperationQueue; });
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
var BufferOperationQueue = /*#__PURE__*/function () {
function BufferOperationQueue(sourceBufferReference) {
this.buffers = void 0;
this.queues = {
video: [],
audio: [],
audiovideo: []
};
this.buffers = sourceBufferReference;
}
var _proto = BufferOperationQueue.prototype;
_proto.append = function append(operation, type) {
var queue = this.queues[type];
queue.push(operation);
if (queue.length === 1 && this.buffers[type]) {
this.executeNext(type);
}
};
_proto.insertAbort = function insertAbort(operation, type) {
var queue = this.queues[type];
queue.unshift(operation);
this.executeNext(type);
};
_proto.appendBlocker = function appendBlocker(type) {
var execute;
var promise = new Promise(function (resolve) {
execute = resolve;
});
var operation = {
execute: execute,
onStart: function onStart() {},
onComplete: function onComplete() {},
onError: function onError() {}
};
this.append(operation, type);
return promise;
};
_proto.executeNext = function executeNext(type) {
var buffers = this.buffers,
queues = this.queues;
var sb = buffers[type];
var queue = queues[type];
if (queue.length) {
var operation = queue[0];
try {
// Operations are expected to result in an 'updateend' event being fired. If not, the queue will lock. Operations
// which do not end with this event must call _onSBUpdateEnd manually
operation.execute();
} catch (e) {
_utils_logger__WEBPACK_IMPORTED_MODULE_0__["logger"].warn('[buffer-operation-queue]: Unhandled exception executing the current operation');
operation.onError(e); // Only shift the current operation off, otherwise the updateend handler will do this for us
if (!sb || !sb.updating) {
queue.shift();
this.executeNext(type);
}
}
}
};
_proto.shiftAndExecuteNext = function shiftAndExecuteNext(type) {
this.queues[type].shift();
this.executeNext(type);
};
_proto.current = function current(type) {
return this.queues[type][0];
};
return BufferOperationQueue;
}();
/***/ }),
/***/ "./src/controller/cap-level-controller.ts":
/*!************************************************!*\
!*** ./src/controller/cap-level-controller.ts ***!
\************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ "./src/events.ts");
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
/*
* cap stream level to media size dimension controller
*/
var CapLevelController = /*#__PURE__*/function () {
function CapLevelController(hls) {
this.autoLevelCapping = void 0;
this.firstLevel = void 0;
this.media = void 0;
this.restrictedLevels = void 0;
this.timer = void 0;
this.hls = void 0;
this.streamController = void 0;
this.clientRect = void 0;
this.hls = hls;
this.autoLevelCapping = Number.POSITIVE_INFINITY;
this.firstLevel = -1;
this.media = null;
this.restrictedLevels = [];
this.timer = undefined;
this.clientRect = null;
this.registerListeners();
}
var _proto = CapLevelController.prototype;
_proto.setStreamController = function setStreamController(streamController) {
this.streamController = streamController;
};
_proto.destroy = function destroy() {
this.unregisterListener();
if (this.hls.config.capLevelToPlayerSize) {
this.stopCapping();
}
this.media = null;
this.clientRect = null; // @ts-ignore
this.hls = this.streamController = null;
};
_proto.registerListeners = function registerListeners() {
var hls = this.hls;
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FPS_DROP_LEVEL_CAPPING, this.onFpsDropLevelCapping, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHING, this.onMediaAttaching, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MANIFEST_PARSED, this.onManifestParsed, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].BUFFER_CODECS, this.onBufferCodecs, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
};
_proto.unregisterListener = function unregisterListener() {
var hls = this.hls;
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FPS_DROP_LEVEL_CAPPING, this.onFpsDropLevelCapping, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHING, this.onMediaAttaching, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MANIFEST_PARSED, this.onManifestParsed, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].BUFFER_CODECS, this.onBufferCodecs, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
};
_proto.onFpsDropLevelCapping = function onFpsDropLevelCapping(event, data) {
// Don't add a restricted level more than once
if (CapLevelController.isLevelAllowed(data.droppedLevel, this.restrictedLevels)) {
this.restrictedLevels.push(data.droppedLevel);
}
};
_proto.onMediaAttaching = function onMediaAttaching(event, data) {
this.media = data.media instanceof HTMLVideoElement ? data.media : null;
};
_proto.onManifestParsed = function onManifestParsed(event, data) {
var hls = this.hls;
this.restrictedLevels = [];
this.firstLevel = data.firstLevel;
if (hls.config.capLevelToPlayerSize && data.video) {
// Start capping immediately if the manifest has signaled video codecs
this.startCapping();
}
} // Only activate capping when playing a video stream; otherwise, multi-bitrate audio-only streams will be restricted
// to the first level
;
_proto.onBufferCodecs = function onBufferCodecs(event, data) {
var hls = this.hls;
if (hls.config.capLevelToPlayerSize && data.video) {
// If the manifest did not signal a video codec capping has been deferred until we're certain video is present
this.startCapping();
}
};
_proto.onMediaDetaching = function onMediaDetaching() {
this.stopCapping();
};
_proto.detectPlayerSize = function detectPlayerSize() {
if (this.media && this.mediaHeight > 0 && this.mediaWidth > 0) {
var levels = this.hls.levels;
if (levels.length) {
var hls = this.hls;
hls.autoLevelCapping = this.getMaxLevel(levels.length - 1);
if (hls.autoLevelCapping > this.autoLevelCapping && this.streamController) {
// if auto level capping has a higher value for the previous one, flush the buffer using nextLevelSwitch
// usually happen when the user go to the fullscreen mode.
this.streamController.nextLevelSwitch();
}
this.autoLevelCapping = hls.autoLevelCapping;
}
}
}
/*
* returns level should be the one with the dimensions equal or greater than the media (player) dimensions (so the video will be downscaled)
*/
;
_proto.getMaxLevel = function getMaxLevel(capLevelIndex) {
var _this = this;
var levels = this.hls.levels;
if (!levels.length) {
return -1;
}
var validLevels = levels.filter(function (level, index) {
return CapLevelController.isLevelAllowed(index, _this.restrictedLevels) && index <= capLevelIndex;
});
this.clientRect = null;
return CapLevelController.getMaxLevelByMediaSize(validLevels, this.mediaWidth, this.mediaHeight);
};
_proto.startCapping = function startCapping() {
if (this.timer) {
// Don't reset capping if started twice; this can happen if the manifest signals a video codec
return;
}
this.autoLevelCapping = Number.POSITIVE_INFINITY;
this.hls.firstLevel = this.getMaxLevel(this.firstLevel);
self.clearInterval(this.timer);
this.timer = self.setInterval(this.detectPlayerSize.bind(this), 1000);
this.detectPlayerSize();
};
_proto.stopCapping = function stopCapping() {
this.restrictedLevels = [];
this.firstLevel = -1;
this.autoLevelCapping = Number.POSITIVE_INFINITY;
if (this.timer) {
self.clearInterval(this.timer);
this.timer = undefined;
}
};
_proto.getDimensions = function getDimensions() {
if (this.clientRect) {
return this.clientRect;
}
var media = this.media;
var boundsRect = {
width: 0,
height: 0
};
if (media) {
var clientRect = media.getBoundingClientRect();
boundsRect.width = clientRect.width;
boundsRect.height = clientRect.height;
if (!boundsRect.width && !boundsRect.height) {
// When the media element has no width or height (equivalent to not being in the DOM),
// then use its width and height attributes (media.width, media.height)
boundsRect.width = clientRect.right - clientRect.left || media.width || 0;
boundsRect.height = clientRect.bottom - clientRect.top || media.height || 0;
}
}
this.clientRect = boundsRect;
return boundsRect;
};
CapLevelController.isLevelAllowed = function isLevelAllowed(level, restrictedLevels) {
if (restrictedLevels === void 0) {
restrictedLevels = [];
}
return restrictedLevels.indexOf(level) === -1;
};
CapLevelController.getMaxLevelByMediaSize = function getMaxLevelByMediaSize(levels, width, height) {
if (!levels || !levels.length) {
return -1;
} // Levels can have the same dimensions but differing bandwidths - since levels are ordered, we can look to the next
// to determine whether we've chosen the greatest bandwidth for the media's dimensions
var atGreatestBandiwdth = function atGreatestBandiwdth(curLevel, nextLevel) {
if (!nextLevel) {
return true;
}
return curLevel.width !== nextLevel.width || curLevel.height !== nextLevel.height;
}; // If we run through the loop without breaking, the media's dimensions are greater than every level, so default to
// the max level
var maxLevelIndex = levels.length - 1;
for (var i = 0; i < levels.length; i += 1) {
var level = levels[i];
if ((level.width >= width || level.height >= height) && atGreatestBandiwdth(level, levels[i + 1])) {
maxLevelIndex = i;
break;
}
}
return maxLevelIndex;
};
_createClass(CapLevelController, [{
key: "mediaWidth",
get: function get() {
return this.getDimensions().width * CapLevelController.contentScaleFactor;
}
}, {
key: "mediaHeight",
get: function get() {
return this.getDimensions().height * CapLevelController.contentScaleFactor;
}
}], [{
key: "contentScaleFactor",
get: function get() {
var pixelRatio = 1;
try {
pixelRatio = self.devicePixelRatio;
} catch (e) {
/* no-op */
}
return pixelRatio;
}
}]);
return CapLevelController;
}();
/* harmony default export */ __webpack_exports__["default"] = (CapLevelController);
/***/ }),
/***/ "./src/controller/fps-controller.ts":
/*!******************************************!*\
!*** ./src/controller/fps-controller.ts ***!
\******************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
var FPSController = /*#__PURE__*/function () {
// stream controller must be provided as a dependency!
function FPSController(hls) {
this.hls = void 0;
this.isVideoPlaybackQualityAvailable = false;
this.timer = void 0;
this.media = null;
this.lastTime = void 0;
this.lastDroppedFrames = 0;
this.lastDecodedFrames = 0;
this.streamController = void 0;
this.hls = hls;
this.registerListeners();
}
var _proto = FPSController.prototype;
_proto.setStreamController = function setStreamController(streamController) {
this.streamController = streamController;
};
_proto.registerListeners = function registerListeners() {
this.hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHING, this.onMediaAttaching, this);
};
_proto.unregisterListeners = function unregisterListeners() {
this.hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHING, this.onMediaAttaching);
};
_proto.destroy = function destroy() {
if (this.timer) {
clearInterval(this.timer);
}
this.unregisterListeners();
this.isVideoPlaybackQualityAvailable = false;
this.media = null;
};
_proto.onMediaAttaching = function onMediaAttaching(event, data) {
var config = this.hls.config;
if (config.capLevelOnFPSDrop) {
var media = data.media instanceof self.HTMLVideoElement ? data.media : null;
this.media = media;
if (media && typeof media.getVideoPlaybackQuality === 'function') {
this.isVideoPlaybackQualityAvailable = true;
}
self.clearInterval(this.timer);
this.timer = self.setInterval(this.checkFPSInterval.bind(this), config.fpsDroppedMonitoringPeriod);
}
};
_proto.checkFPS = function checkFPS(video, decodedFrames, droppedFrames) {
var currentTime = performance.now();
if (decodedFrames) {
if (this.lastTime) {
var currentPeriod = currentTime - this.lastTime;
var currentDropped = droppedFrames - this.lastDroppedFrames;
var currentDecoded = decodedFrames - this.lastDecodedFrames;
var droppedFPS = 1000 * currentDropped / currentPeriod;
var hls = this.hls;
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FPS_DROP, {
currentDropped: currentDropped,
currentDecoded: currentDecoded,
totalDroppedFrames: droppedFrames
});
if (droppedFPS > 0) {
// logger.log('checkFPS : droppedFPS/decodedFPS:' + droppedFPS/(1000 * currentDecoded / currentPeriod));
if (currentDropped > hls.config.fpsDroppedMonitoringThreshold * currentDecoded) {
var currentLevel = hls.currentLevel;
_utils_logger__WEBPACK_IMPORTED_MODULE_1__["logger"].warn('drop FPS ratio greater than max allowed value for currentLevel: ' + currentLevel);
if (currentLevel > 0 && (hls.autoLevelCapping === -1 || hls.autoLevelCapping >= currentLevel)) {
currentLevel = currentLevel - 1;
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FPS_DROP_LEVEL_CAPPING, {
level: currentLevel,
droppedLevel: hls.currentLevel
});
hls.autoLevelCapping = currentLevel;
this.streamController.nextLevelSwitch();
}
}
}
}
this.lastTime = currentTime;
this.lastDroppedFrames = droppedFrames;
this.lastDecodedFrames = decodedFrames;
}
};
_proto.checkFPSInterval = function checkFPSInterval() {
var video = this.media;
if (video) {
if (this.isVideoPlaybackQualityAvailable) {
var videoPlaybackQuality = video.getVideoPlaybackQuality();
this.checkFPS(video, videoPlaybackQuality.totalVideoFrames, videoPlaybackQuality.droppedVideoFrames);
} else {
// HTMLVideoElement doesn't include the webkit types
this.checkFPS(video, video.webkitDecodedFrameCount, video.webkitDroppedFrameCount);
}
}
};
return FPSController;
}();
/* harmony default export */ __webpack_exports__["default"] = (FPSController);
/***/ }),
/***/ "./src/controller/fragment-finders.ts":
/*!********************************************!*\
!*** ./src/controller/fragment-finders.ts ***!
\********************************************/
/*! exports provided: findFragmentByPDT, findFragmentByPTS, fragmentWithinToleranceTest, pdtWithinToleranceTest, findFragWithCC */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findFragmentByPDT", function() { return findFragmentByPDT; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findFragmentByPTS", function() { return findFragmentByPTS; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "fragmentWithinToleranceTest", function() { return fragmentWithinToleranceTest; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "pdtWithinToleranceTest", function() { return pdtWithinToleranceTest; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findFragWithCC", function() { return findFragWithCC; });
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var _utils_binary_search__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/binary-search */ "./src/utils/binary-search.ts");
/**
* Returns first fragment whose endPdt value exceeds the given PDT.
* @param {Array<Fragment>} fragments - The array of candidate fragments
* @param {number|null} [PDTValue = null] - The PDT value which must be exceeded
* @param {number} [maxFragLookUpTolerance = 0] - The amount of time that a fragment's start/end can be within in order to be considered contiguous
* @returns {*|null} fragment - The best matching fragment
*/
function findFragmentByPDT(fragments, PDTValue, maxFragLookUpTolerance) {
if (PDTValue === null || !Array.isArray(fragments) || !fragments.length || !Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(PDTValue)) {
return null;
} // if less than start
var startPDT = fragments[0].programDateTime;
if (PDTValue < (startPDT || 0)) {
return null;
}
var endPDT = fragments[fragments.length - 1].endProgramDateTime;
if (PDTValue >= (endPDT || 0)) {
return null;
}
maxFragLookUpTolerance = maxFragLookUpTolerance || 0;
for (var seg = 0; seg < fragments.length; ++seg) {
var frag = fragments[seg];
if (pdtWithinToleranceTest(PDTValue, maxFragLookUpTolerance, frag)) {
return frag;
}
}
return null;
}
/**
* Finds a fragment based on the SN of the previous fragment; or based on the needs of the current buffer.
* This method compensates for small buffer gaps by applying a tolerance to the start of any candidate fragment, thus
* breaking any traps which would cause the same fragment to be continuously selected within a small range.
* @param {*} fragPrevious - The last frag successfully appended
* @param {Array} fragments - The array of candidate fragments
* @param {number} [bufferEnd = 0] - The end of the contiguous buffered range the playhead is currently within
* @param {number} maxFragLookUpTolerance - The amount of time that a fragment's start/end can be within in order to be considered contiguous
* @returns {*} foundFrag - The best matching fragment
*/
function findFragmentByPTS(fragPrevious, fragments, bufferEnd, maxFragLookUpTolerance) {
if (bufferEnd === void 0) {
bufferEnd = 0;
}
if (maxFragLookUpTolerance === void 0) {
maxFragLookUpTolerance = 0;
}
var fragNext = null;
if (fragPrevious) {
fragNext = fragments[fragPrevious.sn - fragments[0].sn + 1] || null;
} else if (bufferEnd === 0 && fragments[0].start === 0) {
fragNext = fragments[0];
} // Prefer the next fragment if it's within tolerance
if (fragNext && fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, fragNext) === 0) {
return fragNext;
} // We might be seeking past the tolerance so find the best match
var foundFragment = _utils_binary_search__WEBPACK_IMPORTED_MODULE_1__["default"].search(fragments, fragmentWithinToleranceTest.bind(null, bufferEnd, maxFragLookUpTolerance));
if (foundFragment) {
return foundFragment;
} // If no match was found return the next fragment after fragPrevious, or null
return fragNext;
}
/**
* The test function used by the findFragmentBySn's BinarySearch to look for the best match to the current buffer conditions.
* @param {*} candidate - The fragment to test
* @param {number} [bufferEnd = 0] - The end of the current buffered range the playhead is currently within
* @param {number} [maxFragLookUpTolerance = 0] - The amount of time that a fragment's start can be within in order to be considered contiguous
* @returns {number} - 0 if it matches, 1 if too low, -1 if too high
*/
function fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, candidate) {
if (bufferEnd === void 0) {
bufferEnd = 0;
}
if (maxFragLookUpTolerance === void 0) {
maxFragLookUpTolerance = 0;
}
// offset should be within fragment boundary - config.maxFragLookUpTolerance
// this is to cope with situations like
// bufferEnd = 9.991
// frag[Ø] : [0,10]
// frag[1] : [10,20]
// bufferEnd is within frag[0] range ... although what we are expecting is to return frag[1] here
// frag start frag start+duration
// |-----------------------------|
// <---> <--->
// ...--------><-----------------------------><---------....
// previous frag matching fragment next frag
// return -1 return 0 return 1
// logger.log(`level/sn/start/end/bufEnd:${level}/${candidate.sn}/${candidate.start}/${(candidate.start+candidate.duration)}/${bufferEnd}`);
// Set the lookup tolerance to be small enough to detect the current segment - ensures we don't skip over very small segments
var candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0));
if (candidate.start + candidate.duration - candidateLookupTolerance <= bufferEnd) {
return 1;
} else if (candidate.start - candidateLookupTolerance > bufferEnd && candidate.start) {
// if maxFragLookUpTolerance will have negative value then don't return -1 for first element
return -1;
}
return 0;
}
/**
* The test function used by the findFragmentByPdt's BinarySearch to look for the best match to the current buffer conditions.
* This function tests the candidate's program date time values, as represented in Unix time
* @param {*} candidate - The fragment to test
* @param {number} [pdtBufferEnd = 0] - The Unix time representing the end of the current buffered range
* @param {number} [maxFragLookUpTolerance = 0] - The amount of time that a fragment's start can be within in order to be considered contiguous
* @returns {boolean} True if contiguous, false otherwise
*/
function pdtWithinToleranceTest(pdtBufferEnd, maxFragLookUpTolerance, candidate) {
var candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0)) * 1000; // endProgramDateTime can be null, default to zero
var endProgramDateTime = candidate.endProgramDateTime || 0;
return endProgramDateTime - candidateLookupTolerance > pdtBufferEnd;
}
function findFragWithCC(fragments, cc) {
return _utils_binary_search__WEBPACK_IMPORTED_MODULE_1__["default"].search(fragments, function (candidate) {
if (candidate.cc < cc) {
return 1;
} else if (candidate.cc > cc) {
return -1;
} else {
return 0;
}
});
}
/***/ }),
/***/ "./src/controller/fragment-tracker.ts":
/*!********************************************!*\
!*** ./src/controller/fragment-tracker.ts ***!
\********************************************/
/*! exports provided: FragmentState, FragmentTracker */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FragmentState", function() { return FragmentState; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FragmentTracker", function() { return FragmentTracker; });
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts");
var FragmentState;
(function (FragmentState) {
FragmentState["NOT_LOADED"] = "NOT_LOADED";
FragmentState["BACKTRACKED"] = "BACKTRACKED";
FragmentState["APPENDING"] = "APPENDING";
FragmentState["PARTIAL"] = "PARTIAL";
FragmentState["OK"] = "OK";
})(FragmentState || (FragmentState = {}));
var FragmentTracker = /*#__PURE__*/function () {
function FragmentTracker(hls) {
this.activeFragment = null;
this.activeParts = null;
this.fragments = Object.create(null);
this.timeRanges = Object.create(null);
this.bufferPadding = 0.2;
this.hls = void 0;
this.hls = hls;
this._registerListeners();
}
var _proto = FragmentTracker.prototype;
_proto._registerListeners = function _registerListeners() {
var hls = this.hls;
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].BUFFER_APPENDED, this.onBufferAppended, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FRAG_BUFFERED, this.onFragBuffered, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FRAG_LOADED, this.onFragLoaded, this);
};
_proto._unregisterListeners = function _unregisterListeners() {
var hls = this.hls;
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].BUFFER_APPENDED, this.onBufferAppended, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FRAG_BUFFERED, this.onFragBuffered, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FRAG_LOADED, this.onFragLoaded, this);
};
_proto.destroy = function destroy() {
this._unregisterListeners(); // @ts-ignore
this.fragments = this.timeRanges = null;
}
/**
* Return a Fragment with an appended range that matches the position and levelType.
* If not found any Fragment, return null
*/
;
_proto.getAppendedFrag = function getAppendedFrag(position, levelType) {
if (levelType === _types_loader__WEBPACK_IMPORTED_MODULE_1__["PlaylistLevelType"].MAIN) {
var activeFragment = this.activeFragment,
activeParts = this.activeParts;
if (!activeFragment) {
return null;
}
if (activeParts) {
for (var i = activeParts.length; i--;) {
var activePart = activeParts[i];
var appendedPTS = activePart ? activePart.end : activeFragment.appendedPTS;
if (activePart.start <= position && appendedPTS !== undefined && position <= appendedPTS) {
// 9 is a magic number. remove parts from lookup after a match but keep some short seeks back.
if (i > 9) {
this.activeParts = activeParts.slice(i - 9);
}
return activePart;
}
}
} else if (activeFragment.start <= position && activeFragment.appendedPTS !== undefined && position <= activeFragment.appendedPTS) {
return activeFragment;
}
}
return this.getBufferedFrag(position, levelType);
}
/**
* Return a buffered Fragment that matches the position and levelType.
* A buffered Fragment is one whose loading, parsing and appending is done (completed or "partial" meaning aborted).
* If not found any Fragment, return null
*/
;
_proto.getBufferedFrag = function getBufferedFrag(position, levelType) {
var fragments = this.fragments;
var keys = Object.keys(fragments);
for (var i = keys.length; i--;) {
var fragmentEntity = fragments[keys[i]];
if ((fragmentEntity === null || fragmentEntity === void 0 ? void 0 : fragmentEntity.body.type) === levelType && fragmentEntity.buffered) {
var frag = fragmentEntity.body;
if (frag.start <= position && position <= frag.end) {
return frag;
}
}
}
return null;
}
/**
* Partial fragments effected by coded frame eviction will be removed
* The browser will unload parts of the buffer to free up memory for new buffer data
* Fragments will need to be reloaded when the buffer is freed up, removing partial fragments will allow them to reload(since there might be parts that are still playable)
*/
;
_proto.detectEvictedFragments = function detectEvictedFragments(elementaryStream, timeRange, playlistType) {
var _this = this;
// Check if any flagged fragments have been unloaded
Object.keys(this.fragments).forEach(function (key) {
var fragmentEntity = _this.fragments[key];
if (!fragmentEntity) {
return;
}
if (!fragmentEntity.buffered) {
if (fragmentEntity.body.type === playlistType) {
_this.removeFragment(fragmentEntity.body);
}
return;
}
var esData = fragmentEntity.range[elementaryStream];
if (!esData) {
return;
}
esData.time.some(function (time) {
var isNotBuffered = !_this.isTimeBuffered(time.startPTS, time.endPTS, timeRange);
if (isNotBuffered) {
// Unregister partial fragment as it needs to load again to be reused
_this.removeFragment(fragmentEntity.body);
}
return isNotBuffered;
});
});
}
/**
* Checks if the fragment passed in is loaded in the buffer properly
* Partially loaded fragments will be registered as a partial fragment
*/
;
_proto.detectPartialFragments = function detectPartialFragments(data) {
var _this2 = this;
var timeRanges = this.timeRanges;
var frag = data.frag,
part = data.part;
if (!timeRanges || frag.sn === 'initSegment') {
return;
}
var fragKey = getFragmentKey(frag);
var fragmentEntity = this.fragments[fragKey];
if (!fragmentEntity) {
return;
}
Object.keys(timeRanges).forEach(function (elementaryStream) {
var streamInfo = frag.elementaryStreams[elementaryStream];
if (!streamInfo) {
return;
}
var timeRange = timeRanges[elementaryStream];
var partial = part !== null || streamInfo.partial === true;
fragmentEntity.range[elementaryStream] = _this2.getBufferedTimes(frag, part, partial, timeRange);
});
fragmentEntity.backtrack = fragmentEntity.loaded = null;
if (Object.keys(fragmentEntity.range).length) {
fragmentEntity.buffered = true;
} else {
// remove fragment if nothing was appended
this.removeFragment(fragmentEntity.body);
}
};
_proto.fragBuffered = function fragBuffered(frag) {
var fragKey = getFragmentKey(frag);
var fragmentEntity = this.fragments[fragKey];
if (fragmentEntity) {
fragmentEntity.backtrack = fragmentEntity.loaded = null;
fragmentEntity.buffered = true;
}
};
_proto.getBufferedTimes = function getBufferedTimes(fragment, part, partial, timeRange) {
var buffered = {
time: [],
partial: partial
};
var startPTS = part ? part.start : fragment.start;
var endPTS = part ? part.end : fragment.end;
var minEndPTS = fragment.minEndPTS || endPTS;
var maxStartPTS = fragment.maxStartPTS || startPTS;
for (var i = 0; i < timeRange.length; i++) {
var startTime = timeRange.start(i) - this.bufferPadding;
var endTime = timeRange.end(i) + this.bufferPadding;
if (maxStartPTS >= startTime && minEndPTS <= endTime) {
// Fragment is entirely contained in buffer
// No need to check the other timeRange times since it's completely playable
buffered.time.push({
startPTS: Math.max(startPTS, timeRange.start(i)),
endPTS: Math.min(endPTS, timeRange.end(i))
});
break;
} else if (startPTS < endTime && endPTS > startTime) {
buffered.partial = true; // Check for intersection with buffer
// Get playable sections of the fragment
buffered.time.push({
startPTS: Math.max(startPTS, timeRange.start(i)),
endPTS: Math.min(endPTS, timeRange.end(i))
});
} else if (endPTS <= startTime) {
// No need to check the rest of the timeRange as it is in order
break;
}
}
return buffered;
}
/**
* Gets the partial fragment for a certain time
*/
;
_proto.getPartialFragment = function getPartialFragment(time) {
var bestFragment = null;
var timePadding;
var startTime;
var endTime;
var bestOverlap = 0;
var bufferPadding = this.bufferPadding,
fragments = this.fragments;
Object.keys(fragments).forEach(function (key) {
var fragmentEntity = fragments[key];
if (!fragmentEntity) {
return;
}
if (isPartial(fragmentEntity)) {
startTime = fragmentEntity.body.start - bufferPadding;
endTime = fragmentEntity.body.end + bufferPadding;
if (time >= startTime && time <= endTime) {
// Use the fragment that has the most padding from start and end time
timePadding = Math.min(time - startTime, endTime - time);
if (bestOverlap <= timePadding) {
bestFragment = fragmentEntity.body;
bestOverlap = timePadding;
}
}
}
});
return bestFragment;
};
_proto.getState = function getState(fragment) {
var fragKey = getFragmentKey(fragment);
var fragmentEntity = this.fragments[fragKey];
if (fragmentEntity) {
if (!fragmentEntity.buffered) {
if (fragmentEntity.backtrack) {
return FragmentState.BACKTRACKED;
}
return FragmentState.APPENDING;
} else if (isPartial(fragmentEntity)) {
return FragmentState.PARTIAL;
} else {
return FragmentState.OK;
}
}
return FragmentState.NOT_LOADED;
};
_proto.backtrack = function backtrack(frag, data) {
var fragKey = getFragmentKey(frag);
var fragmentEntity = this.fragments[fragKey];
if (!fragmentEntity || fragmentEntity.backtrack) {
return null;
}
var backtrack = fragmentEntity.backtrack = data ? data : fragmentEntity.loaded;
fragmentEntity.loaded = null;
return backtrack;
};
_proto.getBacktrackData = function getBacktrackData(fragment) {
var fragKey = getFragmentKey(fragment);
var fragmentEntity = this.fragments[fragKey];
if (fragmentEntity) {
var _backtrack$payload;
var backtrack = fragmentEntity.backtrack; // If data was already sent to Worker it is detached no longer available
if (backtrack !== null && backtrack !== void 0 && (_backtrack$payload = backtrack.payload) !== null && _backtrack$payload !== void 0 && _backtrack$payload.byteLength) {
return backtrack;
} else {
this.removeFragment(fragment);
}
}
return null;
};
_proto.isTimeBuffered = function isTimeBuffered(startPTS, endPTS, timeRange) {
var startTime;
var endTime;
for (var i = 0; i < timeRange.length; i++) {
startTime = timeRange.start(i) - this.bufferPadding;
endTime = timeRange.end(i) + this.bufferPadding;
if (startPTS >= startTime && endPTS <= endTime) {
return true;
}
if (endPTS <= startTime) {
// No need to check the rest of the timeRange as it is in order
return false;
}
}
return false;
};
_proto.onFragLoaded = function onFragLoaded(event, data) {
var frag = data.frag,
part = data.part; // don't track initsegment (for which sn is not a number)
// don't track frags used for bitrateTest, they're irrelevant.
// don't track parts for memory efficiency
if (frag.sn === 'initSegment' || frag.bitrateTest || part) {
return;
}
var fragKey = getFragmentKey(frag);
this.fragments[fragKey] = {
body: frag,
loaded: data,
backtrack: null,
buffered: false,
range: Object.create(null)
};
};
_proto.onBufferAppended = function onBufferAppended(event, data) {
var _this3 = this;
var frag = data.frag,
part = data.part,
timeRanges = data.timeRanges;
if (frag.type === _types_loader__WEBPACK_IMPORTED_MODULE_1__["PlaylistLevelType"].MAIN) {
this.activeFragment = frag;
if (part) {
var activeParts = this.activeParts;
if (!activeParts) {
this.activeParts = activeParts = [];
}
activeParts.push(part);
} else {
this.activeParts = null;
}
} // Store the latest timeRanges loaded in the buffer
this.timeRanges = timeRanges;
Object.keys(timeRanges).forEach(function (elementaryStream) {
var timeRange = timeRanges[elementaryStream];
_this3.detectEvictedFragments(elementaryStream, timeRange);
if (!part) {
for (var i = 0; i < timeRange.length; i++) {
frag.appendedPTS = Math.max(timeRange.end(i), frag.appendedPTS || 0);
}
}
});
};
_proto.onFragBuffered = function onFragBuffered(event, data) {
this.detectPartialFragments(data);
};
_proto.hasFragment = function hasFragment(fragment) {
var fragKey = getFragmentKey(fragment);
return !!this.fragments[fragKey];
};
_proto.removeFragmentsInRange = function removeFragmentsInRange(start, end, playlistType) {
var _this4 = this;
Object.keys(this.fragments).forEach(function (key) {
var fragmentEntity = _this4.fragments[key];
if (!fragmentEntity) {
return;
}
if (fragmentEntity.buffered) {
var frag = fragmentEntity.body;
if (frag.type === playlistType && frag.start < end && frag.end > start) {
_this4.removeFragment(frag);
}
}
});
};
_proto.removeFragment = function removeFragment(fragment) {
var fragKey = getFragmentKey(fragment);
fragment.stats.loaded = 0;
fragment.clearElementaryStreamInfo();
delete this.fragments[fragKey];
};
_proto.removeAllFragments = function removeAllFragments() {
this.fragments = Object.create(null);
this.activeFragment = null;
this.activeParts = null;
};
return FragmentTracker;
}();
function isPartial(fragmentEntity) {
var _fragmentEntity$range, _fragmentEntity$range2;
return fragmentEntity.buffered && (((_fragmentEntity$range = fragmentEntity.range.video) === null || _fragmentEntity$range === void 0 ? void 0 : _fragmentEntity$range.partial) || ((_fragmentEntity$range2 = fragmentEntity.range.audio) === null || _fragmentEntity$range2 === void 0 ? void 0 : _fragmentEntity$range2.partial));
}
function getFragmentKey(fragment) {
return fragment.type + "_" + fragment.level + "_" + fragment.urlId + "_" + fragment.sn;
}
/***/ }),
/***/ "./src/controller/gap-controller.ts":
/*!******************************************!*\
!*** ./src/controller/gap-controller.ts ***!
\******************************************/
/*! exports provided: STALL_MINIMUM_DURATION_MS, MAX_START_GAP_JUMP, SKIP_BUFFER_HOLE_STEP_SECONDS, SKIP_BUFFER_RANGE_START, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "STALL_MINIMUM_DURATION_MS", function() { return STALL_MINIMUM_DURATION_MS; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MAX_START_GAP_JUMP", function() { return MAX_START_GAP_JUMP; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SKIP_BUFFER_HOLE_STEP_SECONDS", function() { return SKIP_BUFFER_HOLE_STEP_SECONDS; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SKIP_BUFFER_RANGE_START", function() { return SKIP_BUFFER_RANGE_START; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return GapController; });
/* harmony import */ var _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/buffer-helper */ "./src/utils/buffer-helper.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
var STALL_MINIMUM_DURATION_MS = 250;
var MAX_START_GAP_JUMP = 2.0;
var SKIP_BUFFER_HOLE_STEP_SECONDS = 0.1;
var SKIP_BUFFER_RANGE_START = 0.05;
var GapController = /*#__PURE__*/function () {
function GapController(config, media, fragmentTracker, hls) {
this.config = void 0;
this.media = void 0;
this.fragmentTracker = void 0;
this.hls = void 0;
this.nudgeRetry = 0;
this.stallReported = false;
this.stalled = null;
this.moved = false;
this.seeking = false;
this.config = config;
this.media = media;
this.fragmentTracker = fragmentTracker;
this.hls = hls;
}
var _proto = GapController.prototype;
_proto.destroy = function destroy() {
// @ts-ignore
this.hls = this.fragmentTracker = this.media = null;
}
/**
* Checks if the playhead is stuck within a gap, and if so, attempts to free it.
* A gap is an unbuffered range between two buffered ranges (or the start and the first buffered range).
*
* @param {number} lastCurrentTime Previously read playhead position
*/
;
_proto.poll = function poll(lastCurrentTime) {
var config = this.config,
media = this.media,
stalled = this.stalled;
var currentTime = media.currentTime,
seeking = media.seeking;
var seeked = this.seeking && !seeking;
var beginSeek = !this.seeking && seeking;
this.seeking = seeking; // The playhead is moving, no-op
if (currentTime !== lastCurrentTime) {
this.moved = true;
if (stalled !== null) {
// The playhead is now moving, but was previously stalled
if (this.stallReported) {
var _stalledDuration = self.performance.now() - stalled;
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn("playback not stuck anymore @" + currentTime + ", after " + Math.round(_stalledDuration) + "ms");
this.stallReported = false;
}
this.stalled = null;
this.nudgeRetry = 0;
}
return;
} // Clear stalled state when beginning or finishing seeking so that we don't report stalls coming out of a seek
if (beginSeek || seeked) {
this.stalled = null;
} // The playhead should not be moving
if (media.paused || media.ended || media.playbackRate === 0 || !_utils_buffer_helper__WEBPACK_IMPORTED_MODULE_0__["BufferHelper"].getBuffered(media).length) {
return;
}
var bufferInfo = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_0__["BufferHelper"].bufferInfo(media, currentTime, 0);
var isBuffered = bufferInfo.len > 0;
var nextStart = bufferInfo.nextStart || 0; // There is no playable buffer (seeked, waiting for buffer)
if (!isBuffered && !nextStart) {
return;
}
if (seeking) {
// Waiting for seeking in a buffered range to complete
var hasEnoughBuffer = bufferInfo.len > MAX_START_GAP_JUMP; // Next buffered range is too far ahead to jump to while still seeking
var noBufferGap = !nextStart || nextStart - currentTime > MAX_START_GAP_JUMP && !this.fragmentTracker.getPartialFragment(currentTime);
if (hasEnoughBuffer || noBufferGap) {
return;
} // Reset moved state when seeking to a point in or before a gap
this.moved = false;
} // Skip start gaps if we haven't played, but the last poll detected the start of a stall
// The addition poll gives the browser a chance to jump the gap for us
if (!this.moved && this.stalled !== null) {
var _level$details;
// Jump start gaps within jump threshold
var startJump = Math.max(nextStart, bufferInfo.start || 0) - currentTime; // When joining a live stream with audio tracks, account for live playlist window sliding by allowing
// a larger jump over start gaps caused by the audio-stream-controller buffering a start fragment
// that begins over 1 target duration after the video start position.
var level = this.hls.levels ? this.hls.levels[this.hls.currentLevel] : null;
var isLive = level === null || level === void 0 ? void 0 : (_level$details = level.details) === null || _level$details === void 0 ? void 0 : _level$details.live;
var maxStartGapJump = isLive ? level.details.targetduration * 2 : MAX_START_GAP_JUMP;
if (startJump > 0 && startJump <= maxStartGapJump) {
this._trySkipBufferHole(null);
return;
}
} // Start tracking stall time
var tnow = self.performance.now();
if (stalled === null) {
this.stalled = tnow;
return;
}
var stalledDuration = tnow - stalled;
if (!seeking && stalledDuration >= STALL_MINIMUM_DURATION_MS) {
// Report stalling after trying to fix
this._reportStall(bufferInfo.len);
}
var bufferedWithHoles = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_0__["BufferHelper"].bufferInfo(media, currentTime, config.maxBufferHole);
this._tryFixBufferStall(bufferedWithHoles, stalledDuration);
}
/**
* Detects and attempts to fix known buffer stalling issues.
* @param bufferInfo - The properties of the current buffer.
* @param stalledDurationMs - The amount of time Hls.js has been stalling for.
* @private
*/
;
_proto._tryFixBufferStall = function _tryFixBufferStall(bufferInfo, stalledDurationMs) {
var config = this.config,
fragmentTracker = this.fragmentTracker,
media = this.media;
var currentTime = media.currentTime;
var partial = fragmentTracker.getPartialFragment(currentTime);
if (partial) {
// Try to skip over the buffer hole caused by a partial fragment
// This method isn't limited by the size of the gap between buffered ranges
var targetTime = this._trySkipBufferHole(partial); // we return here in this case, meaning
// the branch below only executes when we don't handle a partial fragment
if (targetTime) {
return;
}
} // if we haven't had to skip over a buffer hole of a partial fragment
// we may just have to "nudge" the playlist as the browser decoding/rendering engine
// needs to cross some sort of threshold covering all source-buffers content
// to start playing properly.
if (bufferInfo.len > config.maxBufferHole && stalledDurationMs > config.highBufferWatchdogPeriod * 1000) {
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn('Trying to nudge playhead over buffer-hole'); // Try to nudge currentTime over a buffer hole if we've been stalling for the configured amount of seconds
// We only try to jump the hole if it's under the configured size
// Reset stalled so to rearm watchdog timer
this.stalled = null;
this._tryNudgeBuffer();
}
}
/**
* Triggers a BUFFER_STALLED_ERROR event, but only once per stall period.
* @param bufferLen - The playhead distance from the end of the current buffer segment.
* @private
*/
;
_proto._reportStall = function _reportStall(bufferLen) {
var hls = this.hls,
media = this.media,
stallReported = this.stallReported;
if (!stallReported) {
// Report stalled error once
this.stallReported = true;
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn("Playback stalling at @" + media.currentTime + " due to low buffer (buffer=" + bufferLen + ")");
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].MEDIA_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].BUFFER_STALLED_ERROR,
fatal: false,
buffer: bufferLen
});
}
}
/**
* Attempts to fix buffer stalls by jumping over known gaps caused by partial fragments
* @param partial - The partial fragment found at the current time (where playback is stalling).
* @private
*/
;
_proto._trySkipBufferHole = function _trySkipBufferHole(partial) {
var config = this.config,
hls = this.hls,
media = this.media;
var currentTime = media.currentTime;
var lastEndTime = 0; // Check if currentTime is between unbuffered regions of partial fragments
var buffered = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_0__["BufferHelper"].getBuffered(media);
for (var i = 0; i < buffered.length; i++) {
var startTime = buffered.start(i);
if (currentTime + config.maxBufferHole >= lastEndTime && currentTime < startTime) {
var targetTime = Math.max(startTime + SKIP_BUFFER_RANGE_START, media.currentTime + SKIP_BUFFER_HOLE_STEP_SECONDS);
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn("skipping hole, adjusting currentTime from " + currentTime + " to " + targetTime);
this.moved = true;
this.stalled = null;
media.currentTime = targetTime;
if (partial) {
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].MEDIA_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].BUFFER_SEEK_OVER_HOLE,
fatal: false,
reason: "fragment loaded with buffer holes, seeking from " + currentTime + " to " + targetTime,
frag: partial
});
}
return targetTime;
}
lastEndTime = buffered.end(i);
}
return 0;
}
/**
* Attempts to fix buffer stalls by advancing the mediaElement's current time by a small amount.
* @private
*/
;
_proto._tryNudgeBuffer = function _tryNudgeBuffer() {
var config = this.config,
hls = this.hls,
media = this.media;
var currentTime = media.currentTime;
var nudgeRetry = (this.nudgeRetry || 0) + 1;
this.nudgeRetry = nudgeRetry;
if (nudgeRetry < config.nudgeMaxRetry) {
var targetTime = currentTime + nudgeRetry * config.nudgeOffset; // playback stalled in buffered area ... let's nudge currentTime to try to overcome this
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn("Nudging 'currentTime' from " + currentTime + " to " + targetTime);
media.currentTime = targetTime;
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].MEDIA_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].BUFFER_NUDGE_ON_STALL,
fatal: false
});
} else {
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].error("Playhead still not moving while enough data buffered @" + currentTime + " after " + config.nudgeMaxRetry + " nudges");
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].MEDIA_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].BUFFER_STALLED_ERROR,
fatal: true
});
}
};
return GapController;
}();
/***/ }),
/***/ "./src/controller/id3-track-controller.ts":
/*!************************************************!*\
!*** ./src/controller/id3-track-controller.ts ***!
\************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/texttrack-utils */ "./src/utils/texttrack-utils.ts");
/* harmony import */ var _demux_id3__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../demux/id3 */ "./src/demux/id3.ts");
var MIN_CUE_DURATION = 0.25;
var ID3TrackController = /*#__PURE__*/function () {
function ID3TrackController(hls) {
this.hls = void 0;
this.id3Track = null;
this.media = null;
this.hls = hls;
this._registerListeners();
}
var _proto = ID3TrackController.prototype;
_proto.destroy = function destroy() {
this._unregisterListeners();
};
_proto._registerListeners = function _registerListeners() {
var hls = this.hls;
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FRAG_PARSING_METADATA, this.onFragParsingMetadata, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].BUFFER_FLUSHING, this.onBufferFlushing, this);
};
_proto._unregisterListeners = function _unregisterListeners() {
var hls = this.hls;
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FRAG_PARSING_METADATA, this.onFragParsingMetadata, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].BUFFER_FLUSHING, this.onBufferFlushing, this);
} // Add ID3 metatadata text track.
;
_proto.onMediaAttached = function onMediaAttached(event, data) {
this.media = data.media;
};
_proto.onMediaDetaching = function onMediaDetaching() {
if (!this.id3Track) {
return;
}
Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_1__["clearCurrentCues"])(this.id3Track);
this.id3Track = null;
this.media = null;
};
_proto.getID3Track = function getID3Track(textTracks) {
if (!this.media) {
return;
}
for (var i = 0; i < textTracks.length; i++) {
var textTrack = textTracks[i];
if (textTrack.kind === 'metadata' && textTrack.label === 'id3') {
// send 'addtrack' when reusing the textTrack for metadata,
// same as what we do for captions
Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_1__["sendAddTrackEvent"])(textTrack, this.media);
return textTrack;
}
}
return this.media.addTextTrack('metadata', 'id3');
};
_proto.onFragParsingMetadata = function onFragParsingMetadata(event, data) {
if (!this.media) {
return;
}
var fragment = data.frag;
var samples = data.samples; // create track dynamically
if (!this.id3Track) {
this.id3Track = this.getID3Track(this.media.textTracks);
this.id3Track.mode = 'hidden';
} // Attempt to recreate Safari functionality by creating
// WebKitDataCue objects when available and store the decoded
// ID3 data in the value property of the cue
var Cue = self.WebKitDataCue || self.VTTCue || self.TextTrackCue;
for (var i = 0; i < samples.length; i++) {
var frames = _demux_id3__WEBPACK_IMPORTED_MODULE_2__["getID3Frames"](samples[i].data);
if (frames) {
var startTime = samples[i].pts;
var endTime = i < samples.length - 1 ? samples[i + 1].pts : fragment.end;
var timeDiff = endTime - startTime;
if (timeDiff <= 0) {
endTime = startTime + MIN_CUE_DURATION;
}
for (var j = 0; j < frames.length; j++) {
var frame = frames[j]; // Safari doesn't put the timestamp frame in the TextTrack
if (!_demux_id3__WEBPACK_IMPORTED_MODULE_2__["isTimeStampFrame"](frame)) {
var cue = new Cue(startTime, endTime, '');
cue.value = frame;
this.id3Track.addCue(cue);
}
}
}
}
};
_proto.onBufferFlushing = function onBufferFlushing(event, _ref) {
var startOffset = _ref.startOffset,
endOffset = _ref.endOffset,
type = _ref.type;
if (!type || type === 'audio') {
// id3 cues come from parsed audio only remove cues when audio buffer is cleared
var id3Track = this.id3Track;
if (id3Track) {
Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_1__["removeCuesInRange"])(id3Track, startOffset, endOffset);
}
}
};
return ID3TrackController;
}();
/* harmony default export */ __webpack_exports__["default"] = (ID3TrackController);
/***/ }),
/***/ "./src/controller/latency-controller.ts":
/*!**********************************************!*\
!*** ./src/controller/latency-controller.ts ***!
\**********************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return LatencyController; });
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
var LatencyController = /*#__PURE__*/function () {
function LatencyController(hls) {
var _this = this;
this.hls = void 0;
this.config = void 0;
this.media = null;
this.levelDetails = null;
this.currentTime = 0;
this.stallCount = 0;
this._latency = null;
this.timeupdateHandler = function () {
return _this.timeupdate();
};
this.hls = hls;
this.config = hls.config;
this.registerListeners();
}
var _proto = LatencyController.prototype;
_proto.destroy = function destroy() {
this.unregisterListeners();
this.onMediaDetaching();
this.levelDetails = null; // @ts-ignore
this.hls = this.timeupdateHandler = null;
};
_proto.registerListeners = function registerListeners() {
this.hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this);
this.hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
this.hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADING, this.onManifestLoading, this);
this.hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_UPDATED, this.onLevelUpdated, this);
this.hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, this.onError, this);
};
_proto.unregisterListeners = function unregisterListeners() {
this.hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_ATTACHED, this.onMediaAttached);
this.hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_DETACHING, this.onMediaDetaching);
this.hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADING, this.onManifestLoading);
this.hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_UPDATED, this.onLevelUpdated);
this.hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, this.onError);
};
_proto.onMediaAttached = function onMediaAttached(event, data) {
this.media = data.media;
this.media.addEventListener('timeupdate', this.timeupdateHandler);
};
_proto.onMediaDetaching = function onMediaDetaching() {
if (this.media) {
this.media.removeEventListener('timeupdate', this.timeupdateHandler);
this.media = null;
}
};
_proto.onManifestLoading = function onManifestLoading() {
this.levelDetails = null;
this._latency = null;
this.stallCount = 0;
};
_proto.onLevelUpdated = function onLevelUpdated(event, _ref) {
var details = _ref.details;
this.levelDetails = details;
if (details.advanced) {
this.timeupdate();
}
if (!details.live && this.media) {
this.media.removeEventListener('timeupdate', this.timeupdateHandler);
}
};
_proto.onError = function onError(event, data) {
if (data.details !== _errors__WEBPACK_IMPORTED_MODULE_0__["ErrorDetails"].BUFFER_STALLED_ERROR) {
return;
}
this.stallCount++;
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn('[playback-rate-controller]: Stall detected, adjusting target latency');
};
_proto.timeupdate = function timeupdate() {
var media = this.media,
levelDetails = this.levelDetails;
if (!media || !levelDetails) {
return;
}
this.currentTime = media.currentTime;
var latency = this.computeLatency();
if (latency === null) {
return;
}
this._latency = latency; // Adapt playbackRate to meet target latency in low-latency mode
var _this$config = this.config,
lowLatencyMode = _this$config.lowLatencyMode,
maxLiveSyncPlaybackRate = _this$config.maxLiveSyncPlaybackRate;
if (!lowLatencyMode || maxLiveSyncPlaybackRate === 1) {
return;
}
var targetLatency = this.targetLatency;
if (targetLatency === null) {
return;
}
var distanceFromTarget = latency - targetLatency; // Only adjust playbackRate when within one target duration of targetLatency
// and more than one second from under-buffering.
// Playback further than one target duration from target can be considered DVR playback.
var liveMinLatencyDuration = Math.min(this.maxLatency, targetLatency + levelDetails.targetduration);
var inLiveRange = distanceFromTarget < liveMinLatencyDuration;
if (levelDetails.live && inLiveRange && distanceFromTarget > 0.05 && this.forwardBufferLength > 1) {
var max = Math.min(2, Math.max(1.0, maxLiveSyncPlaybackRate));
var rate = Math.round(2 / (1 + Math.exp(-0.75 * distanceFromTarget - this.edgeStalled)) * 20) / 20;
media.playbackRate = Math.min(max, Math.max(1, rate));
} else if (media.playbackRate !== 1 && media.playbackRate !== 0) {
media.playbackRate = 1;
}
};
_proto.estimateLiveEdge = function estimateLiveEdge() {
var levelDetails = this.levelDetails;
if (levelDetails === null) {
return null;
}
return levelDetails.edge + levelDetails.age;
};
_proto.computeLatency = function computeLatency() {
var liveEdge = this.estimateLiveEdge();
if (liveEdge === null) {
return null;
}
return liveEdge - this.currentTime;
};
_createClass(LatencyController, [{
key: "latency",
get: function get() {
return this._latency || 0;
}
}, {
key: "maxLatency",
get: function get() {
var config = this.config,
levelDetails = this.levelDetails;
if (config.liveMaxLatencyDuration !== undefined) {
return config.liveMaxLatencyDuration;
}
return levelDetails ? config.liveMaxLatencyDurationCount * levelDetails.targetduration : 0;
}
}, {
key: "targetLatency",
get: function get() {
var levelDetails = this.levelDetails;
if (levelDetails === null) {
return null;
}
var holdBack = levelDetails.holdBack,
partHoldBack = levelDetails.partHoldBack,
targetduration = levelDetails.targetduration;
var _this$config2 = this.config,
liveSyncDuration = _this$config2.liveSyncDuration,
liveSyncDurationCount = _this$config2.liveSyncDurationCount,
lowLatencyMode = _this$config2.lowLatencyMode;
var userConfig = this.hls.userConfig;
var targetLatency = lowLatencyMode ? partHoldBack || holdBack : holdBack;
if (userConfig.liveSyncDuration || userConfig.liveSyncDurationCount || targetLatency === 0) {
targetLatency = liveSyncDuration !== undefined ? liveSyncDuration : liveSyncDurationCount * targetduration;
}
var maxLiveSyncOnStallIncrease = targetduration;
var liveSyncOnStallIncrease = 1.0;
return targetLatency + Math.min(this.stallCount * liveSyncOnStallIncrease, maxLiveSyncOnStallIncrease);
}
}, {
key: "liveSyncPosition",
get: function get() {
var liveEdge = this.estimateLiveEdge();
var targetLatency = this.targetLatency;
var levelDetails = this.levelDetails;
if (liveEdge === null || targetLatency === null || levelDetails === null) {
return null;
}
var edge = levelDetails.edge;
var syncPosition = liveEdge - targetLatency - this.edgeStalled;
var min = edge - levelDetails.totalduration;
var max = edge - (this.config.lowLatencyMode && levelDetails.partTarget || levelDetails.targetduration);
return Math.min(Math.max(min, syncPosition), max);
}
}, {
key: "drift",
get: function get() {
var levelDetails = this.levelDetails;
if (levelDetails === null) {
return 1;
}
return levelDetails.drift;
}
}, {
key: "edgeStalled",
get: function get() {
var levelDetails = this.levelDetails;
if (levelDetails === null) {
return 0;
}
var maxLevelUpdateAge = (this.config.lowLatencyMode && levelDetails.partTarget || levelDetails.targetduration) * 3;
return Math.max(levelDetails.age - maxLevelUpdateAge, 0);
}
}, {
key: "forwardBufferLength",
get: function get() {
var media = this.media,
levelDetails = this.levelDetails;
if (!media || !levelDetails) {
return 0;
}
var bufferedRanges = media.buffered.length;
return bufferedRanges ? media.buffered.end(bufferedRanges - 1) : levelDetails.edge - this.currentTime;
}
}]);
return LatencyController;
}();
/***/ }),
/***/ "./src/controller/level-controller.ts":
/*!********************************************!*\
!*** ./src/controller/level-controller.ts ***!
\********************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return LevelController; });
/* harmony import */ var _types_level__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../types/level */ "./src/types/level.ts");
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
/* harmony import */ var _utils_codecs__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/codecs */ "./src/utils/codecs.ts");
/* harmony import */ var _level_helper__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./level-helper */ "./src/controller/level-helper.ts");
/* harmony import */ var _base_playlist_controller__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./base-playlist-controller */ "./src/controller/base-playlist-controller.ts");
/* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts");
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
/*
* Level Controller
*/
var chromeOrFirefox = /chrome|firefox/.test(navigator.userAgent.toLowerCase());
var LevelController = /*#__PURE__*/function (_BasePlaylistControll) {
_inheritsLoose(LevelController, _BasePlaylistControll);
function LevelController(hls) {
var _this;
_this = _BasePlaylistControll.call(this, hls, '[level-controller]') || this;
_this._levels = [];
_this._firstLevel = -1;
_this._startLevel = void 0;
_this.currentLevelIndex = -1;
_this.manualLevelIndex = -1;
_this.onParsedComplete = void 0;
_this._registerListeners();
return _this;
}
var _proto = LevelController.prototype;
_proto._registerListeners = function _registerListeners() {
var hls = this.hls;
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADED, this.onManifestLoaded, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_LOADED, this.onLevelLoaded, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_LOADED, this.onFragLoaded, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, this.onError, this);
};
_proto._unregisterListeners = function _unregisterListeners() {
var hls = this.hls;
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADED, this.onManifestLoaded, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_LOADED, this.onLevelLoaded, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_LOADED, this.onFragLoaded, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, this.onError, this);
};
_proto.destroy = function destroy() {
this._unregisterListeners();
this.manualLevelIndex = -1;
this._levels.length = 0;
_BasePlaylistControll.prototype.destroy.call(this);
};
_proto.startLoad = function startLoad() {
var levels = this._levels; // clean up live level details to force reload them, and reset load errors
levels.forEach(function (level) {
level.loadError = 0;
});
_BasePlaylistControll.prototype.startLoad.call(this);
};
_proto.onManifestLoaded = function onManifestLoaded(event, data) {
var levels = [];
var audioTracks = [];
var subtitleTracks = [];
var bitrateStart;
var levelSet = {};
var levelFromSet;
var resolutionFound = false;
var videoCodecFound = false;
var audioCodecFound = false; // regroup redundant levels together
data.levels.forEach(function (levelParsed) {
var attributes = levelParsed.attrs;
resolutionFound = resolutionFound || !!(levelParsed.width && levelParsed.height);
videoCodecFound = videoCodecFound || !!levelParsed.videoCodec;
audioCodecFound = audioCodecFound || !!levelParsed.audioCodec; // erase audio codec info if browser does not support mp4a.40.34.
// demuxer will autodetect codec and fallback to mpeg/audio
if (chromeOrFirefox && levelParsed.audioCodec && levelParsed.audioCodec.indexOf('mp4a.40.34') !== -1) {
levelParsed.audioCodec = undefined;
}
var levelKey = levelParsed.bitrate + "-" + levelParsed.attrs.RESOLUTION + "-" + levelParsed.attrs.CODECS;
levelFromSet = levelSet[levelKey];
if (!levelFromSet) {
levelFromSet = new _types_level__WEBPACK_IMPORTED_MODULE_0__["Level"](levelParsed);
levelSet[levelKey] = levelFromSet;
levels.push(levelFromSet);
} else {
levelFromSet.url.push(levelParsed.url);
}
if (attributes) {
if (attributes.AUDIO) {
Object(_level_helper__WEBPACK_IMPORTED_MODULE_4__["addGroupId"])(levelFromSet, 'audio', attributes.AUDIO);
}
if (attributes.SUBTITLES) {
Object(_level_helper__WEBPACK_IMPORTED_MODULE_4__["addGroupId"])(levelFromSet, 'text', attributes.SUBTITLES);
}
}
}); // remove audio-only level if we also have levels with video codecs or RESOLUTION signalled
if ((resolutionFound || videoCodecFound) && audioCodecFound) {
levels = levels.filter(function (_ref) {
var videoCodec = _ref.videoCodec,
width = _ref.width,
height = _ref.height;
return !!videoCodec || !!(width && height);
});
} // only keep levels with supported audio/video codecs
levels = levels.filter(function (_ref2) {
var audioCodec = _ref2.audioCodec,
videoCodec = _ref2.videoCodec;
return (!audioCodec || Object(_utils_codecs__WEBPACK_IMPORTED_MODULE_3__["isCodecSupportedInMp4"])(audioCodec, 'audio')) && (!videoCodec || Object(_utils_codecs__WEBPACK_IMPORTED_MODULE_3__["isCodecSupportedInMp4"])(videoCodec, 'video'));
});
if (data.audioTracks) {
audioTracks = data.audioTracks.filter(function (track) {
return !track.audioCodec || Object(_utils_codecs__WEBPACK_IMPORTED_MODULE_3__["isCodecSupportedInMp4"])(track.audioCodec, 'audio');
}); // Assign ids after filtering as array indices by group-id
Object(_level_helper__WEBPACK_IMPORTED_MODULE_4__["assignTrackIdsByGroup"])(audioTracks);
}
if (data.subtitles) {
subtitleTracks = data.subtitles;
Object(_level_helper__WEBPACK_IMPORTED_MODULE_4__["assignTrackIdsByGroup"])(subtitleTracks);
}
if (levels.length > 0) {
// start bitrate is the first bitrate of the manifest
bitrateStart = levels[0].bitrate; // sort level on bitrate
levels.sort(function (a, b) {
return a.bitrate - b.bitrate;
});
this._levels = levels; // find index of first level in sorted levels
for (var i = 0; i < levels.length; i++) {
if (levels[i].bitrate === bitrateStart) {
this._firstLevel = i;
this.log("manifest loaded, " + levels.length + " level(s) found, first bitrate: " + bitrateStart);
break;
}
} // Audio is only alternate if manifest include a URI along with the audio group tag,
// and this is not an audio-only stream where levels contain audio-only
var audioOnly = audioCodecFound && !videoCodecFound;
var edata = {
levels: levels,
audioTracks: audioTracks,
subtitleTracks: subtitleTracks,
firstLevel: this._firstLevel,
stats: data.stats,
audio: audioCodecFound,
video: videoCodecFound,
altAudio: !audioOnly && audioTracks.some(function (t) {
return !!t.url;
})
};
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_PARSED, edata); // Initiate loading after all controllers have received MANIFEST_PARSED
if (this.hls.config.autoStartLoad || this.hls.forceStartLoad) {
this.hls.startLoad(this.hls.config.startPosition);
}
} else {
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorTypes"].MEDIA_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].MANIFEST_INCOMPATIBLE_CODECS_ERROR,
fatal: true,
url: data.url,
reason: 'no level with compatible codecs found in manifest'
});
}
};
_proto.onError = function onError(event, data) {
_BasePlaylistControll.prototype.onError.call(this, event, data);
if (data.fatal) {
return;
} // Switch to redundant level when track fails to load
var context = data.context;
var level = this._levels[this.currentLevelIndex];
if (context && (context.type === _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].AUDIO_TRACK && level.audioGroupIds && context.groupId === level.audioGroupIds[level.urlId] || context.type === _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].SUBTITLE_TRACK && level.textGroupIds && context.groupId === level.textGroupIds[level.urlId])) {
this.redundantFailover(this.currentLevelIndex);
return;
}
var levelError = false;
var levelSwitch = true;
var levelIndex; // try to recover not fatal errors
switch (data.details) {
case _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].FRAG_LOAD_ERROR:
case _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].FRAG_LOAD_TIMEOUT:
case _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].KEY_LOAD_ERROR:
case _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].KEY_LOAD_TIMEOUT:
if (data.frag) {
var _level = this._levels[data.frag.level]; // Set levelIndex when we're out of fragment retries
if (_level) {
_level.fragmentError++;
if (_level.fragmentError > this.hls.config.fragLoadingMaxRetry) {
levelIndex = data.frag.level;
}
} else {
levelIndex = data.frag.level;
}
}
break;
case _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].LEVEL_LOAD_ERROR:
case _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].LEVEL_LOAD_TIMEOUT:
// Do not perform level switch if an error occurred using delivery directives
// Attempt to reload level without directives first
if (context) {
if (context.deliveryDirectives) {
levelSwitch = false;
}
levelIndex = context.level;
}
levelError = true;
break;
case _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].REMUX_ALLOC_ERROR:
levelIndex = data.level;
levelError = true;
break;
}
if (levelIndex !== undefined) {
this.recoverLevel(data, levelIndex, levelError, levelSwitch);
}
}
/**
* Switch to a redundant stream if any available.
* If redundant stream is not available, emergency switch down if ABR mode is enabled.
*/
;
_proto.recoverLevel = function recoverLevel(errorEvent, levelIndex, levelError, levelSwitch) {
var errorDetails = errorEvent.details;
var level = this._levels[levelIndex];
level.loadError++;
if (levelError) {
var retrying = this.retryLoadingOrFail(errorEvent);
if (retrying) {
// boolean used to inform stream controller not to switch back to IDLE on non fatal error
errorEvent.levelRetry = true;
} else {
this.currentLevelIndex = -1;
return;
}
}
if (levelSwitch) {
var redundantLevels = level.url.length; // Try redundant fail-over until level.loadError reaches redundantLevels
if (redundantLevels > 1 && level.loadError < redundantLevels) {
errorEvent.levelRetry = true;
this.redundantFailover(levelIndex);
} else if (this.manualLevelIndex === -1) {
// Search for available level in auto level selection mode, cycling from highest to lowest bitrate
var nextLevel = levelIndex === 0 ? this._levels.length - 1 : levelIndex - 1;
if (this.currentLevelIndex !== nextLevel && this._levels[nextLevel].loadError === 0) {
this.warn(errorDetails + ": switch to " + nextLevel);
errorEvent.levelRetry = true;
this.hls.nextAutoLevel = nextLevel;
}
}
}
};
_proto.redundantFailover = function redundantFailover(levelIndex) {
var level = this._levels[levelIndex];
var redundantLevels = level.url.length;
if (redundantLevels > 1) {
// Update the url id of all levels so that we stay on the same set of variants when level switching
var newUrlId = (level.urlId + 1) % redundantLevels;
this.warn("Switching to redundant URL-id " + newUrlId);
this._levels.forEach(function (level) {
level.urlId = newUrlId;
});
this.level = levelIndex;
}
} // reset errors on the successful load of a fragment
;
_proto.onFragLoaded = function onFragLoaded(event, _ref3) {
var frag = _ref3.frag;
if (frag !== undefined && frag.type === _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN) {
var level = this._levels[frag.level];
if (level !== undefined) {
level.fragmentError = 0;
level.loadError = 0;
}
}
};
_proto.onLevelLoaded = function onLevelLoaded(event, data) {
var _data$deliveryDirecti2;
var level = data.level,
details = data.details;
var curLevel = this._levels[level];
if (!curLevel) {
var _data$deliveryDirecti;
this.warn("Invalid level index " + level);
if ((_data$deliveryDirecti = data.deliveryDirectives) !== null && _data$deliveryDirecti !== void 0 && _data$deliveryDirecti.skip) {
details.deltaUpdateFailed = true;
}
return;
} // only process level loaded events matching with expected level
if (level === this.currentLevelIndex) {
// reset level load error counter on successful level loaded only if there is no issues with fragments
if (curLevel.fragmentError === 0) {
curLevel.loadError = 0;
this.retryCount = 0;
}
this.playlistLoaded(level, data, curLevel.details);
} else if ((_data$deliveryDirecti2 = data.deliveryDirectives) !== null && _data$deliveryDirecti2 !== void 0 && _data$deliveryDirecti2.skip) {
// received a delta playlist update that cannot be merged
details.deltaUpdateFailed = true;
}
};
_proto.onAudioTrackSwitched = function onAudioTrackSwitched(event, data) {
var currentLevel = this.hls.levels[this.currentLevelIndex];
if (!currentLevel) {
return;
}
if (currentLevel.audioGroupIds) {
var urlId = -1;
var audioGroupId = this.hls.audioTracks[data.id].groupId;
for (var i = 0; i < currentLevel.audioGroupIds.length; i++) {
if (currentLevel.audioGroupIds[i] === audioGroupId) {
urlId = i;
break;
}
}
if (urlId !== currentLevel.urlId) {
currentLevel.urlId = urlId;
this.startLoad();
}
}
};
_proto.loadPlaylist = function loadPlaylist(hlsUrlParameters) {
var level = this.currentLevelIndex;
var currentLevel = this._levels[level];
if (this.canLoad && currentLevel && currentLevel.url.length > 0) {
var id = currentLevel.urlId;
var url = currentLevel.url[id];
if (hlsUrlParameters) {
try {
url = hlsUrlParameters.addDirectives(url);
} catch (error) {
this.warn("Could not construct new URL with HLS Delivery Directives: " + error);
}
}
this.log("Attempt loading level index " + level + (hlsUrlParameters ? ' at sn ' + hlsUrlParameters.msn + ' part ' + hlsUrlParameters.part : '') + " with URL-id " + id + " " + url); // console.log('Current audio track group ID:', this.hls.audioTracks[this.hls.audioTrack].groupId);
// console.log('New video quality level audio group id:', levelObject.attrs.AUDIO, level);
this.clearTimer();
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_LOADING, {
url: url,
level: level,
id: id,
deliveryDirectives: hlsUrlParameters || null
});
}
};
_proto.removeLevel = function removeLevel(levelIndex, urlId) {
var filterLevelAndGroupByIdIndex = function filterLevelAndGroupByIdIndex(url, id) {
return id !== urlId;
};
var levels = this._levels.filter(function (level, index) {
if (index !== levelIndex) {
return true;
}
if (level.url.length > 1 && urlId !== undefined) {
level.url = level.url.filter(filterLevelAndGroupByIdIndex);
if (level.audioGroupIds) {
level.audioGroupIds = level.audioGroupIds.filter(filterLevelAndGroupByIdIndex);
}
if (level.textGroupIds) {
level.textGroupIds = level.textGroupIds.filter(filterLevelAndGroupByIdIndex);
}
level.urlId = 0;
return true;
}
return false;
}).map(function (level, index) {
var details = level.details;
if (details !== null && details !== void 0 && details.fragments) {
details.fragments.forEach(function (fragment) {
fragment.level = index;
});
}
return level;
});
this._levels = levels;
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVELS_UPDATED, {
levels: levels
});
};
_createClass(LevelController, [{
key: "levels",
get: function get() {
if (this._levels.length === 0) {
return null;
}
return this._levels;
}
}, {
key: "level",
get: function get() {
return this.currentLevelIndex;
},
set: function set(newLevel) {
var _levels$newLevel;
var levels = this._levels;
if (levels.length === 0) {
return;
}
if (this.currentLevelIndex === newLevel && (_levels$newLevel = levels[newLevel]) !== null && _levels$newLevel !== void 0 && _levels$newLevel.details) {
return;
} // check if level idx is valid
if (newLevel < 0 || newLevel >= levels.length) {
// invalid level id given, trigger error
var fatal = newLevel < 0;
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorTypes"].OTHER_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].LEVEL_SWITCH_ERROR,
level: newLevel,
fatal: fatal,
reason: 'invalid level idx'
});
if (fatal) {
return;
}
newLevel = Math.min(newLevel, levels.length - 1);
} // stopping live reloading timer if any
this.clearTimer();
var lastLevelIndex = this.currentLevelIndex;
var lastLevel = levels[lastLevelIndex];
var level = levels[newLevel];
this.log("switching to level " + newLevel + " from " + lastLevelIndex);
this.currentLevelIndex = newLevel;
var levelSwitchingData = _extends({}, level, {
level: newLevel,
maxBitrate: level.maxBitrate,
uri: level.uri,
urlId: level.urlId
}); // @ts-ignore
delete levelSwitchingData._urlId;
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_SWITCHING, levelSwitchingData); // check if we need to load playlist for this level
var levelDetails = level.details;
if (!levelDetails || levelDetails.live) {
// level not retrieved yet, or live playlist we need to (re)load it
var hlsUrlParameters = this.switchParams(level.uri, lastLevel === null || lastLevel === void 0 ? void 0 : lastLevel.details);
this.loadPlaylist(hlsUrlParameters);
}
}
}, {
key: "manualLevel",
get: function get() {
return this.manualLevelIndex;
},
set: function set(newLevel) {
this.manualLevelIndex = newLevel;
if (this._startLevel === undefined) {
this._startLevel = newLevel;
}
if (newLevel !== -1) {
this.level = newLevel;
}
}
}, {
key: "firstLevel",
get: function get() {
return this._firstLevel;
},
set: function set(newLevel) {
this._firstLevel = newLevel;
}
}, {
key: "startLevel",
get: function get() {
// hls.startLevel takes precedence over config.startLevel
// if none of these values are defined, fallback on this._firstLevel (first quality level appearing in variant manifest)
if (this._startLevel === undefined) {
var configStartLevel = this.hls.config.startLevel;
if (configStartLevel !== undefined) {
return configStartLevel;
} else {
return this._firstLevel;
}
} else {
return this._startLevel;
}
},
set: function set(newLevel) {
this._startLevel = newLevel;
}
}, {
key: "nextLoadLevel",
get: function get() {
if (this.manualLevelIndex !== -1) {
return this.manualLevelIndex;
} else {
return this.hls.nextAutoLevel;
}
},
set: function set(nextLevel) {
this.level = nextLevel;
if (this.manualLevelIndex === -1) {
this.hls.nextAutoLevel = nextLevel;
}
}
}]);
return LevelController;
}(_base_playlist_controller__WEBPACK_IMPORTED_MODULE_5__["default"]);
/***/ }),
/***/ "./src/controller/level-helper.ts":
/*!****************************************!*\
!*** ./src/controller/level-helper.ts ***!
\****************************************/
/*! exports provided: addGroupId, assignTrackIdsByGroup, updatePTS, updateFragPTSDTS, mergeDetails, mapPartIntersection, mapFragmentIntersection, adjustSliding, addSliding, computeReloadInterval, getFragmentWithSN, getPartWith */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "addGroupId", function() { return addGroupId; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "assignTrackIdsByGroup", function() { return assignTrackIdsByGroup; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updatePTS", function() { return updatePTS; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateFragPTSDTS", function() { return updateFragPTSDTS; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mergeDetails", function() { return mergeDetails; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mapPartIntersection", function() { return mapPartIntersection; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mapFragmentIntersection", function() { return mapFragmentIntersection; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "adjustSliding", function() { return adjustSliding; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "addSliding", function() { return addSliding; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "computeReloadInterval", function() { return computeReloadInterval; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getFragmentWithSN", function() { return getFragmentWithSN; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getPartWith", function() { return getPartWith; });
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/**
* @module LevelHelper
* Providing methods dealing with playlist sliding and drift
* */
function addGroupId(level, type, id) {
switch (type) {
case 'audio':
if (!level.audioGroupIds) {
level.audioGroupIds = [];
}
level.audioGroupIds.push(id);
break;
case 'text':
if (!level.textGroupIds) {
level.textGroupIds = [];
}
level.textGroupIds.push(id);
break;
}
}
function assignTrackIdsByGroup(tracks) {
var groups = {};
tracks.forEach(function (track) {
var groupId = track.groupId || '';
track.id = groups[groupId] = groups[groupId] || 0;
groups[groupId]++;
});
}
function updatePTS(fragments, fromIdx, toIdx) {
var fragFrom = fragments[fromIdx];
var fragTo = fragments[toIdx];
updateFromToPTS(fragFrom, fragTo);
}
function updateFromToPTS(fragFrom, fragTo) {
var fragToPTS = fragTo.startPTS; // if we know startPTS[toIdx]
if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(fragToPTS)) {
// update fragment duration.
// it helps to fix drifts between playlist reported duration and fragment real duration
var duration = 0;
var frag;
if (fragTo.sn > fragFrom.sn) {
duration = fragToPTS - fragFrom.start;
frag = fragFrom;
} else {
duration = fragFrom.start - fragToPTS;
frag = fragTo;
} // TODO? Drift can go either way, or the playlist could be completely accurate
// console.assert(duration > 0,
// `duration of ${duration} computed for frag ${frag.sn}, level ${frag.level}, there should be some duration drift between playlist and fragment!`);
if (frag.duration !== duration) {
frag.duration = duration;
} // we dont know startPTS[toIdx]
} else if (fragTo.sn > fragFrom.sn) {
var contiguous = fragFrom.cc === fragTo.cc; // TODO: With part-loading end/durations we need to confirm the whole fragment is loaded before using (or setting) minEndPTS
if (contiguous && fragFrom.minEndPTS) {
fragTo.start = fragFrom.start + (fragFrom.minEndPTS - fragFrom.start);
} else {
fragTo.start = fragFrom.start + fragFrom.duration;
}
} else {
fragTo.start = Math.max(fragFrom.start - fragTo.duration, 0);
}
}
function updateFragPTSDTS(details, frag, startPTS, endPTS, startDTS, endDTS) {
var parsedMediaDuration = endPTS - startPTS;
if (parsedMediaDuration <= 0) {
_utils_logger__WEBPACK_IMPORTED_MODULE_1__["logger"].warn('Fragment should have a positive duration', frag);
endPTS = startPTS + frag.duration;
endDTS = startDTS + frag.duration;
}
var maxStartPTS = startPTS;
var minEndPTS = endPTS;
var fragStartPts = frag.startPTS;
var fragEndPts = frag.endPTS;
if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(fragStartPts)) {
// delta PTS between audio and video
var deltaPTS = Math.abs(fragStartPts - startPTS);
if (!Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(frag.deltaPTS)) {
frag.deltaPTS = deltaPTS;
} else {
frag.deltaPTS = Math.max(deltaPTS, frag.deltaPTS);
}
maxStartPTS = Math.max(startPTS, fragStartPts);
startPTS = Math.min(startPTS, fragStartPts);
startDTS = Math.min(startDTS, frag.startDTS);
minEndPTS = Math.min(endPTS, fragEndPts);
endPTS = Math.max(endPTS, fragEndPts);
endDTS = Math.max(endDTS, frag.endDTS);
}
frag.duration = endPTS - startPTS;
var drift = startPTS - frag.start;
frag.appendedPTS = endPTS;
frag.start = frag.startPTS = startPTS;
frag.maxStartPTS = maxStartPTS;
frag.startDTS = startDTS;
frag.endPTS = endPTS;
frag.minEndPTS = minEndPTS;
frag.endDTS = endDTS;
var sn = frag.sn; // 'initSegment'
// exit if sn out of range
if (!details || sn < details.startSN || sn > details.endSN) {
return 0;
}
var i;
var fragIdx = sn - details.startSN;
var fragments = details.fragments; // update frag reference in fragments array
// rationale is that fragments array might not contain this frag object.
// this will happen if playlist has been refreshed between frag loading and call to updateFragPTSDTS()
// if we don't update frag, we won't be able to propagate PTS info on the playlist
// resulting in invalid sliding computation
fragments[fragIdx] = frag; // adjust fragment PTS/duration from seqnum-1 to frag 0
for (i = fragIdx; i > 0; i--) {
updateFromToPTS(fragments[i], fragments[i - 1]);
} // adjust fragment PTS/duration from seqnum to last frag
for (i = fragIdx; i < fragments.length - 1; i++) {
updateFromToPTS(fragments[i], fragments[i + 1]);
}
if (details.fragmentHint) {
updateFromToPTS(fragments[fragments.length - 1], details.fragmentHint);
}
details.PTSKnown = details.alignedSliding = true;
return drift;
}
function mergeDetails(oldDetails, newDetails) {
// Track the last initSegment processed. Initialize it to the last one on the timeline.
var currentInitSegment = null;
var oldFragments = oldDetails.fragments;
for (var i = oldFragments.length - 1; i >= 0; i--) {
var oldInit = oldFragments[i].initSegment;
if (oldInit) {
currentInitSegment = oldInit;
break;
}
}
if (oldDetails.fragmentHint) {
// prevent PTS and duration from being adjusted on the next hint
delete oldDetails.fragmentHint.endPTS;
} // check if old/new playlists have fragments in common
// loop through overlapping SN and update startPTS , cc, and duration if any found
var ccOffset = 0;
var PTSFrag;
mapFragmentIntersection(oldDetails, newDetails, function (oldFrag, newFrag) {
var _currentInitSegment;
if (oldFrag.relurl) {
// Do not compare CC if the old fragment has no url. This is a level.fragmentHint used by LL-HLS parts.
// It maybe be off by 1 if it was created before any parts or discontinuity tags were appended to the end
// of the playlist.
ccOffset = oldFrag.cc - newFrag.cc;
}
if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(oldFrag.startPTS) && Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(oldFrag.endPTS)) {
newFrag.start = newFrag.startPTS = oldFrag.startPTS;
newFrag.startDTS = oldFrag.startDTS;
newFrag.appendedPTS = oldFrag.appendedPTS;
newFrag.maxStartPTS = oldFrag.maxStartPTS;
newFrag.endPTS = oldFrag.endPTS;
newFrag.endDTS = oldFrag.endDTS;
newFrag.minEndPTS = oldFrag.minEndPTS;
newFrag.duration = oldFrag.endPTS - oldFrag.startPTS;
if (newFrag.duration) {
PTSFrag = newFrag;
} // PTS is known when any segment has startPTS and endPTS
newDetails.PTSKnown = newDetails.alignedSliding = true;
}
newFrag.elementaryStreams = oldFrag.elementaryStreams;
newFrag.loader = oldFrag.loader;
newFrag.stats = oldFrag.stats;
newFrag.urlId = oldFrag.urlId;
if (oldFrag.initSegment) {
newFrag.initSegment = oldFrag.initSegment;
currentInitSegment = oldFrag.initSegment;
} else if (!newFrag.initSegment || newFrag.initSegment.relurl == ((_currentInitSegment = currentInitSegment) === null || _currentInitSegment === void 0 ? void 0 : _currentInitSegment.relurl)) {
newFrag.initSegment = currentInitSegment;
}
});
if (newDetails.skippedSegments) {
newDetails.deltaUpdateFailed = newDetails.fragments.some(function (frag) {
return !frag;
});
if (newDetails.deltaUpdateFailed) {
_utils_logger__WEBPACK_IMPORTED_MODULE_1__["logger"].warn('[level-helper] Previous playlist missing segments skipped in delta playlist');
for (var _i = newDetails.skippedSegments; _i--;) {
newDetails.fragments.shift();
}
newDetails.startSN = newDetails.fragments[0].sn;
newDetails.startCC = newDetails.fragments[0].cc;
}
}
var newFragments = newDetails.fragments;
if (ccOffset) {
_utils_logger__WEBPACK_IMPORTED_MODULE_1__["logger"].warn('discontinuity sliding from playlist, take drift into account');
for (var _i2 = 0; _i2 < newFragments.length; _i2++) {
newFragments[_i2].cc += ccOffset;
}
}
if (newDetails.skippedSegments) {
newDetails.startCC = newDetails.fragments[0].cc;
} // Merge parts
mapPartIntersection(oldDetails.partList, newDetails.partList, function (oldPart, newPart) {
newPart.elementaryStreams = oldPart.elementaryStreams;
newPart.stats = oldPart.stats;
}); // if at least one fragment contains PTS info, recompute PTS information for all fragments
if (PTSFrag) {
updateFragPTSDTS(newDetails, PTSFrag, PTSFrag.startPTS, PTSFrag.endPTS, PTSFrag.startDTS, PTSFrag.endDTS);
} else {
// ensure that delta is within oldFragments range
// also adjust sliding in case delta is 0 (we could have old=[50-60] and new=old=[50-61])
// in that case we also need to adjust start offset of all fragments
adjustSliding(oldDetails, newDetails);
}
if (newFragments.length) {
newDetails.totalduration = newDetails.edge - newFragments[0].start;
}
newDetails.driftStartTime = oldDetails.driftStartTime;
newDetails.driftStart = oldDetails.driftStart;
var advancedDateTime = newDetails.advancedDateTime;
if (newDetails.advanced && advancedDateTime) {
var edge = newDetails.edge;
if (!newDetails.driftStart) {
newDetails.driftStartTime = advancedDateTime;
newDetails.driftStart = edge;
}
newDetails.driftEndTime = advancedDateTime;
newDetails.driftEnd = edge;
} else {
newDetails.driftEndTime = oldDetails.driftEndTime;
newDetails.driftEnd = oldDetails.driftEnd;
newDetails.advancedDateTime = oldDetails.advancedDateTime;
}
}
function mapPartIntersection(oldParts, newParts, intersectionFn) {
if (oldParts && newParts) {
var delta = 0;
for (var i = 0, len = oldParts.length; i <= len; i++) {
var _oldPart = oldParts[i];
var _newPart = newParts[i + delta];
if (_oldPart && _newPart && _oldPart.index === _newPart.index && _oldPart.fragment.sn === _newPart.fragment.sn) {
intersectionFn(_oldPart, _newPart);
} else {
delta--;
}
}
}
}
function mapFragmentIntersection(oldDetails, newDetails, intersectionFn) {
var skippedSegments = newDetails.skippedSegments;
var start = Math.max(oldDetails.startSN, newDetails.startSN) - newDetails.startSN;
var end = (oldDetails.fragmentHint ? 1 : 0) + (skippedSegments ? newDetails.endSN : Math.min(oldDetails.endSN, newDetails.endSN)) - newDetails.startSN;
var delta = newDetails.startSN - oldDetails.startSN;
var newFrags = newDetails.fragmentHint ? newDetails.fragments.concat(newDetails.fragmentHint) : newDetails.fragments;
var oldFrags = oldDetails.fragmentHint ? oldDetails.fragments.concat(oldDetails.fragmentHint) : oldDetails.fragments;
for (var i = start; i <= end; i++) {
var _oldFrag = oldFrags[delta + i];
var _newFrag = newFrags[i];
if (skippedSegments && !_newFrag && i < skippedSegments) {
// Fill in skipped segments in delta playlist
_newFrag = newDetails.fragments[i] = _oldFrag;
}
if (_oldFrag && _newFrag) {
intersectionFn(_oldFrag, _newFrag);
}
}
}
function adjustSliding(oldDetails, newDetails) {
var delta = newDetails.startSN + newDetails.skippedSegments - oldDetails.startSN;
var oldFragments = oldDetails.fragments;
if (delta < 0 || delta >= oldFragments.length) {
return;
}
addSliding(newDetails, oldFragments[delta].start);
}
function addSliding(details, start) {
if (start) {
var fragments = details.fragments;
for (var i = details.skippedSegments; i < fragments.length; i++) {
fragments[i].start += start;
}
if (details.fragmentHint) {
details.fragmentHint.start += start;
}
}
}
function computeReloadInterval(newDetails, stats) {
var reloadInterval = 1000 * newDetails.levelTargetDuration;
var reloadIntervalAfterMiss = reloadInterval / 2;
var timeSinceLastModified = newDetails.age;
var useLastModified = timeSinceLastModified > 0 && timeSinceLastModified < reloadInterval * 3;
var roundTrip = stats.loading.end - stats.loading.start;
var estimatedTimeUntilUpdate;
var availabilityDelay = newDetails.availabilityDelay; // let estimate = 'average';
if (newDetails.updated === false) {
if (useLastModified) {
// estimate = 'miss round trip';
// We should have had a hit so try again in the time it takes to get a response,
// but no less than 1/3 second.
var minRetry = 333 * newDetails.misses;
estimatedTimeUntilUpdate = Math.max(Math.min(reloadIntervalAfterMiss, roundTrip * 2), minRetry);
newDetails.availabilityDelay = (newDetails.availabilityDelay || 0) + estimatedTimeUntilUpdate;
} else {
// estimate = 'miss half average';
// follow HLS Spec, If the client reloads a Playlist file and finds that it has not
// changed then it MUST wait for a period of one-half the target
// duration before retrying.
estimatedTimeUntilUpdate = reloadIntervalAfterMiss;
}
} else if (useLastModified) {
// estimate = 'next modified date';
// Get the closest we've been to timeSinceLastModified on update
availabilityDelay = Math.min(availabilityDelay || reloadInterval / 2, timeSinceLastModified);
newDetails.availabilityDelay = availabilityDelay;
estimatedTimeUntilUpdate = availabilityDelay + reloadInterval - timeSinceLastModified;
} else {
estimatedTimeUntilUpdate = reloadInterval - roundTrip;
} // console.log(`[computeReloadInterval] live reload ${newDetails.updated ? 'REFRESHED' : 'MISSED'}`,
// '\n method', estimate,
// '\n estimated time until update =>', estimatedTimeUntilUpdate,
// '\n average target duration', reloadInterval,
// '\n time since modified', timeSinceLastModified,
// '\n time round trip', roundTrip,
// '\n availability delay', availabilityDelay);
return Math.round(estimatedTimeUntilUpdate);
}
function getFragmentWithSN(level, sn, fragCurrent) {
if (!level || !level.details) {
return null;
}
var levelDetails = level.details;
var fragment = levelDetails.fragments[sn - levelDetails.startSN];
if (fragment) {
return fragment;
}
fragment = levelDetails.fragmentHint;
if (fragment && fragment.sn === sn) {
return fragment;
}
if (sn < levelDetails.startSN && fragCurrent && fragCurrent.sn === sn) {
return fragCurrent;
}
return null;
}
function getPartWith(level, sn, partIndex) {
if (!level || !level.details) {
return null;
}
var partList = level.details.partList;
if (partList) {
for (var i = partList.length; i--;) {
var part = partList[i];
if (part.index === partIndex && part.fragment.sn === sn) {
return part;
}
}
}
return null;
}
/***/ }),
/***/ "./src/controller/stream-controller.ts":
/*!*********************************************!*\
!*** ./src/controller/stream-controller.ts ***!
\*********************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return StreamController; });
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./base-stream-controller */ "./src/controller/base-stream-controller.ts");
/* harmony import */ var _is_supported__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../is-supported */ "./src/is-supported.ts");
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/buffer-helper */ "./src/utils/buffer-helper.ts");
/* harmony import */ var _fragment_tracker__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./fragment-tracker */ "./src/controller/fragment-tracker.ts");
/* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts");
/* harmony import */ var _loader_fragment__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../loader/fragment */ "./src/loader/fragment.ts");
/* harmony import */ var _demux_transmuxer_interface__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../demux/transmuxer-interface */ "./src/demux/transmuxer-interface.ts");
/* harmony import */ var _types_transmuxer__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../types/transmuxer */ "./src/types/transmuxer.ts");
/* harmony import */ var _gap_controller__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./gap-controller */ "./src/controller/gap-controller.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
var TICK_INTERVAL = 100; // how often to tick in ms
var StreamController = /*#__PURE__*/function (_BaseStreamController) {
_inheritsLoose(StreamController, _BaseStreamController);
function StreamController(hls, fragmentTracker) {
var _this;
_this = _BaseStreamController.call(this, hls, fragmentTracker, '[stream-controller]') || this;
_this.audioCodecSwap = false;
_this.gapController = null;
_this.level = -1;
_this._forceStartLoad = false;
_this.altAudio = false;
_this.audioOnly = false;
_this.fragPlaying = null;
_this.onvplaying = null;
_this.onvseeked = null;
_this.fragLastKbps = 0;
_this.stalled = false;
_this.couldBacktrack = false;
_this.audioCodecSwitch = false;
_this.videoBuffer = null;
_this._registerListeners();
return _this;
}
var _proto = StreamController.prototype;
_proto._registerListeners = function _registerListeners() {
var hls = this.hls;
hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].MANIFEST_LOADING, this.onManifestLoading, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].MANIFEST_PARSED, this.onManifestParsed, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].LEVEL_LOADING, this.onLevelLoading, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].LEVEL_LOADED, this.onLevelLoaded, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].FRAG_LOAD_EMERGENCY_ABORTED, this.onFragLoadEmergencyAborted, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].ERROR, this.onError, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].BUFFER_CREATED, this.onBufferCreated, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].BUFFER_FLUSHED, this.onBufferFlushed, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].LEVELS_UPDATED, this.onLevelsUpdated, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].FRAG_BUFFERED, this.onFragBuffered, this);
};
_proto._unregisterListeners = function _unregisterListeners() {
var hls = this.hls;
hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].MANIFEST_LOADING, this.onManifestLoading, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].MANIFEST_PARSED, this.onManifestParsed, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].LEVEL_LOADED, this.onLevelLoaded, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].FRAG_LOAD_EMERGENCY_ABORTED, this.onFragLoadEmergencyAborted, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].ERROR, this.onError, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].BUFFER_CREATED, this.onBufferCreated, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].BUFFER_FLUSHED, this.onBufferFlushed, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].LEVELS_UPDATED, this.onLevelsUpdated, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].FRAG_BUFFERED, this.onFragBuffered, this);
};
_proto.onHandlerDestroying = function onHandlerDestroying() {
this._unregisterListeners();
this.onMediaDetaching();
};
_proto.startLoad = function startLoad(startPosition) {
if (this.levels) {
var lastCurrentTime = this.lastCurrentTime,
hls = this.hls;
this.stopLoad();
this.setInterval(TICK_INTERVAL);
this.level = -1;
this.fragLoadError = 0;
if (!this.startFragRequested) {
// determine load level
var startLevel = hls.startLevel;
if (startLevel === -1) {
if (hls.config.testBandwidth) {
// -1 : guess start Level by doing a bitrate test by loading first fragment of lowest quality level
startLevel = 0;
this.bitrateTest = true;
} else {
startLevel = hls.nextAutoLevel;
}
} // set new level to playlist loader : this will trigger start level load
// hls.nextLoadLevel remains until it is set to a new value or until a new frag is successfully loaded
this.level = hls.nextLoadLevel = startLevel;
this.loadedmetadata = false;
} // if startPosition undefined but lastCurrentTime set, set startPosition to last currentTime
if (lastCurrentTime > 0 && startPosition === -1) {
this.log("Override startPosition with lastCurrentTime @" + lastCurrentTime.toFixed(3));
startPosition = lastCurrentTime;
}
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
this.nextLoadPosition = this.startPosition = this.lastCurrentTime = startPosition;
this.tick();
} else {
this._forceStartLoad = true;
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].STOPPED;
}
};
_proto.stopLoad = function stopLoad() {
this._forceStartLoad = false;
_BaseStreamController.prototype.stopLoad.call(this);
};
_proto.doTick = function doTick() {
switch (this.state) {
case _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE:
this.doTickIdle();
break;
case _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_LEVEL:
{
var _levels$level;
var levels = this.levels,
level = this.level;
var details = levels === null || levels === void 0 ? void 0 : (_levels$level = levels[level]) === null || _levels$level === void 0 ? void 0 : _levels$level.details;
if (details && (!details.live || this.levelLastLoaded === this.level)) {
if (this.waitForCdnTuneIn(details)) {
break;
}
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
break;
}
break;
}
case _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].FRAG_LOADING_WAITING_RETRY:
{
var _this$media;
var now = self.performance.now();
var retryDate = this.retryDate; // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading
if (!retryDate || now >= retryDate || (_this$media = this.media) !== null && _this$media !== void 0 && _this$media.seeking) {
this.log('retryDate reached, switch back to IDLE state');
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
}
}
break;
default:
break;
} // check buffer
// check/update current fragment
this.onTickEnd();
};
_proto.onTickEnd = function onTickEnd() {
_BaseStreamController.prototype.onTickEnd.call(this);
this.checkBuffer();
this.checkFragmentChanged();
};
_proto.doTickIdle = function doTickIdle() {
var _frag$decryptdata, _frag$decryptdata2;
var hls = this.hls,
levelLastLoaded = this.levelLastLoaded,
levels = this.levels,
media = this.media;
var config = hls.config,
level = hls.nextLoadLevel; // if start level not parsed yet OR
// if video not attached AND start fragment already requested OR start frag prefetch not enabled
// exit loop, as we either need more info (level not parsed) or we need media to be attached to load new fragment
if (levelLastLoaded === null || !media && (this.startFragRequested || !config.startFragPrefetch)) {
return;
} // If the "main" level is audio-only but we are loading an alternate track in the same group, do not load anything
if (this.altAudio && this.audioOnly) {
return;
}
if (!levels || !levels[level]) {
return;
}
var levelInfo = levels[level]; // if buffer length is less than maxBufLen try to load a new fragment
// set next load level : this will trigger a playlist load if needed
this.level = hls.nextLoadLevel = level;
var levelDetails = levelInfo.details; // if level info not retrieved yet, switch state and wait for level retrieval
// if live playlist, ensure that new playlist has been refreshed to avoid loading/try to load
// a useless and outdated fragment (that might even introduce load error if it is already out of the live playlist)
if (!levelDetails || this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_LEVEL || levelDetails.live && this.levelLastLoaded !== level) {
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_LEVEL;
return;
}
var bufferInfo = this.getFwdBufferInfo(this.mediaBuffer ? this.mediaBuffer : media, _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN);
if (bufferInfo === null) {
return;
}
var bufferLen = bufferInfo.len; // compute max Buffer Length that we could get from this load level, based on level bitrate. don't buffer more than 60 MB and more than 30s
var maxBufLen = this.getMaxBufferLength(levelInfo.maxBitrate); // Stay idle if we are still with buffer margins
if (bufferLen >= maxBufLen) {
return;
}
if (this._streamEnded(bufferInfo, levelDetails)) {
var data = {};
if (this.altAudio) {
data.type = 'video';
}
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].BUFFER_EOS, data);
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].ENDED;
return;
}
var targetBufferTime = bufferInfo.end;
var frag = this.getNextFragment(targetBufferTime, levelDetails); // Avoid backtracking after seeking or switching by loading an earlier segment in streams that could backtrack
if (this.couldBacktrack && !this.fragPrevious && frag && frag.sn !== 'initSegment') {
var fragIdx = frag.sn - levelDetails.startSN;
if (fragIdx > 1) {
frag = levelDetails.fragments[fragIdx - 1];
this.fragmentTracker.removeFragment(frag);
}
} // Avoid loop loading by using nextLoadPosition set for backtracking
if (frag && this.fragmentTracker.getState(frag) === _fragment_tracker__WEBPACK_IMPORTED_MODULE_5__["FragmentState"].OK && this.nextLoadPosition > targetBufferTime) {
// Cleanup the fragment tracker before trying to find the next unbuffered fragment
var type = this.audioOnly && !this.altAudio ? _loader_fragment__WEBPACK_IMPORTED_MODULE_7__["ElementaryStreamTypes"].AUDIO : _loader_fragment__WEBPACK_IMPORTED_MODULE_7__["ElementaryStreamTypes"].VIDEO;
this.afterBufferFlushed(media, type, _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN);
frag = this.getNextFragment(this.nextLoadPosition, levelDetails);
}
if (!frag) {
return;
}
if (frag.initSegment && !frag.initSegment.data && !this.bitrateTest) {
frag = frag.initSegment;
} // We want to load the key if we're dealing with an identity key, because we will decrypt
// this content using the key we fetch. Other keys will be handled by the DRM CDM via EME.
if (((_frag$decryptdata = frag.decryptdata) === null || _frag$decryptdata === void 0 ? void 0 : _frag$decryptdata.keyFormat) === 'identity' && !((_frag$decryptdata2 = frag.decryptdata) !== null && _frag$decryptdata2 !== void 0 && _frag$decryptdata2.key)) {
this.loadKey(frag, levelDetails);
} else {
this.loadFragment(frag, levelDetails, targetBufferTime);
}
};
_proto.loadFragment = function loadFragment(frag, levelDetails, targetBufferTime) {
var _this$media2;
// Check if fragment is not loaded
var fragState = this.fragmentTracker.getState(frag);
this.fragCurrent = frag; // Use data from loaded backtracked fragment if available
if (fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_5__["FragmentState"].BACKTRACKED) {
var data = this.fragmentTracker.getBacktrackData(frag);
if (data) {
this._handleFragmentLoadProgress(data);
this._handleFragmentLoadComplete(data);
return;
} else {
fragState = _fragment_tracker__WEBPACK_IMPORTED_MODULE_5__["FragmentState"].NOT_LOADED;
}
}
if (fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_5__["FragmentState"].NOT_LOADED || fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_5__["FragmentState"].PARTIAL) {
if (frag.sn === 'initSegment') {
this._loadInitSegment(frag);
} else if (this.bitrateTest) {
frag.bitrateTest = true;
this.log("Fragment " + frag.sn + " of level " + frag.level + " is being downloaded to test bitrate and will not be buffered");
this._loadBitrateTestFrag(frag);
} else {
this.startFragRequested = true;
_BaseStreamController.prototype.loadFragment.call(this, frag, levelDetails, targetBufferTime);
}
} else if (fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_5__["FragmentState"].APPENDING) {
// Lower the buffer size and try again
if (this.reduceMaxBufferLength(frag.duration)) {
this.fragmentTracker.removeFragment(frag);
}
} else if (((_this$media2 = this.media) === null || _this$media2 === void 0 ? void 0 : _this$media2.buffered.length) === 0) {
// Stop gap for bad tracker / buffer flush behavior
this.fragmentTracker.removeAllFragments();
}
};
_proto.getAppendedFrag = function getAppendedFrag(position) {
var fragOrPart = this.fragmentTracker.getAppendedFrag(position, _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN);
if (fragOrPart && 'fragment' in fragOrPart) {
return fragOrPart.fragment;
}
return fragOrPart;
};
_proto.getBufferedFrag = function getBufferedFrag(position) {
return this.fragmentTracker.getBufferedFrag(position, _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN);
};
_proto.followingBufferedFrag = function followingBufferedFrag(frag) {
if (frag) {
// try to get range of next fragment (500ms after this range)
return this.getBufferedFrag(frag.end + 0.5);
}
return null;
}
/*
on immediate level switch :
- pause playback if playing
- cancel any pending load request
- and trigger a buffer flush
*/
;
_proto.immediateLevelSwitch = function immediateLevelSwitch() {
this.abortCurrentFrag();
this.flushMainBuffer(0, Number.POSITIVE_INFINITY);
}
/**
* try to switch ASAP without breaking video playback:
* in order to ensure smooth but quick level switching,
* we need to find the next flushable buffer range
* we should take into account new segment fetch time
*/
;
_proto.nextLevelSwitch = function nextLevelSwitch() {
var levels = this.levels,
media = this.media; // ensure that media is defined and that metadata are available (to retrieve currentTime)
if (media !== null && media !== void 0 && media.readyState) {
var fetchdelay;
var fragPlayingCurrent = this.getAppendedFrag(media.currentTime);
if (fragPlayingCurrent && fragPlayingCurrent.start > 1) {
// flush buffer preceding current fragment (flush until current fragment start offset)
// minus 1s to avoid video freezing, that could happen if we flush keyframe of current video ...
this.flushMainBuffer(0, fragPlayingCurrent.start - 1);
}
if (!media.paused && levels) {
// add a safety delay of 1s
var nextLevelId = this.hls.nextLoadLevel;
var nextLevel = levels[nextLevelId];
var fragLastKbps = this.fragLastKbps;
if (fragLastKbps && this.fragCurrent) {
fetchdelay = this.fragCurrent.duration * nextLevel.maxBitrate / (1000 * fragLastKbps) + 1;
} else {
fetchdelay = 0;
}
} else {
fetchdelay = 0;
} // this.log('fetchdelay:'+fetchdelay);
// find buffer range that will be reached once new fragment will be fetched
var bufferedFrag = this.getBufferedFrag(media.currentTime + fetchdelay);
if (bufferedFrag) {
// we can flush buffer range following this one without stalling playback
var nextBufferedFrag = this.followingBufferedFrag(bufferedFrag);
if (nextBufferedFrag) {
// if we are here, we can also cancel any loading/demuxing in progress, as they are useless
this.abortCurrentFrag(); // start flush position is in next buffered frag. Leave some padding for non-independent segments and smoother playback.
var maxStart = nextBufferedFrag.maxStartPTS ? nextBufferedFrag.maxStartPTS : nextBufferedFrag.start;
var fragDuration = nextBufferedFrag.duration;
var startPts = Math.max(bufferedFrag.end, maxStart + Math.min(Math.max(fragDuration - this.config.maxFragLookUpTolerance, fragDuration * 0.5), fragDuration * 0.75));
this.flushMainBuffer(startPts, Number.POSITIVE_INFINITY);
}
}
}
};
_proto.abortCurrentFrag = function abortCurrentFrag() {
var fragCurrent = this.fragCurrent;
this.fragCurrent = null;
if (fragCurrent !== null && fragCurrent !== void 0 && fragCurrent.loader) {
fragCurrent.loader.abort();
}
if (this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].KEY_LOADING) {
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
}
this.nextLoadPosition = this.getLoadPosition();
};
_proto.flushMainBuffer = function flushMainBuffer(startOffset, endOffset) {
_BaseStreamController.prototype.flushMainBuffer.call(this, startOffset, endOffset, this.altAudio ? 'video' : null);
};
_proto.onMediaAttached = function onMediaAttached(event, data) {
_BaseStreamController.prototype.onMediaAttached.call(this, event, data);
var media = data.media;
this.onvplaying = this.onMediaPlaying.bind(this);
this.onvseeked = this.onMediaSeeked.bind(this);
media.addEventListener('playing', this.onvplaying);
media.addEventListener('seeked', this.onvseeked);
this.gapController = new _gap_controller__WEBPACK_IMPORTED_MODULE_10__["default"](this.config, media, this.fragmentTracker, this.hls);
};
_proto.onMediaDetaching = function onMediaDetaching() {
var media = this.media;
if (media) {
media.removeEventListener('playing', this.onvplaying);
media.removeEventListener('seeked', this.onvseeked);
this.onvplaying = this.onvseeked = null;
this.videoBuffer = null;
}
this.fragPlaying = null;
if (this.gapController) {
this.gapController.destroy();
this.gapController = null;
}
_BaseStreamController.prototype.onMediaDetaching.call(this);
};
_proto.onMediaPlaying = function onMediaPlaying() {
// tick to speed up FRAG_CHANGED triggering
this.tick();
};
_proto.onMediaSeeked = function onMediaSeeked() {
var media = this.media;
var currentTime = media ? media.currentTime : null;
if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(currentTime)) {
this.log("Media seeked to " + currentTime.toFixed(3));
} // tick to speed up FRAG_CHANGED triggering
this.tick();
};
_proto.onManifestLoading = function onManifestLoading() {
// reset buffer on manifest loading
this.log('Trigger BUFFER_RESET');
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].BUFFER_RESET, undefined);
this.fragmentTracker.removeAllFragments();
this.couldBacktrack = this.stalled = false;
this.startPosition = this.lastCurrentTime = 0;
this.fragPlaying = null;
};
_proto.onManifestParsed = function onManifestParsed(event, data) {
var aac = false;
var heaac = false;
var codec;
data.levels.forEach(function (level) {
// detect if we have different kind of audio codecs used amongst playlists
codec = level.audioCodec;
if (codec) {
if (codec.indexOf('mp4a.40.2') !== -1) {
aac = true;
}
if (codec.indexOf('mp4a.40.5') !== -1) {
heaac = true;
}
}
});
this.audioCodecSwitch = aac && heaac && !Object(_is_supported__WEBPACK_IMPORTED_MODULE_2__["changeTypeSupported"])();
if (this.audioCodecSwitch) {
this.log('Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC');
}
this.levels = data.levels;
this.startFragRequested = false;
};
_proto.onLevelLoading = function onLevelLoading(event, data) {
var levels = this.levels;
if (!levels || this.state !== _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE) {
return;
}
var level = levels[data.level];
if (!level.details || level.details.live && this.levelLastLoaded !== data.level || this.waitForCdnTuneIn(level.details)) {
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_LEVEL;
}
};
_proto.onLevelLoaded = function onLevelLoaded(event, data) {
var _curLevel$details;
var levels = this.levels;
var newLevelId = data.level;
var newDetails = data.details;
var duration = newDetails.totalduration;
if (!levels) {
this.warn("Levels were reset while loading level " + newLevelId);
return;
}
this.log("Level " + newLevelId + " loaded [" + newDetails.startSN + "," + newDetails.endSN + "], cc [" + newDetails.startCC + ", " + newDetails.endCC + "] duration:" + duration);
var fragCurrent = this.fragCurrent;
if (fragCurrent && (this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].FRAG_LOADING || this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].FRAG_LOADING_WAITING_RETRY)) {
if (fragCurrent.level !== data.level && fragCurrent.loader) {
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
fragCurrent.loader.abort();
}
}
var curLevel = levels[newLevelId];
var sliding = 0;
if (newDetails.live || (_curLevel$details = curLevel.details) !== null && _curLevel$details !== void 0 && _curLevel$details.live) {
if (!newDetails.fragments[0]) {
newDetails.deltaUpdateFailed = true;
}
if (newDetails.deltaUpdateFailed) {
return;
}
sliding = this.alignPlaylists(newDetails, curLevel.details);
} // override level info
curLevel.details = newDetails;
this.levelLastLoaded = newLevelId;
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].LEVEL_UPDATED, {
details: newDetails,
level: newLevelId
}); // only switch back to IDLE state if we were waiting for level to start downloading a new fragment
if (this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_LEVEL) {
if (this.waitForCdnTuneIn(newDetails)) {
// Wait for Low-Latency CDN Tune-in
return;
}
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
}
if (!this.startFragRequested) {
this.setStartPosition(newDetails, sliding);
} else if (newDetails.live) {
this.synchronizeToLiveEdge(newDetails);
} // trigger handler right now
this.tick();
};
_proto._handleFragmentLoadProgress = function _handleFragmentLoadProgress(data) {
var _frag$initSegment;
var frag = data.frag,
part = data.part,
payload = data.payload;
var levels = this.levels;
if (!levels) {
this.warn("Levels were reset while fragment load was in progress. Fragment " + frag.sn + " of level " + frag.level + " will not be buffered");
return;
}
var currentLevel = levels[frag.level];
var details = currentLevel.details;
if (!details) {
this.warn("Dropping fragment " + frag.sn + " of level " + frag.level + " after level details were reset");
return;
}
var videoCodec = currentLevel.videoCodec; // time Offset is accurate if level PTS is known, or if playlist is not sliding (not live)
var accurateTimeOffset = details.PTSKnown || !details.live;
var initSegmentData = (_frag$initSegment = frag.initSegment) === null || _frag$initSegment === void 0 ? void 0 : _frag$initSegment.data;
var audioCodec = this._getAudioCodec(currentLevel); // transmux the MPEG-TS data to ISO-BMFF segments
// this.log(`Transmuxing ${frag.sn} of [${details.startSN} ,${details.endSN}],level ${frag.level}, cc ${frag.cc}`);
var transmuxer = this.transmuxer = this.transmuxer || new _demux_transmuxer_interface__WEBPACK_IMPORTED_MODULE_8__["default"](this.hls, _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN, this._handleTransmuxComplete.bind(this), this._handleTransmuxerFlush.bind(this));
var partIndex = part ? part.index : -1;
var partial = partIndex !== -1;
var chunkMeta = new _types_transmuxer__WEBPACK_IMPORTED_MODULE_9__["ChunkMetadata"](frag.level, frag.sn, frag.stats.chunkCount, payload.byteLength, partIndex, partial);
var initPTS = this.initPTS[frag.cc];
transmuxer.push(payload, initSegmentData, audioCodec, videoCodec, frag, part, details.totalduration, accurateTimeOffset, chunkMeta, initPTS);
};
_proto.onAudioTrackSwitching = function onAudioTrackSwitching(event, data) {
// if any URL found on new audio track, it is an alternate audio track
var fromAltAudio = this.altAudio;
var altAudio = !!data.url;
var trackId = data.id; // if we switch on main audio, ensure that main fragment scheduling is synced with media.buffered
// don't do anything if we switch to alt audio: audio stream controller is handling it.
// we will just have to change buffer scheduling on audioTrackSwitched
if (!altAudio) {
if (this.mediaBuffer !== this.media) {
this.log('Switching on main audio, use media.buffered to schedule main fragment loading');
this.mediaBuffer = this.media;
var fragCurrent = this.fragCurrent; // we need to refill audio buffer from main: cancel any frag loading to speed up audio switch
if (fragCurrent !== null && fragCurrent !== void 0 && fragCurrent.loader) {
this.log('Switching to main audio track, cancel main fragment load');
fragCurrent.loader.abort();
} // destroy transmuxer to force init segment generation (following audio switch)
this.resetTransmuxer(); // switch to IDLE state to load new fragment
this.resetLoadingState();
} else if (this.audioOnly) {
// Reset audio transmuxer so when switching back to main audio we're not still appending where we left off
this.resetTransmuxer();
}
var hls = this.hls; // If switching from alt to main audio, flush all audio and trigger track switched
if (fromAltAudio) {
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].BUFFER_FLUSHING, {
startOffset: 0,
endOffset: Number.POSITIVE_INFINITY,
type: 'audio'
});
}
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].AUDIO_TRACK_SWITCHED, {
id: trackId
});
}
};
_proto.onAudioTrackSwitched = function onAudioTrackSwitched(event, data) {
var trackId = data.id;
var altAudio = !!this.hls.audioTracks[trackId].url;
if (altAudio) {
var videoBuffer = this.videoBuffer; // if we switched on alternate audio, ensure that main fragment scheduling is synced with video sourcebuffer buffered
if (videoBuffer && this.mediaBuffer !== videoBuffer) {
this.log('Switching on alternate audio, use video.buffered to schedule main fragment loading');
this.mediaBuffer = videoBuffer;
}
}
this.altAudio = altAudio;
this.tick();
};
_proto.onBufferCreated = function onBufferCreated(event, data) {
var tracks = data.tracks;
var mediaTrack;
var name;
var alternate = false;
for (var type in tracks) {
var track = tracks[type];
if (track.id === 'main') {
name = type;
mediaTrack = track; // keep video source buffer reference
if (type === 'video') {
var videoTrack = tracks[type];
if (videoTrack) {
this.videoBuffer = videoTrack.buffer;
}
}
} else {
alternate = true;
}
}
if (alternate && mediaTrack) {
this.log("Alternate track found, use " + name + ".buffered to schedule main fragment loading");
this.mediaBuffer = mediaTrack.buffer;
} else {
this.mediaBuffer = this.media;
}
};
_proto.onFragBuffered = function onFragBuffered(event, data) {
var frag = data.frag,
part = data.part;
if (frag && frag.type !== _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN) {
return;
}
if (this.fragContextChanged(frag)) {
// If a level switch was requested while a fragment was buffering, it will emit the FRAG_BUFFERED event upon completion
// Avoid setting state back to IDLE, since that will interfere with a level switch
this.warn("Fragment " + frag.sn + (part ? ' p: ' + part.index : '') + " of level " + frag.level + " finished buffering, but was aborted. state: " + this.state);
if (this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].PARSED) {
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
}
return;
}
var stats = part ? part.stats : frag.stats;
this.fragLastKbps = Math.round(8 * stats.total / (stats.buffering.end - stats.loading.first));
if (frag.sn !== 'initSegment') {
this.fragPrevious = frag;
}
this.fragBufferedComplete(frag, part);
};
_proto.onError = function onError(event, data) {
switch (data.details) {
case _errors__WEBPACK_IMPORTED_MODULE_11__["ErrorDetails"].FRAG_LOAD_ERROR:
case _errors__WEBPACK_IMPORTED_MODULE_11__["ErrorDetails"].FRAG_LOAD_TIMEOUT:
case _errors__WEBPACK_IMPORTED_MODULE_11__["ErrorDetails"].KEY_LOAD_ERROR:
case _errors__WEBPACK_IMPORTED_MODULE_11__["ErrorDetails"].KEY_LOAD_TIMEOUT:
this.onFragmentOrKeyLoadError(_types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN, data);
break;
case _errors__WEBPACK_IMPORTED_MODULE_11__["ErrorDetails"].LEVEL_LOAD_ERROR:
case _errors__WEBPACK_IMPORTED_MODULE_11__["ErrorDetails"].LEVEL_LOAD_TIMEOUT:
if (this.state !== _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].ERROR) {
if (data.fatal) {
// if fatal error, stop processing
this.warn("" + data.details);
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].ERROR;
} else {
// in case of non fatal error while loading level, if level controller is not retrying to load level , switch back to IDLE
if (!data.levelRetry && this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_LEVEL) {
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
}
}
}
break;
case _errors__WEBPACK_IMPORTED_MODULE_11__["ErrorDetails"].BUFFER_FULL_ERROR:
// if in appending state
if (data.parent === 'main' && (this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].PARSING || this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].PARSED)) {
var flushBuffer = true;
var bufferedInfo = this.getFwdBufferInfo(this.media, _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN); // 0.5 : tolerance needed as some browsers stalls playback before reaching buffered end
// reduce max buf len if current position is buffered
if (bufferedInfo && bufferedInfo.len > 0.5) {
flushBuffer = !this.reduceMaxBufferLength(bufferedInfo.len);
}
if (flushBuffer) {
// current position is not buffered, but browser is still complaining about buffer full error
// this happens on IE/Edge, refer to https://github.com/video-dev/hls.js/pull/708
// in that case flush the whole buffer to recover
this.warn('buffer full error also media.currentTime is not buffered, flush main'); // flush main buffer
this.immediateLevelSwitch();
}
this.resetLoadingState();
}
break;
default:
break;
}
} // Checks the health of the buffer and attempts to resolve playback stalls.
;
_proto.checkBuffer = function checkBuffer() {
var media = this.media,
gapController = this.gapController;
if (!media || !gapController || !media.readyState) {
// Exit early if we don't have media or if the media hasn't buffered anything yet (readyState 0)
return;
} // Check combined buffer
var buffered = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__["BufferHelper"].getBuffered(media);
if (!this.loadedmetadata && buffered.length) {
this.loadedmetadata = true;
this.seekToStartPos();
} else {
// Resolve gaps using the main buffer, whose ranges are the intersections of the A/V sourcebuffers
gapController.poll(this.lastCurrentTime);
}
this.lastCurrentTime = media.currentTime;
};
_proto.onFragLoadEmergencyAborted = function onFragLoadEmergencyAborted() {
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE; // if loadedmetadata is not set, it means that we are emergency switch down on first frag
// in that case, reset startFragRequested flag
if (!this.loadedmetadata) {
this.startFragRequested = false;
this.nextLoadPosition = this.startPosition;
}
this.tickImmediate();
};
_proto.onBufferFlushed = function onBufferFlushed(event, _ref) {
var type = _ref.type;
if (type !== _loader_fragment__WEBPACK_IMPORTED_MODULE_7__["ElementaryStreamTypes"].AUDIO || this.audioOnly && !this.altAudio) {
var media = (type === _loader_fragment__WEBPACK_IMPORTED_MODULE_7__["ElementaryStreamTypes"].VIDEO ? this.videoBuffer : this.mediaBuffer) || this.media;
this.afterBufferFlushed(media, type, _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN);
}
};
_proto.onLevelsUpdated = function onLevelsUpdated(event, data) {
this.levels = data.levels;
};
_proto.swapAudioCodec = function swapAudioCodec() {
this.audioCodecSwap = !this.audioCodecSwap;
}
/**
* Seeks to the set startPosition if not equal to the mediaElement's current time.
* @private
*/
;
_proto.seekToStartPos = function seekToStartPos() {
var media = this.media;
var currentTime = media.currentTime;
var startPosition = this.startPosition; // only adjust currentTime if different from startPosition or if startPosition not buffered
// at that stage, there should be only one buffered range, as we reach that code after first fragment has been buffered
if (startPosition >= 0 && currentTime < startPosition) {
if (media.seeking) {
_utils_logger__WEBPACK_IMPORTED_MODULE_12__["logger"].log("could not seek to " + startPosition + ", already seeking at " + currentTime);
return;
}
var buffered = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__["BufferHelper"].getBuffered(media);
var bufferStart = buffered.length ? buffered.start(0) : 0;
var delta = bufferStart - startPosition;
if (delta > 0 && (delta < this.config.maxBufferHole || delta < this.config.maxFragLookUpTolerance)) {
_utils_logger__WEBPACK_IMPORTED_MODULE_12__["logger"].log("adjusting start position by " + delta + " to match buffer start");
startPosition += delta;
this.startPosition = startPosition;
}
this.log("seek to target start position " + startPosition + " from current time " + currentTime);
media.currentTime = startPosition;
}
};
_proto._getAudioCodec = function _getAudioCodec(currentLevel) {
var audioCodec = this.config.defaultAudioCodec || currentLevel.audioCodec;
if (this.audioCodecSwap && audioCodec) {
this.log('Swapping audio codec');
if (audioCodec.indexOf('mp4a.40.5') !== -1) {
audioCodec = 'mp4a.40.2';
} else {
audioCodec = 'mp4a.40.5';
}
}
return audioCodec;
};
_proto._loadBitrateTestFrag = function _loadBitrateTestFrag(frag) {
var _this2 = this;
this._doFragLoad(frag).then(function (data) {
var hls = _this2.hls;
if (!data || hls.nextLoadLevel || _this2.fragContextChanged(frag)) {
return;
}
_this2.fragLoadError = 0;
_this2.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
_this2.startFragRequested = false;
_this2.bitrateTest = false;
var stats = frag.stats; // Bitrate tests fragments are neither parsed nor buffered
stats.parsing.start = stats.parsing.end = stats.buffering.start = stats.buffering.end = self.performance.now();
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].FRAG_LOADED, data);
});
};
_proto._handleTransmuxComplete = function _handleTransmuxComplete(transmuxResult) {
var _id3$samples;
var id = 'main';
var hls = this.hls;
var remuxResult = transmuxResult.remuxResult,
chunkMeta = transmuxResult.chunkMeta;
var context = this.getCurrentContext(chunkMeta);
if (!context) {
this.warn("The loading context changed while buffering fragment " + chunkMeta.sn + " of level " + chunkMeta.level + ". This chunk will not be buffered.");
this.resetLiveStartWhenNotLoaded(chunkMeta.level);
return;
}
var frag = context.frag,
part = context.part,
level = context.level;
var video = remuxResult.video,
text = remuxResult.text,
id3 = remuxResult.id3,
initSegment = remuxResult.initSegment; // The audio-stream-controller handles audio buffering if Hls.js is playing an alternate audio track
var audio = this.altAudio ? undefined : remuxResult.audio; // Check if the current fragment has been aborted. We check this by first seeing if we're still playing the current level.
// If we are, subsequently check if the currently loading fragment (fragCurrent) has changed.
if (this.fragContextChanged(frag)) {
return;
}
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].PARSING;
if (initSegment) {
if (initSegment.tracks) {
this._bufferInitSegment(level, initSegment.tracks, frag, chunkMeta);
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].FRAG_PARSING_INIT_SEGMENT, {
frag: frag,
id: id,
tracks: initSegment.tracks
});
} // This would be nice if Number.isFinite acted as a typeguard, but it doesn't. See: https://github.com/Microsoft/TypeScript/issues/10038
var initPTS = initSegment.initPTS;
var timescale = initSegment.timescale;
if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(initPTS)) {
this.initPTS[frag.cc] = initPTS;
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].INIT_PTS_FOUND, {
frag: frag,
id: id,
initPTS: initPTS,
timescale: timescale
});
}
} // Avoid buffering if backtracking this fragment
if (video && remuxResult.independent !== false) {
if (level.details) {
var startPTS = video.startPTS,
endPTS = video.endPTS,
startDTS = video.startDTS,
endDTS = video.endDTS;
if (part) {
part.elementaryStreams[video.type] = {
startPTS: startPTS,
endPTS: endPTS,
startDTS: startDTS,
endDTS: endDTS
};
} else {
if (video.firstKeyFrame && video.independent) {
this.couldBacktrack = true;
}
if (video.dropped && video.independent) {
// Backtrack if dropped frames create a gap after currentTime
var pos = this.getLoadPosition() + this.config.maxBufferHole;
if (pos < startPTS) {
this.backtrack(frag);
return;
} // Set video stream start to fragment start so that truncated samples do not distort the timeline, and mark it partial
frag.setElementaryStreamInfo(video.type, frag.start, endPTS, frag.start, endDTS, true);
}
}
frag.setElementaryStreamInfo(video.type, startPTS, endPTS, startDTS, endDTS);
this.bufferFragmentData(video, frag, part, chunkMeta);
}
} else if (remuxResult.independent === false) {
this.backtrack(frag);
return;
}
if (audio) {
var _startPTS = audio.startPTS,
_endPTS = audio.endPTS,
_startDTS = audio.startDTS,
_endDTS = audio.endDTS;
if (part) {
part.elementaryStreams[_loader_fragment__WEBPACK_IMPORTED_MODULE_7__["ElementaryStreamTypes"].AUDIO] = {
startPTS: _startPTS,
endPTS: _endPTS,
startDTS: _startDTS,
endDTS: _endDTS
};
}
frag.setElementaryStreamInfo(_loader_fragment__WEBPACK_IMPORTED_MODULE_7__["ElementaryStreamTypes"].AUDIO, _startPTS, _endPTS, _startDTS, _endDTS);
this.bufferFragmentData(audio, frag, part, chunkMeta);
}
if (id3 !== null && id3 !== void 0 && (_id3$samples = id3.samples) !== null && _id3$samples !== void 0 && _id3$samples.length) {
var emittedID3 = {
frag: frag,
id: id,
samples: id3.samples
};
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].FRAG_PARSING_METADATA, emittedID3);
}
if (text) {
var emittedText = {
frag: frag,
id: id,
samples: text.samples
};
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].FRAG_PARSING_USERDATA, emittedText);
}
};
_proto._bufferInitSegment = function _bufferInitSegment(currentLevel, tracks, frag, chunkMeta) {
var _this3 = this;
if (this.state !== _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].PARSING) {
return;
}
this.audioOnly = !!tracks.audio && !tracks.video; // if audio track is expected to come from audio stream controller, discard any coming from main
if (this.altAudio && !this.audioOnly) {
delete tracks.audio;
} // include levelCodec in audio and video tracks
var audio = tracks.audio,
video = tracks.video,
audiovideo = tracks.audiovideo;
if (audio) {
var audioCodec = currentLevel.audioCodec;
var ua = navigator.userAgent.toLowerCase();
if (this.audioCodecSwitch) {
if (audioCodec) {
if (audioCodec.indexOf('mp4a.40.5') !== -1) {
audioCodec = 'mp4a.40.2';
} else {
audioCodec = 'mp4a.40.5';
}
} // In the case that AAC and HE-AAC audio codecs are signalled in manifest,
// force HE-AAC, as it seems that most browsers prefers it.
// don't force HE-AAC if mono stream, or in Firefox
if (audio.metadata.channelCount !== 1 && ua.indexOf('firefox') === -1) {
audioCodec = 'mp4a.40.5';
}
} // HE-AAC is broken on Android, always signal audio codec as AAC even if variant manifest states otherwise
if (ua.indexOf('android') !== -1 && audio.container !== 'audio/mpeg') {
// Exclude mpeg audio
audioCodec = 'mp4a.40.2';
this.log("Android: force audio codec to " + audioCodec);
}
if (currentLevel.audioCodec && currentLevel.audioCodec !== audioCodec) {
this.log("Swapping manifest audio codec \"" + currentLevel.audioCodec + "\" for \"" + audioCodec + "\"");
}
audio.levelCodec = audioCodec;
audio.id = 'main';
this.log("Init audio buffer, container:" + audio.container + ", codecs[selected/level/parsed]=[" + (audioCodec || '') + "/" + (currentLevel.audioCodec || '') + "/" + audio.codec + "]");
}
if (video) {
video.levelCodec = currentLevel.videoCodec;
video.id = 'main';
this.log("Init video buffer, container:" + video.container + ", codecs[level/parsed]=[" + (currentLevel.videoCodec || '') + "/" + video.codec + "]");
}
if (audiovideo) {
this.log("Init audiovideo buffer, container:" + audiovideo.container + ", codecs[level/parsed]=[" + (currentLevel.attrs.CODECS || '') + "/" + audiovideo.codec + "]");
}
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].BUFFER_CODECS, tracks); // loop through tracks that are going to be provided to bufferController
Object.keys(tracks).forEach(function (trackName) {
var track = tracks[trackName];
var initSegment = track.initSegment;
if (initSegment !== null && initSegment !== void 0 && initSegment.byteLength) {
_this3.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].BUFFER_APPENDING, {
type: trackName,
data: initSegment,
frag: frag,
part: null,
chunkMeta: chunkMeta,
parent: frag.type
});
}
}); // trigger handler right now
this.tick();
};
_proto.backtrack = function backtrack(frag) {
this.couldBacktrack = true; // Causes findFragments to backtrack through fragments to find the keyframe
this.resetTransmuxer();
this.flushBufferGap(frag);
var data = this.fragmentTracker.backtrack(frag);
this.fragPrevious = null;
this.nextLoadPosition = frag.start;
if (data) {
this.resetFragmentLoading(frag);
} else {
// Change state to BACKTRACKING so that fragmentEntity.backtrack data can be added after _doFragLoad
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].BACKTRACKING;
}
};
_proto.checkFragmentChanged = function checkFragmentChanged() {
var video = this.media;
var fragPlayingCurrent = null;
if (video && video.readyState > 1 && video.seeking === false) {
var currentTime = video.currentTime;
/* if video element is in seeked state, currentTime can only increase.
(assuming that playback rate is positive ...)
As sometimes currentTime jumps back to zero after a
media decode error, check this, to avoid seeking back to
wrong position after a media decode error
*/
if (_utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__["BufferHelper"].isBuffered(video, currentTime)) {
fragPlayingCurrent = this.getAppendedFrag(currentTime);
} else if (_utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__["BufferHelper"].isBuffered(video, currentTime + 0.1)) {
/* ensure that FRAG_CHANGED event is triggered at startup,
when first video frame is displayed and playback is paused.
add a tolerance of 100ms, in case current position is not buffered,
check if current pos+100ms is buffered and use that buffer range
for FRAG_CHANGED event reporting */
fragPlayingCurrent = this.getAppendedFrag(currentTime + 0.1);
}
if (fragPlayingCurrent) {
var fragPlaying = this.fragPlaying;
var fragCurrentLevel = fragPlayingCurrent.level;
if (!fragPlaying || fragPlayingCurrent.sn !== fragPlaying.sn || fragPlaying.level !== fragCurrentLevel || fragPlayingCurrent.urlId !== fragPlaying.urlId) {
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].FRAG_CHANGED, {
frag: fragPlayingCurrent
});
if (!fragPlaying || fragPlaying.level !== fragCurrentLevel) {
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].LEVEL_SWITCHED, {
level: fragCurrentLevel
});
}
this.fragPlaying = fragPlayingCurrent;
}
}
}
};
_createClass(StreamController, [{
key: "nextLevel",
get: function get() {
var frag = this.nextBufferedFrag;
if (frag) {
return frag.level;
} else {
return -1;
}
}
}, {
key: "currentLevel",
get: function get() {
var media = this.media;
if (media) {
var fragPlayingCurrent = this.getAppendedFrag(media.currentTime);
if (fragPlayingCurrent) {
return fragPlayingCurrent.level;
}
}
return -1;
}
}, {
key: "nextBufferedFrag",
get: function get() {
var media = this.media;
if (media) {
// first get end range of current fragment
var fragPlayingCurrent = this.getAppendedFrag(media.currentTime);
return this.followingBufferedFrag(fragPlayingCurrent);
} else {
return null;
}
}
}, {
key: "forceStartLoad",
get: function get() {
return this._forceStartLoad;
}
}]);
return StreamController;
}(_base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["default"]);
/***/ }),
/***/ "./src/crypt/aes-crypto.ts":
/*!*********************************!*\
!*** ./src/crypt/aes-crypto.ts ***!
\*********************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return AESCrypto; });
var AESCrypto = /*#__PURE__*/function () {
function AESCrypto(subtle, iv) {
this.subtle = void 0;
this.aesIV = void 0;
this.subtle = subtle;
this.aesIV = iv;
}
var _proto = AESCrypto.prototype;
_proto.decrypt = function decrypt(data, key) {
return this.subtle.decrypt({
name: 'AES-CBC',
iv: this.aesIV
}, key, data);
};
return AESCrypto;
}();
/***/ }),
/***/ "./src/crypt/aes-decryptor.ts":
/*!************************************!*\
!*** ./src/crypt/aes-decryptor.ts ***!
\************************************/
/*! exports provided: removePadding, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "removePadding", function() { return removePadding; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return AESDecryptor; });
/* harmony import */ var _utils_typed_array__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/typed-array */ "./src/utils/typed-array.ts");
// PKCS7
function removePadding(array) {
var outputBytes = array.byteLength;
var paddingBytes = outputBytes && new DataView(array.buffer).getUint8(outputBytes - 1);
if (paddingBytes) {
return Object(_utils_typed_array__WEBPACK_IMPORTED_MODULE_0__["sliceUint8"])(array, 0, outputBytes - paddingBytes);
}
return array;
}
var AESDecryptor = /*#__PURE__*/function () {
function AESDecryptor() {
this.rcon = [0x0, 0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];
this.subMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];
this.invSubMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];
this.sBox = new Uint32Array(256);
this.invSBox = new Uint32Array(256);
this.key = new Uint32Array(0);
this.ksRows = 0;
this.keySize = 0;
this.keySchedule = void 0;
this.invKeySchedule = void 0;
this.initTable();
} // Using view.getUint32() also swaps the byte order.
var _proto = AESDecryptor.prototype;
_proto.uint8ArrayToUint32Array_ = function uint8ArrayToUint32Array_(arrayBuffer) {
var view = new DataView(arrayBuffer);
var newArray = new Uint32Array(4);
for (var i = 0; i < 4; i++) {
newArray[i] = view.getUint32(i * 4);
}
return newArray;
};
_proto.initTable = function initTable() {
var sBox = this.sBox;
var invSBox = this.invSBox;
var subMix = this.subMix;
var subMix0 = subMix[0];
var subMix1 = subMix[1];
var subMix2 = subMix[2];
var subMix3 = subMix[3];
var invSubMix = this.invSubMix;
var invSubMix0 = invSubMix[0];
var invSubMix1 = invSubMix[1];
var invSubMix2 = invSubMix[2];
var invSubMix3 = invSubMix[3];
var d = new Uint32Array(256);
var x = 0;
var xi = 0;
var i = 0;
for (i = 0; i < 256; i++) {
if (i < 128) {
d[i] = i << 1;
} else {
d[i] = i << 1 ^ 0x11b;
}
}
for (i = 0; i < 256; i++) {
var sx = xi ^ xi << 1 ^ xi << 2 ^ xi << 3 ^ xi << 4;
sx = sx >>> 8 ^ sx & 0xff ^ 0x63;
sBox[x] = sx;
invSBox[sx] = x; // Compute multiplication
var x2 = d[x];
var x4 = d[x2];
var x8 = d[x4]; // Compute sub/invSub bytes, mix columns tables
var t = d[sx] * 0x101 ^ sx * 0x1010100;
subMix0[x] = t << 24 | t >>> 8;
subMix1[x] = t << 16 | t >>> 16;
subMix2[x] = t << 8 | t >>> 24;
subMix3[x] = t; // Compute inv sub bytes, inv mix columns tables
t = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100;
invSubMix0[sx] = t << 24 | t >>> 8;
invSubMix1[sx] = t << 16 | t >>> 16;
invSubMix2[sx] = t << 8 | t >>> 24;
invSubMix3[sx] = t; // Compute next counter
if (!x) {
x = xi = 1;
} else {
x = x2 ^ d[d[d[x8 ^ x2]]];
xi ^= d[d[xi]];
}
}
};
_proto.expandKey = function expandKey(keyBuffer) {
// convert keyBuffer to Uint32Array
var key = this.uint8ArrayToUint32Array_(keyBuffer);
var sameKey = true;
var offset = 0;
while (offset < key.length && sameKey) {
sameKey = key[offset] === this.key[offset];
offset++;
}
if (sameKey) {
return;
}
this.key = key;
var keySize = this.keySize = key.length;
if (keySize !== 4 && keySize !== 6 && keySize !== 8) {
throw new Error('Invalid aes key size=' + keySize);
}
var ksRows = this.ksRows = (keySize + 6 + 1) * 4;
var ksRow;
var invKsRow;
var keySchedule = this.keySchedule = new Uint32Array(ksRows);
var invKeySchedule = this.invKeySchedule = new Uint32Array(ksRows);
var sbox = this.sBox;
var rcon = this.rcon;
var invSubMix = this.invSubMix;
var invSubMix0 = invSubMix[0];
var invSubMix1 = invSubMix[1];
var invSubMix2 = invSubMix[2];
var invSubMix3 = invSubMix[3];
var prev;
var t;
for (ksRow = 0; ksRow < ksRows; ksRow++) {
if (ksRow < keySize) {
prev = keySchedule[ksRow] = key[ksRow];
continue;
}
t = prev;
if (ksRow % keySize === 0) {
// Rot word
t = t << 8 | t >>> 24; // Sub word
t = sbox[t >>> 24] << 24 | sbox[t >>> 16 & 0xff] << 16 | sbox[t >>> 8 & 0xff] << 8 | sbox[t & 0xff]; // Mix Rcon
t ^= rcon[ksRow / keySize | 0] << 24;
} else if (keySize > 6 && ksRow % keySize === 4) {
// Sub word
t = sbox[t >>> 24] << 24 | sbox[t >>> 16 & 0xff] << 16 | sbox[t >>> 8 & 0xff] << 8 | sbox[t & 0xff];
}
keySchedule[ksRow] = prev = (keySchedule[ksRow - keySize] ^ t) >>> 0;
}
for (invKsRow = 0; invKsRow < ksRows; invKsRow++) {
ksRow = ksRows - invKsRow;
if (invKsRow & 3) {
t = keySchedule[ksRow];
} else {
t = keySchedule[ksRow - 4];
}
if (invKsRow < 4 || ksRow <= 4) {
invKeySchedule[invKsRow] = t;
} else {
invKeySchedule[invKsRow] = invSubMix0[sbox[t >>> 24]] ^ invSubMix1[sbox[t >>> 16 & 0xff]] ^ invSubMix2[sbox[t >>> 8 & 0xff]] ^ invSubMix3[sbox[t & 0xff]];
}
invKeySchedule[invKsRow] = invKeySchedule[invKsRow] >>> 0;
}
} // Adding this as a method greatly improves performance.
;
_proto.networkToHostOrderSwap = function networkToHostOrderSwap(word) {
return word << 24 | (word & 0xff00) << 8 | (word & 0xff0000) >> 8 | word >>> 24;
};
_proto.decrypt = function decrypt(inputArrayBuffer, offset, aesIV) {
var nRounds = this.keySize + 6;
var invKeySchedule = this.invKeySchedule;
var invSBOX = this.invSBox;
var invSubMix = this.invSubMix;
var invSubMix0 = invSubMix[0];
var invSubMix1 = invSubMix[1];
var invSubMix2 = invSubMix[2];
var invSubMix3 = invSubMix[3];
var initVector = this.uint8ArrayToUint32Array_(aesIV);
var initVector0 = initVector[0];
var initVector1 = initVector[1];
var initVector2 = initVector[2];
var initVector3 = initVector[3];
var inputInt32 = new Int32Array(inputArrayBuffer);
var outputInt32 = new Int32Array(inputInt32.length);
var t0, t1, t2, t3;
var s0, s1, s2, s3;
var inputWords0, inputWords1, inputWords2, inputWords3;
var ksRow, i;
var swapWord = this.networkToHostOrderSwap;
while (offset < inputInt32.length) {
inputWords0 = swapWord(inputInt32[offset]);
inputWords1 = swapWord(inputInt32[offset + 1]);
inputWords2 = swapWord(inputInt32[offset + 2]);
inputWords3 = swapWord(inputInt32[offset + 3]);
s0 = inputWords0 ^ invKeySchedule[0];
s1 = inputWords3 ^ invKeySchedule[1];
s2 = inputWords2 ^ invKeySchedule[2];
s3 = inputWords1 ^ invKeySchedule[3];
ksRow = 4; // Iterate through the rounds of decryption
for (i = 1; i < nRounds; i++) {
t0 = invSubMix0[s0 >>> 24] ^ invSubMix1[s1 >> 16 & 0xff] ^ invSubMix2[s2 >> 8 & 0xff] ^ invSubMix3[s3 & 0xff] ^ invKeySchedule[ksRow];
t1 = invSubMix0[s1 >>> 24] ^ invSubMix1[s2 >> 16 & 0xff] ^ invSubMix2[s3 >> 8 & 0xff] ^ invSubMix3[s0 & 0xff] ^ invKeySchedule[ksRow + 1];
t2 = invSubMix0[s2 >>> 24] ^ invSubMix1[s3 >> 16 & 0xff] ^ invSubMix2[s0 >> 8 & 0xff] ^ invSubMix3[s1 & 0xff] ^ invKeySchedule[ksRow + 2];
t3 = invSubMix0[s3 >>> 24] ^ invSubMix1[s0 >> 16 & 0xff] ^ invSubMix2[s1 >> 8 & 0xff] ^ invSubMix3[s2 & 0xff] ^ invKeySchedule[ksRow + 3]; // Update state
s0 = t0;
s1 = t1;
s2 = t2;
s3 = t3;
ksRow = ksRow + 4;
} // Shift rows, sub bytes, add round key
t0 = invSBOX[s0 >>> 24] << 24 ^ invSBOX[s1 >> 16 & 0xff] << 16 ^ invSBOX[s2 >> 8 & 0xff] << 8 ^ invSBOX[s3 & 0xff] ^ invKeySchedule[ksRow];
t1 = invSBOX[s1 >>> 24] << 24 ^ invSBOX[s2 >> 16 & 0xff] << 16 ^ invSBOX[s3 >> 8 & 0xff] << 8 ^ invSBOX[s0 & 0xff] ^ invKeySchedule[ksRow + 1];
t2 = invSBOX[s2 >>> 24] << 24 ^ invSBOX[s3 >> 16 & 0xff] << 16 ^ invSBOX[s0 >> 8 & 0xff] << 8 ^ invSBOX[s1 & 0xff] ^ invKeySchedule[ksRow + 2];
t3 = invSBOX[s3 >>> 24] << 24 ^ invSBOX[s0 >> 16 & 0xff] << 16 ^ invSBOX[s1 >> 8 & 0xff] << 8 ^ invSBOX[s2 & 0xff] ^ invKeySchedule[ksRow + 3]; // Write
outputInt32[offset] = swapWord(t0 ^ initVector0);
outputInt32[offset + 1] = swapWord(t3 ^ initVector1);
outputInt32[offset + 2] = swapWord(t2 ^ initVector2);
outputInt32[offset + 3] = swapWord(t1 ^ initVector3); // reset initVector to last 4 unsigned int
initVector0 = inputWords0;
initVector1 = inputWords1;
initVector2 = inputWords2;
initVector3 = inputWords3;
offset = offset + 4;
}
return outputInt32.buffer;
};
return AESDecryptor;
}();
/***/ }),
/***/ "./src/crypt/decrypter.ts":
/*!********************************!*\
!*** ./src/crypt/decrypter.ts ***!
\********************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Decrypter; });
/* harmony import */ var _aes_crypto__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./aes-crypto */ "./src/crypt/aes-crypto.ts");
/* harmony import */ var _fast_aes_key__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./fast-aes-key */ "./src/crypt/fast-aes-key.ts");
/* harmony import */ var _aes_decryptor__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./aes-decryptor */ "./src/crypt/aes-decryptor.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/mp4-tools */ "./src/utils/mp4-tools.ts");
/* harmony import */ var _utils_typed_array__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/typed-array */ "./src/utils/typed-array.ts");
var CHUNK_SIZE = 16; // 16 bytes, 128 bits
var Decrypter = /*#__PURE__*/function () {
function Decrypter(observer, config, _temp) {
var _ref = _temp === void 0 ? {} : _temp,
_ref$removePKCS7Paddi = _ref.removePKCS7Padding,
removePKCS7Padding = _ref$removePKCS7Paddi === void 0 ? true : _ref$removePKCS7Paddi;
this.logEnabled = true;
this.observer = void 0;
this.config = void 0;
this.removePKCS7Padding = void 0;
this.subtle = null;
this.softwareDecrypter = null;
this.key = null;
this.fastAesKey = null;
this.remainderData = null;
this.currentIV = null;
this.currentResult = null;
this.observer = observer;
this.config = config;
this.removePKCS7Padding = removePKCS7Padding; // built in decryptor expects PKCS7 padding
if (removePKCS7Padding) {
try {
var browserCrypto = self.crypto;
if (browserCrypto) {
this.subtle = browserCrypto.subtle || browserCrypto.webkitSubtle;
}
} catch (e) {
/* no-op */
}
}
if (this.subtle === null) {
this.config.enableSoftwareAES = true;
}
}
var _proto = Decrypter.prototype;
_proto.destroy = function destroy() {
// @ts-ignore
this.observer = null;
};
_proto.isSync = function isSync() {
return this.config.enableSoftwareAES;
};
_proto.flush = function flush() {
var currentResult = this.currentResult;
if (!currentResult) {
this.reset();
return;
}
var data = new Uint8Array(currentResult);
this.reset();
if (this.removePKCS7Padding) {
return Object(_aes_decryptor__WEBPACK_IMPORTED_MODULE_2__["removePadding"])(data);
}
return data;
};
_proto.reset = function reset() {
this.currentResult = null;
this.currentIV = null;
this.remainderData = null;
if (this.softwareDecrypter) {
this.softwareDecrypter = null;
}
};
_proto.decrypt = function decrypt(data, key, iv, callback) {
if (this.config.enableSoftwareAES) {
this.softwareDecrypt(new Uint8Array(data), key, iv);
var decryptResult = this.flush();
if (decryptResult) {
callback(decryptResult.buffer);
}
} else {
this.webCryptoDecrypt(new Uint8Array(data), key, iv).then(callback);
}
};
_proto.softwareDecrypt = function softwareDecrypt(data, key, iv) {
var currentIV = this.currentIV,
currentResult = this.currentResult,
remainderData = this.remainderData;
this.logOnce('JS AES decrypt'); // The output is staggered during progressive parsing - the current result is cached, and emitted on the next call
// This is done in order to strip PKCS7 padding, which is found at the end of each segment. We only know we've reached
// the end on flush(), but by that time we have already received all bytes for the segment.
// Progressive decryption does not work with WebCrypto
if (remainderData) {
data = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_4__["appendUint8Array"])(remainderData, data);
this.remainderData = null;
} // Byte length must be a multiple of 16 (AES-128 = 128 bit blocks = 16 bytes)
var currentChunk = this.getValidChunk(data);
if (!currentChunk.length) {
return null;
}
if (currentIV) {
iv = currentIV;
}
var softwareDecrypter = this.softwareDecrypter;
if (!softwareDecrypter) {
softwareDecrypter = this.softwareDecrypter = new _aes_decryptor__WEBPACK_IMPORTED_MODULE_2__["default"]();
}
softwareDecrypter.expandKey(key);
var result = currentResult;
this.currentResult = softwareDecrypter.decrypt(currentChunk.buffer, 0, iv);
this.currentIV = Object(_utils_typed_array__WEBPACK_IMPORTED_MODULE_5__["sliceUint8"])(currentChunk, -16).buffer;
if (!result) {
return null;
}
return result;
};
_proto.webCryptoDecrypt = function webCryptoDecrypt(data, key, iv) {
var _this = this;
var subtle = this.subtle;
if (this.key !== key || !this.fastAesKey) {
this.key = key;
this.fastAesKey = new _fast_aes_key__WEBPACK_IMPORTED_MODULE_1__["default"](subtle, key);
}
return this.fastAesKey.expandKey().then(function (aesKey) {
// decrypt using web crypto
if (!subtle) {
return Promise.reject(new Error('web crypto not initialized'));
}
var crypto = new _aes_crypto__WEBPACK_IMPORTED_MODULE_0__["default"](subtle, iv);
return crypto.decrypt(data.buffer, aesKey);
}).catch(function (err) {
return _this.onWebCryptoError(err, data, key, iv);
});
};
_proto.onWebCryptoError = function onWebCryptoError(err, data, key, iv) {
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn('[decrypter.ts]: WebCrypto Error, disable WebCrypto API:', err);
this.config.enableSoftwareAES = true;
this.logEnabled = true;
return this.softwareDecrypt(data, key, iv);
};
_proto.getValidChunk = function getValidChunk(data) {
var currentChunk = data;
var splitPoint = data.length - data.length % CHUNK_SIZE;
if (splitPoint !== data.length) {
currentChunk = Object(_utils_typed_array__WEBPACK_IMPORTED_MODULE_5__["sliceUint8"])(data, 0, splitPoint);
this.remainderData = Object(_utils_typed_array__WEBPACK_IMPORTED_MODULE_5__["sliceUint8"])(data, splitPoint);
}
return currentChunk;
};
_proto.logOnce = function logOnce(msg) {
if (!this.logEnabled) {
return;
}
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].log("[decrypter.ts]: " + msg);
this.logEnabled = false;
};
return Decrypter;
}();
/***/ }),
/***/ "./src/crypt/fast-aes-key.ts":
/*!***********************************!*\
!*** ./src/crypt/fast-aes-key.ts ***!
\***********************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return FastAESKey; });
var FastAESKey = /*#__PURE__*/function () {
function FastAESKey(subtle, key) {
this.subtle = void 0;
this.key = void 0;
this.subtle = subtle;
this.key = key;
}
var _proto = FastAESKey.prototype;
_proto.expandKey = function expandKey() {
return this.subtle.importKey('raw', this.key, {
name: 'AES-CBC'
}, false, ['encrypt', 'decrypt']);
};
return FastAESKey;
}();
/***/ }),
/***/ "./src/demux/aacdemuxer.ts":
/*!*********************************!*\
!*** ./src/demux/aacdemuxer.ts ***!
\*********************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _base_audio_demuxer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base-audio-demuxer */ "./src/demux/base-audio-demuxer.ts");
/* harmony import */ var _adts__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./adts */ "./src/demux/adts.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/* harmony import */ var _demux_id3__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../demux/id3 */ "./src/demux/id3.ts");
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
/**
* AAC demuxer
*/
var AACDemuxer = /*#__PURE__*/function (_BaseAudioDemuxer) {
_inheritsLoose(AACDemuxer, _BaseAudioDemuxer);
function AACDemuxer(observer, config) {
var _this;
_this = _BaseAudioDemuxer.call(this) || this;
_this.observer = void 0;
_this.config = void 0;
_this.observer = observer;
_this.config = config;
return _this;
}
var _proto = AACDemuxer.prototype;
_proto.resetInitSegment = function resetInitSegment(audioCodec, videoCodec, duration) {
_BaseAudioDemuxer.prototype.resetInitSegment.call(this, audioCodec, videoCodec, duration);
this._audioTrack = {
container: 'audio/adts',
type: 'audio',
id: 0,
pid: -1,
sequenceNumber: 0,
isAAC: true,
samples: [],
manifestCodec: audioCodec,
duration: duration,
inputTimeScale: 90000,
dropped: 0
};
} // Source for probe info - https://wiki.multimedia.cx/index.php?title=ADTS
;
AACDemuxer.probe = function probe(data) {
if (!data) {
return false;
} // Check for the ADTS sync word
// Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1
// Layer bits (position 14 and 15) in header should be always 0 for ADTS
// More info https://wiki.multimedia.cx/index.php?title=ADTS
var id3Data = _demux_id3__WEBPACK_IMPORTED_MODULE_3__["getID3Data"](data, 0) || [];
var offset = id3Data.length;
for (var length = data.length; offset < length; offset++) {
if (_adts__WEBPACK_IMPORTED_MODULE_1__["probe"](data, offset)) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('ADTS sync word found !');
return true;
}
}
return false;
};
_proto.canParse = function canParse(data, offset) {
return _adts__WEBPACK_IMPORTED_MODULE_1__["canParse"](data, offset);
};
_proto.appendFrame = function appendFrame(track, data, offset) {
_adts__WEBPACK_IMPORTED_MODULE_1__["initTrackConfig"](track, this.observer, data, offset, track.manifestCodec);
var frame = _adts__WEBPACK_IMPORTED_MODULE_1__["appendFrame"](track, data, offset, this.initPTS, this.frameIndex);
if (frame && frame.missing === 0) {
return frame;
}
};
return AACDemuxer;
}(_base_audio_demuxer__WEBPACK_IMPORTED_MODULE_0__["default"]);
AACDemuxer.minProbeByteLength = 9;
/* harmony default export */ __webpack_exports__["default"] = (AACDemuxer);
/***/ }),
/***/ "./src/demux/adts.ts":
/*!***************************!*\
!*** ./src/demux/adts.ts ***!
\***************************/
/*! exports provided: getAudioConfig, isHeaderPattern, getHeaderLength, getFullFrameLength, canGetFrameLength, isHeader, canParse, probe, initTrackConfig, getFrameDuration, parseFrameHeader, appendFrame */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getAudioConfig", function() { return getAudioConfig; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isHeaderPattern", function() { return isHeaderPattern; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getHeaderLength", function() { return getHeaderLength; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getFullFrameLength", function() { return getFullFrameLength; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "canGetFrameLength", function() { return canGetFrameLength; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isHeader", function() { return isHeader; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "canParse", function() { return canParse; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "probe", function() { return probe; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initTrackConfig", function() { return initTrackConfig; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getFrameDuration", function() { return getFrameDuration; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseFrameHeader", function() { return parseFrameHeader; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "appendFrame", function() { return appendFrame; });
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/**
* ADTS parser helper
* @link https://wiki.multimedia.cx/index.php?title=ADTS
*/
function getAudioConfig(observer, data, offset, audioCodec) {
var adtsObjectType;
var adtsExtensionSamplingIndex;
var adtsChanelConfig;
var config;
var userAgent = navigator.userAgent.toLowerCase();
var manifestCodec = audioCodec;
var adtsSampleingRates = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350]; // byte 2
adtsObjectType = ((data[offset + 2] & 0xc0) >>> 6) + 1;
var adtsSamplingIndex = (data[offset + 2] & 0x3c) >>> 2;
if (adtsSamplingIndex > adtsSampleingRates.length - 1) {
observer.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].MEDIA_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].FRAG_PARSING_ERROR,
fatal: true,
reason: "invalid ADTS sampling index:" + adtsSamplingIndex
});
return;
}
adtsChanelConfig = (data[offset + 2] & 0x01) << 2; // byte 3
adtsChanelConfig |= (data[offset + 3] & 0xc0) >>> 6;
_utils_logger__WEBPACK_IMPORTED_MODULE_0__["logger"].log("manifest codec:" + audioCodec + ", ADTS type:" + adtsObjectType + ", samplingIndex:" + adtsSamplingIndex); // firefox: freq less than 24kHz = AAC SBR (HE-AAC)
if (/firefox/i.test(userAgent)) {
if (adtsSamplingIndex >= 6) {
adtsObjectType = 5;
config = new Array(4); // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies
// there is a factor 2 between frame sample rate and output sample rate
// multiply frequency by 2 (see table below, equivalent to substract 3)
adtsExtensionSamplingIndex = adtsSamplingIndex - 3;
} else {
adtsObjectType = 2;
config = new Array(2);
adtsExtensionSamplingIndex = adtsSamplingIndex;
} // Android : always use AAC
} else if (userAgent.indexOf('android') !== -1) {
adtsObjectType = 2;
config = new Array(2);
adtsExtensionSamplingIndex = adtsSamplingIndex;
} else {
/* for other browsers (Chrome/Vivaldi/Opera ...)
always force audio type to be HE-AAC SBR, as some browsers do not support audio codec switch properly (like Chrome ...)
*/
adtsObjectType = 5;
config = new Array(4); // if (manifest codec is HE-AAC or HE-AACv2) OR (manifest codec not specified AND frequency less than 24kHz)
if (audioCodec && (audioCodec.indexOf('mp4a.40.29') !== -1 || audioCodec.indexOf('mp4a.40.5') !== -1) || !audioCodec && adtsSamplingIndex >= 6) {
// HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies
// there is a factor 2 between frame sample rate and output sample rate
// multiply frequency by 2 (see table below, equivalent to substract 3)
adtsExtensionSamplingIndex = adtsSamplingIndex - 3;
} else {
// if (manifest codec is AAC) AND (frequency less than 24kHz AND nb channel is 1) OR (manifest codec not specified and mono audio)
// Chrome fails to play back with low frequency AAC LC mono when initialized with HE-AAC. This is not a problem with stereo.
if (audioCodec && audioCodec.indexOf('mp4a.40.2') !== -1 && (adtsSamplingIndex >= 6 && adtsChanelConfig === 1 || /vivaldi/i.test(userAgent)) || !audioCodec && adtsChanelConfig === 1) {
adtsObjectType = 2;
config = new Array(2);
}
adtsExtensionSamplingIndex = adtsSamplingIndex;
}
}
/* refer to http://wiki.multimedia.cx/index.php?title=MPEG-4_Audio#Audio_Specific_Config
ISO 14496-3 (AAC).pdf - Table 1.13 — Syntax of AudioSpecificConfig()
Audio Profile / Audio Object Type
0: Null
1: AAC Main
2: AAC LC (Low Complexity)
3: AAC SSR (Scalable Sample Rate)
4: AAC LTP (Long Term Prediction)
5: SBR (Spectral Band Replication)
6: AAC Scalable
sampling freq
0: 96000 Hz
1: 88200 Hz
2: 64000 Hz
3: 48000 Hz
4: 44100 Hz
5: 32000 Hz
6: 24000 Hz
7: 22050 Hz
8: 16000 Hz
9: 12000 Hz
10: 11025 Hz
11: 8000 Hz
12: 7350 Hz
13: Reserved
14: Reserved
15: frequency is written explictly
Channel Configurations
These are the channel configurations:
0: Defined in AOT Specifc Config
1: 1 channel: front-center
2: 2 channels: front-left, front-right
*/
// audioObjectType = profile => profile, the MPEG-4 Audio Object Type minus 1
config[0] = adtsObjectType << 3; // samplingFrequencyIndex
config[0] |= (adtsSamplingIndex & 0x0e) >> 1;
config[1] |= (adtsSamplingIndex & 0x01) << 7; // channelConfiguration
config[1] |= adtsChanelConfig << 3;
if (adtsObjectType === 5) {
// adtsExtensionSampleingIndex
config[1] |= (adtsExtensionSamplingIndex & 0x0e) >> 1;
config[2] = (adtsExtensionSamplingIndex & 0x01) << 7; // adtsObjectType (force to 2, chrome is checking that object type is less than 5 ???
// https://chromium.googlesource.com/chromium/src.git/+/master/media/formats/mp4/aac.cc
config[2] |= 2 << 2;
config[3] = 0;
}
return {
config: config,
samplerate: adtsSampleingRates[adtsSamplingIndex],
channelCount: adtsChanelConfig,
codec: 'mp4a.40.' + adtsObjectType,
manifestCodec: manifestCodec
};
}
function isHeaderPattern(data, offset) {
return data[offset] === 0xff && (data[offset + 1] & 0xf6) === 0xf0;
}
function getHeaderLength(data, offset) {
return data[offset + 1] & 0x01 ? 7 : 9;
}
function getFullFrameLength(data, offset) {
return (data[offset + 3] & 0x03) << 11 | data[offset + 4] << 3 | (data[offset + 5] & 0xe0) >>> 5;
}
function canGetFrameLength(data, offset) {
return offset + 5 < data.length;
}
function isHeader(data, offset) {
// Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1
// Layer bits (position 14 and 15) in header should be always 0 for ADTS
// More info https://wiki.multimedia.cx/index.php?title=ADTS
return offset + 1 < data.length && isHeaderPattern(data, offset);
}
function canParse(data, offset) {
return canGetFrameLength(data, offset) && isHeaderPattern(data, offset) && getFullFrameLength(data, offset) <= data.length - offset;
}
function probe(data, offset) {
// same as isHeader but we also check that ADTS frame follows last ADTS frame
// or end of data is reached
if (isHeader(data, offset)) {
// ADTS header Length
var headerLength = getHeaderLength(data, offset);
if (offset + headerLength >= data.length) {
return false;
} // ADTS frame Length
var frameLength = getFullFrameLength(data, offset);
if (frameLength <= headerLength) {
return false;
}
var newOffset = offset + frameLength;
return newOffset === data.length || isHeader(data, newOffset);
}
return false;
}
function initTrackConfig(track, observer, data, offset, audioCodec) {
if (!track.samplerate) {
var config = getAudioConfig(observer, data, offset, audioCodec);
if (!config) {
return;
}
track.config = config.config;
track.samplerate = config.samplerate;
track.channelCount = config.channelCount;
track.codec = config.codec;
track.manifestCodec = config.manifestCodec;
_utils_logger__WEBPACK_IMPORTED_MODULE_0__["logger"].log("parsed codec:" + track.codec + ", rate:" + config.samplerate + ", channels:" + config.channelCount);
}
}
function getFrameDuration(samplerate) {
return 1024 * 90000 / samplerate;
}
function parseFrameHeader(data, offset, pts, frameIndex, frameDuration) {
// The protection skip bit tells us if we have 2 bytes of CRC data at the end of the ADTS header
var headerLength = getHeaderLength(data, offset); // retrieve frame size
var frameLength = getFullFrameLength(data, offset);
frameLength -= headerLength;
if (frameLength > 0) {
var stamp = pts + frameIndex * frameDuration; // logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}/${(stamp/90).toFixed(0)}`);
return {
headerLength: headerLength,
frameLength: frameLength,
stamp: stamp
};
}
}
function appendFrame(track, data, offset, pts, frameIndex) {
var frameDuration = getFrameDuration(track.samplerate);
var header = parseFrameHeader(data, offset, pts, frameIndex, frameDuration);
if (header) {
var frameLength = header.frameLength,
headerLength = header.headerLength,
stamp = header.stamp;
var length = headerLength + frameLength;
var missing = Math.max(0, offset + length - data.length); // logger.log(`AAC frame ${frameIndex}, pts:${stamp} length@offset/total: ${frameLength}@${offset+headerLength}/${data.byteLength} missing: ${missing}`);
var unit;
if (missing) {
unit = new Uint8Array(length - headerLength);
unit.set(data.subarray(offset + headerLength, data.length), 0);
} else {
unit = data.subarray(offset + headerLength, offset + length);
}
var sample = {
unit: unit,
pts: stamp
};
if (!missing) {
track.samples.push(sample);
}
return {
sample: sample,
length: length,
missing: missing
};
}
}
/***/ }),
/***/ "./src/demux/base-audio-demuxer.ts":
/*!*****************************************!*\
!*** ./src/demux/base-audio-demuxer.ts ***!
\*****************************************/
/*! exports provided: initPTSFn, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initPTSFn", function() { return initPTSFn; });
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var _demux_id3__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../demux/id3 */ "./src/demux/id3.ts");
/* harmony import */ var _dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./dummy-demuxed-track */ "./src/demux/dummy-demuxed-track.ts");
/* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/mp4-tools */ "./src/utils/mp4-tools.ts");
/* harmony import */ var _utils_typed_array__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/typed-array */ "./src/utils/typed-array.ts");
var BaseAudioDemuxer = /*#__PURE__*/function () {
function BaseAudioDemuxer() {
this._audioTrack = void 0;
this._id3Track = void 0;
this.frameIndex = 0;
this.cachedData = null;
this.initPTS = null;
}
var _proto = BaseAudioDemuxer.prototype;
_proto.resetInitSegment = function resetInitSegment(audioCodec, videoCodec, duration) {
this._id3Track = {
type: 'id3',
id: 0,
pid: -1,
inputTimeScale: 90000,
sequenceNumber: 0,
samples: [],
dropped: 0
};
};
_proto.resetTimeStamp = function resetTimeStamp() {};
_proto.resetContiguity = function resetContiguity() {};
_proto.canParse = function canParse(data, offset) {
return false;
};
_proto.appendFrame = function appendFrame(track, data, offset) {} // feed incoming data to the front of the parsing pipeline
;
_proto.demux = function demux(data, timeOffset) {
if (this.cachedData) {
data = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_3__["appendUint8Array"])(this.cachedData, data);
this.cachedData = null;
}
var id3Data = _demux_id3__WEBPACK_IMPORTED_MODULE_1__["getID3Data"](data, 0);
var offset = id3Data ? id3Data.length : 0;
var lastDataIndex;
var pts;
var track = this._audioTrack;
var id3Track = this._id3Track;
var timestamp = id3Data ? _demux_id3__WEBPACK_IMPORTED_MODULE_1__["getTimeStamp"](id3Data) : undefined;
var length = data.length;
if (this.frameIndex === 0 || this.initPTS === null) {
this.initPTS = initPTSFn(timestamp, timeOffset);
} // more expressive than alternative: id3Data?.length
if (id3Data && id3Data.length > 0) {
id3Track.samples.push({
pts: this.initPTS,
dts: this.initPTS,
data: id3Data
});
}
pts = this.initPTS;
while (offset < length) {
if (this.canParse(data, offset)) {
var frame = this.appendFrame(track, data, offset);
if (frame) {
this.frameIndex++;
pts = frame.sample.pts;
offset += frame.length;
lastDataIndex = offset;
} else {
offset = length;
}
} else if (_demux_id3__WEBPACK_IMPORTED_MODULE_1__["canParse"](data, offset)) {
// after a ID3.canParse, a call to ID3.getID3Data *should* always returns some data
id3Data = _demux_id3__WEBPACK_IMPORTED_MODULE_1__["getID3Data"](data, offset);
id3Track.samples.push({
pts: pts,
dts: pts,
data: id3Data
});
offset += id3Data.length;
lastDataIndex = offset;
} else {
offset++;
}
if (offset === length && lastDataIndex !== length) {
var partialData = Object(_utils_typed_array__WEBPACK_IMPORTED_MODULE_4__["sliceUint8"])(data, lastDataIndex);
if (this.cachedData) {
this.cachedData = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_3__["appendUint8Array"])(this.cachedData, partialData);
} else {
this.cachedData = partialData;
}
}
}
return {
audioTrack: track,
avcTrack: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_2__["dummyTrack"])(),
id3Track: id3Track,
textTrack: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_2__["dummyTrack"])()
};
};
_proto.demuxSampleAes = function demuxSampleAes(data, keyData, timeOffset) {
return Promise.reject(new Error("[" + this + "] This demuxer does not support Sample-AES decryption"));
};
_proto.flush = function flush(timeOffset) {
// Parse cache in case of remaining frames.
var cachedData = this.cachedData;
if (cachedData) {
this.cachedData = null;
this.demux(cachedData, 0);
}
this.frameIndex = 0;
return {
audioTrack: this._audioTrack,
avcTrack: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_2__["dummyTrack"])(),
id3Track: this._id3Track,
textTrack: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_2__["dummyTrack"])()
};
};
_proto.destroy = function destroy() {};
return BaseAudioDemuxer;
}();
/**
* Initialize PTS
* <p>
* use timestamp unless it is undefined, NaN or Infinity
* </p>
*/
var initPTSFn = function initPTSFn(timestamp, timeOffset) {
return Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(timestamp) ? timestamp * 90 : timeOffset * 90000;
};
/* harmony default export */ __webpack_exports__["default"] = (BaseAudioDemuxer);
/***/ }),
/***/ "./src/demux/chunk-cache.ts":
/*!**********************************!*\
!*** ./src/demux/chunk-cache.ts ***!
\**********************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return ChunkCache; });
var ChunkCache = /*#__PURE__*/function () {
function ChunkCache() {
this.chunks = [];
this.dataLength = 0;
}
var _proto = ChunkCache.prototype;
_proto.push = function push(chunk) {
this.chunks.push(chunk);
this.dataLength += chunk.length;
};
_proto.flush = function flush() {
var chunks = this.chunks,
dataLength = this.dataLength;
var result;
if (!chunks.length) {
return new Uint8Array(0);
} else if (chunks.length === 1) {
result = chunks[0];
} else {
result = concatUint8Arrays(chunks, dataLength);
}
this.reset();
return result;
};
_proto.reset = function reset() {
this.chunks.length = 0;
this.dataLength = 0;
};
return ChunkCache;
}();
function concatUint8Arrays(chunks, dataLength) {
var result = new Uint8Array(dataLength);
var offset = 0;
for (var i = 0; i < chunks.length; i++) {
var chunk = chunks[i];
result.set(chunk, offset);
offset += chunk.length;
}
return result;
}
/***/ }),
/***/ "./src/demux/dummy-demuxed-track.ts":
/*!******************************************!*\
!*** ./src/demux/dummy-demuxed-track.ts ***!
\******************************************/
/*! exports provided: dummyTrack */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dummyTrack", function() { return dummyTrack; });
function dummyTrack() {
return {
type: '',
id: -1,
pid: -1,
inputTimeScale: 90000,
sequenceNumber: -1,
samples: [],
dropped: 0
};
}
/***/ }),
/***/ "./src/demux/exp-golomb.ts":
/*!*********************************!*\
!*** ./src/demux/exp-golomb.ts ***!
\*********************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/**
* Parser for exponential Golomb codes, a variable-bitwidth number encoding scheme used by h264.
*/
var ExpGolomb = /*#__PURE__*/function () {
function ExpGolomb(data) {
this.data = void 0;
this.bytesAvailable = void 0;
this.word = void 0;
this.bitsAvailable = void 0;
this.data = data; // the number of bytes left to examine in this.data
this.bytesAvailable = data.byteLength; // the current word being examined
this.word = 0; // :uint
// the number of bits left to examine in the current word
this.bitsAvailable = 0; // :uint
} // ():void
var _proto = ExpGolomb.prototype;
_proto.loadWord = function loadWord() {
var data = this.data;
var bytesAvailable = this.bytesAvailable;
var position = data.byteLength - bytesAvailable;
var workingBytes = new Uint8Array(4);
var availableBytes = Math.min(4, bytesAvailable);
if (availableBytes === 0) {
throw new Error('no bytes available');
}
workingBytes.set(data.subarray(position, position + availableBytes));
this.word = new DataView(workingBytes.buffer).getUint32(0); // track the amount of this.data that has been processed
this.bitsAvailable = availableBytes * 8;
this.bytesAvailable -= availableBytes;
} // (count:int):void
;
_proto.skipBits = function skipBits(count) {
var skipBytes; // :int
if (this.bitsAvailable > count) {
this.word <<= count;
this.bitsAvailable -= count;
} else {
count -= this.bitsAvailable;
skipBytes = count >> 3;
count -= skipBytes >> 3;
this.bytesAvailable -= skipBytes;
this.loadWord();
this.word <<= count;
this.bitsAvailable -= count;
}
} // (size:int):uint
;
_proto.readBits = function readBits(size) {
var bits = Math.min(this.bitsAvailable, size); // :uint
var valu = this.word >>> 32 - bits; // :uint
if (size > 32) {
_utils_logger__WEBPACK_IMPORTED_MODULE_0__["logger"].error('Cannot read more than 32 bits at a time');
}
this.bitsAvailable -= bits;
if (this.bitsAvailable > 0) {
this.word <<= bits;
} else if (this.bytesAvailable > 0) {
this.loadWord();
}
bits = size - bits;
if (bits > 0 && this.bitsAvailable) {
return valu << bits | this.readBits(bits);
} else {
return valu;
}
} // ():uint
;
_proto.skipLZ = function skipLZ() {
var leadingZeroCount; // :uint
for (leadingZeroCount = 0; leadingZeroCount < this.bitsAvailable; ++leadingZeroCount) {
if ((this.word & 0x80000000 >>> leadingZeroCount) !== 0) {
// the first bit of working word is 1
this.word <<= leadingZeroCount;
this.bitsAvailable -= leadingZeroCount;
return leadingZeroCount;
}
} // we exhausted word and still have not found a 1
this.loadWord();
return leadingZeroCount + this.skipLZ();
} // ():void
;
_proto.skipUEG = function skipUEG() {
this.skipBits(1 + this.skipLZ());
} // ():void
;
_proto.skipEG = function skipEG() {
this.skipBits(1 + this.skipLZ());
} // ():uint
;
_proto.readUEG = function readUEG() {
var clz = this.skipLZ(); // :uint
return this.readBits(clz + 1) - 1;
} // ():int
;
_proto.readEG = function readEG() {
var valu = this.readUEG(); // :int
if (0x01 & valu) {
// the number is odd if the low order bit is set
return 1 + valu >>> 1; // add 1 to make it even, and divide by 2
} else {
return -1 * (valu >>> 1); // divide by two then make it negative
}
} // Some convenience functions
// :Boolean
;
_proto.readBoolean = function readBoolean() {
return this.readBits(1) === 1;
} // ():int
;
_proto.readUByte = function readUByte() {
return this.readBits(8);
} // ():int
;
_proto.readUShort = function readUShort() {
return this.readBits(16);
} // ():int
;
_proto.readUInt = function readUInt() {
return this.readBits(32);
}
/**
* Advance the ExpGolomb decoder past a scaling list. The scaling
* list is optionally transmitted as part of a sequence parameter
* set and is not relevant to transmuxing.
* @param count the number of entries in this scaling list
* @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1
*/
;
_proto.skipScalingList = function skipScalingList(count) {
var lastScale = 8;
var nextScale = 8;
var deltaScale;
for (var j = 0; j < count; j++) {
if (nextScale !== 0) {
deltaScale = this.readEG();
nextScale = (lastScale + deltaScale + 256) % 256;
}
lastScale = nextScale === 0 ? lastScale : nextScale;
}
}
/**
* Read a sequence parameter set and return some interesting video
* properties. A sequence parameter set is the H264 metadata that
* describes the properties of upcoming video frames.
* @param data {Uint8Array} the bytes of a sequence parameter set
* @return {object} an object with configuration parsed from the
* sequence parameter set, including the dimensions of the
* associated video frames.
*/
;
_proto.readSPS = function readSPS() {
var frameCropLeftOffset = 0;
var frameCropRightOffset = 0;
var frameCropTopOffset = 0;
var frameCropBottomOffset = 0;
var numRefFramesInPicOrderCntCycle;
var scalingListCount;
var i;
var readUByte = this.readUByte.bind(this);
var readBits = this.readBits.bind(this);
var readUEG = this.readUEG.bind(this);
var readBoolean = this.readBoolean.bind(this);
var skipBits = this.skipBits.bind(this);
var skipEG = this.skipEG.bind(this);
var skipUEG = this.skipUEG.bind(this);
var skipScalingList = this.skipScalingList.bind(this);
readUByte();
var profileIdc = readUByte(); // profile_idc
readBits(5); // profileCompat constraint_set[0-4]_flag, u(5)
skipBits(3); // reserved_zero_3bits u(3),
readUByte(); // level_idc u(8)
skipUEG(); // seq_parameter_set_id
// some profiles have more optional data we don't need
if (profileIdc === 100 || profileIdc === 110 || profileIdc === 122 || profileIdc === 244 || profileIdc === 44 || profileIdc === 83 || profileIdc === 86 || profileIdc === 118 || profileIdc === 128) {
var chromaFormatIdc = readUEG();
if (chromaFormatIdc === 3) {
skipBits(1);
} // separate_colour_plane_flag
skipUEG(); // bit_depth_luma_minus8
skipUEG(); // bit_depth_chroma_minus8
skipBits(1); // qpprime_y_zero_transform_bypass_flag
if (readBoolean()) {
// seq_scaling_matrix_present_flag
scalingListCount = chromaFormatIdc !== 3 ? 8 : 12;
for (i = 0; i < scalingListCount; i++) {
if (readBoolean()) {
// seq_scaling_list_present_flag[ i ]
if (i < 6) {
skipScalingList(16);
} else {
skipScalingList(64);
}
}
}
}
}
skipUEG(); // log2_max_frame_num_minus4
var picOrderCntType = readUEG();
if (picOrderCntType === 0) {
readUEG(); // log2_max_pic_order_cnt_lsb_minus4
} else if (picOrderCntType === 1) {
skipBits(1); // delta_pic_order_always_zero_flag
skipEG(); // offset_for_non_ref_pic
skipEG(); // offset_for_top_to_bottom_field
numRefFramesInPicOrderCntCycle = readUEG();
for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) {
skipEG();
} // offset_for_ref_frame[ i ]
}
skipUEG(); // max_num_ref_frames
skipBits(1); // gaps_in_frame_num_value_allowed_flag
var picWidthInMbsMinus1 = readUEG();
var picHeightInMapUnitsMinus1 = readUEG();
var frameMbsOnlyFlag = readBits(1);
if (frameMbsOnlyFlag === 0) {
skipBits(1);
} // mb_adaptive_frame_field_flag
skipBits(1); // direct_8x8_inference_flag
if (readBoolean()) {
// frame_cropping_flag
frameCropLeftOffset = readUEG();
frameCropRightOffset = readUEG();
frameCropTopOffset = readUEG();
frameCropBottomOffset = readUEG();
}
var pixelRatio = [1, 1];
if (readBoolean()) {
// vui_parameters_present_flag
if (readBoolean()) {
// aspect_ratio_info_present_flag
var aspectRatioIdc = readUByte();
switch (aspectRatioIdc) {
case 1:
pixelRatio = [1, 1];
break;
case 2:
pixelRatio = [12, 11];
break;
case 3:
pixelRatio = [10, 11];
break;
case 4:
pixelRatio = [16, 11];
break;
case 5:
pixelRatio = [40, 33];
break;
case 6:
pixelRatio = [24, 11];
break;
case 7:
pixelRatio = [20, 11];
break;
case 8:
pixelRatio = [32, 11];
break;
case 9:
pixelRatio = [80, 33];
break;
case 10:
pixelRatio = [18, 11];
break;
case 11:
pixelRatio = [15, 11];
break;
case 12:
pixelRatio = [64, 33];
break;
case 13:
pixelRatio = [160, 99];
break;
case 14:
pixelRatio = [4, 3];
break;
case 15:
pixelRatio = [3, 2];
break;
case 16:
pixelRatio = [2, 1];
break;
case 255:
{
pixelRatio = [readUByte() << 8 | readUByte(), readUByte() << 8 | readUByte()];
break;
}
}
}
}
return {
width: Math.ceil((picWidthInMbsMinus1 + 1) * 16 - frameCropLeftOffset * 2 - frameCropRightOffset * 2),
height: (2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16 - (frameMbsOnlyFlag ? 2 : 4) * (frameCropTopOffset + frameCropBottomOffset),
pixelRatio: pixelRatio
};
};
_proto.readSliceType = function readSliceType() {
// skip NALu type
this.readUByte(); // discard first_mb_in_slice
this.readUEG(); // return slice_type
return this.readUEG();
};
return ExpGolomb;
}();
/* harmony default export */ __webpack_exports__["default"] = (ExpGolomb);
/***/ }),
/***/ "./src/demux/id3.ts":
/*!**************************!*\
!*** ./src/demux/id3.ts ***!
\**************************/
/*! exports provided: isHeader, isFooter, getID3Data, canParse, getTimeStamp, isTimeStampFrame, getID3Frames, decodeFrame, utf8ArrayToStr, testables */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isHeader", function() { return isHeader; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isFooter", function() { return isFooter; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getID3Data", function() { return getID3Data; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "canParse", function() { return canParse; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getTimeStamp", function() { return getTimeStamp; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isTimeStampFrame", function() { return isTimeStampFrame; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getID3Frames", function() { return getID3Frames; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "decodeFrame", function() { return decodeFrame; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "utf8ArrayToStr", function() { return utf8ArrayToStr; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "testables", function() { return testables; });
// breaking up those two types in order to clarify what is happening in the decoding path.
/**
* Returns true if an ID3 header can be found at offset in data
* @param {Uint8Array} data - The data to search in
* @param {number} offset - The offset at which to start searching
* @return {boolean} - True if an ID3 header is found
*/
var isHeader = function isHeader(data, offset) {
/*
* http://id3.org/id3v2.3.0
* [0] = 'I'
* [1] = 'D'
* [2] = '3'
* [3,4] = {Version}
* [5] = {Flags}
* [6-9] = {ID3 Size}
*
* An ID3v2 tag can be detected with the following pattern:
* $49 44 33 yy yy xx zz zz zz zz
* Where yy is less than $FF, xx is the 'flags' byte and zz is less than $80
*/
if (offset + 10 <= data.length) {
// look for 'ID3' identifier
if (data[offset] === 0x49 && data[offset + 1] === 0x44 && data[offset + 2] === 0x33) {
// check version is within range
if (data[offset + 3] < 0xff && data[offset + 4] < 0xff) {
// check size is within range
if (data[offset + 6] < 0x80 && data[offset + 7] < 0x80 && data[offset + 8] < 0x80 && data[offset + 9] < 0x80) {
return true;
}
}
}
}
return false;
};
/**
* Returns true if an ID3 footer can be found at offset in data
* @param {Uint8Array} data - The data to search in
* @param {number} offset - The offset at which to start searching
* @return {boolean} - True if an ID3 footer is found
*/
var isFooter = function isFooter(data, offset) {
/*
* The footer is a copy of the header, but with a different identifier
*/
if (offset + 10 <= data.length) {
// look for '3DI' identifier
if (data[offset] === 0x33 && data[offset + 1] === 0x44 && data[offset + 2] === 0x49) {
// check version is within range
if (data[offset + 3] < 0xff && data[offset + 4] < 0xff) {
// check size is within range
if (data[offset + 6] < 0x80 && data[offset + 7] < 0x80 && data[offset + 8] < 0x80 && data[offset + 9] < 0x80) {
return true;
}
}
}
}
return false;
};
/**
* Returns any adjacent ID3 tags found in data starting at offset, as one block of data
* @param {Uint8Array} data - The data to search in
* @param {number} offset - The offset at which to start searching
* @return {Uint8Array | undefined} - The block of data containing any ID3 tags found
* or *undefined* if no header is found at the starting offset
*/
var getID3Data = function getID3Data(data, offset) {
var front = offset;
var length = 0;
while (isHeader(data, offset)) {
// ID3 header is 10 bytes
length += 10;
var size = readSize(data, offset + 6);
length += size;
if (isFooter(data, offset + 10)) {
// ID3 footer is 10 bytes
length += 10;
}
offset += length;
}
if (length > 0) {
return data.subarray(front, front + length);
}
return undefined;
};
var readSize = function readSize(data, offset) {
var size = 0;
size = (data[offset] & 0x7f) << 21;
size |= (data[offset + 1] & 0x7f) << 14;
size |= (data[offset + 2] & 0x7f) << 7;
size |= data[offset + 3] & 0x7f;
return size;
};
var canParse = function canParse(data, offset) {
return isHeader(data, offset) && readSize(data, offset + 6) + 10 <= data.length - offset;
};
/**
* Searches for the Elementary Stream timestamp found in the ID3 data chunk
* @param {Uint8Array} data - Block of data containing one or more ID3 tags
* @return {number | undefined} - The timestamp
*/
var getTimeStamp = function getTimeStamp(data) {
var frames = getID3Frames(data);
for (var i = 0; i < frames.length; i++) {
var frame = frames[i];
if (isTimeStampFrame(frame)) {
return readTimeStamp(frame);
}
}
return undefined;
};
/**
* Returns true if the ID3 frame is an Elementary Stream timestamp frame
* @param {ID3 frame} frame
*/
var isTimeStampFrame = function isTimeStampFrame(frame) {
return frame && frame.key === 'PRIV' && frame.info === 'com.apple.streaming.transportStreamTimestamp';
};
var getFrameData = function getFrameData(data) {
/*
Frame ID $xx xx xx xx (four characters)
Size $xx xx xx xx
Flags $xx xx
*/
var type = String.fromCharCode(data[0], data[1], data[2], data[3]);
var size = readSize(data, 4); // skip frame id, size, and flags
var offset = 10;
return {
type: type,
size: size,
data: data.subarray(offset, offset + size)
};
};
/**
* Returns an array of ID3 frames found in all the ID3 tags in the id3Data
* @param {Uint8Array} id3Data - The ID3 data containing one or more ID3 tags
* @return {ID3.Frame[]} - Array of ID3 frame objects
*/
var getID3Frames = function getID3Frames(id3Data) {
var offset = 0;
var frames = [];
while (isHeader(id3Data, offset)) {
var size = readSize(id3Data, offset + 6); // skip past ID3 header
offset += 10;
var end = offset + size; // loop through frames in the ID3 tag
while (offset + 8 < end) {
var frameData = getFrameData(id3Data.subarray(offset));
var frame = decodeFrame(frameData);
if (frame) {
frames.push(frame);
} // skip frame header and frame data
offset += frameData.size + 10;
}
if (isFooter(id3Data, offset)) {
offset += 10;
}
}
return frames;
};
var decodeFrame = function decodeFrame(frame) {
if (frame.type === 'PRIV') {
return decodePrivFrame(frame);
} else if (frame.type[0] === 'W') {
return decodeURLFrame(frame);
}
return decodeTextFrame(frame);
};
var decodePrivFrame = function decodePrivFrame(frame) {
/*
Format: <text string>\0<binary data>
*/
if (frame.size < 2) {
return undefined;
}
var owner = utf8ArrayToStr(frame.data, true);
var privateData = new Uint8Array(frame.data.subarray(owner.length + 1));
return {
key: frame.type,
info: owner,
data: privateData.buffer
};
};
var decodeTextFrame = function decodeTextFrame(frame) {
if (frame.size < 2) {
return undefined;
}
if (frame.type === 'TXXX') {
/*
Format:
[0] = {Text Encoding}
[1-?] = {Description}\0{Value}
*/
var index = 1;
var description = utf8ArrayToStr(frame.data.subarray(index), true);
index += description.length + 1;
var value = utf8ArrayToStr(frame.data.subarray(index));
return {
key: frame.type,
info: description,
data: value
};
}
/*
Format:
[0] = {Text Encoding}
[1-?] = {Value}
*/
var text = utf8ArrayToStr(frame.data.subarray(1));
return {
key: frame.type,
data: text
};
};
var decodeURLFrame = function decodeURLFrame(frame) {
if (frame.type === 'WXXX') {
/*
Format:
[0] = {Text Encoding}
[1-?] = {Description}\0{URL}
*/
if (frame.size < 2) {
return undefined;
}
var index = 1;
var description = utf8ArrayToStr(frame.data.subarray(index), true);
index += description.length + 1;
var value = utf8ArrayToStr(frame.data.subarray(index));
return {
key: frame.type,
info: description,
data: value
};
}
/*
Format:
[0-?] = {URL}
*/
var url = utf8ArrayToStr(frame.data);
return {
key: frame.type,
data: url
};
};
var readTimeStamp = function readTimeStamp(timeStampFrame) {
if (timeStampFrame.data.byteLength === 8) {
var data = new Uint8Array(timeStampFrame.data); // timestamp is 33 bit expressed as a big-endian eight-octet number,
// with the upper 31 bits set to zero.
var pts33Bit = data[3] & 0x1;
var timestamp = (data[4] << 23) + (data[5] << 15) + (data[6] << 7) + data[7];
timestamp /= 45;
if (pts33Bit) {
timestamp += 47721858.84;
} // 2^32 / 90
return Math.round(timestamp);
}
return undefined;
}; // http://stackoverflow.com/questions/8936984/uint8array-to-string-in-javascript/22373197
// http://www.onicos.com/staff/iz/amuse/javascript/expert/utf.txt
/* utf.js - UTF-8 <=> UTF-16 convertion
*
* Copyright (C) 1999 Masanao Izumo <iz@onicos.co.jp>
* Version: 1.0
* LastModified: Dec 25 1999
* This library is free. You can redistribute it and/or modify it.
*/
var utf8ArrayToStr = function utf8ArrayToStr(array, exitOnNull) {
if (exitOnNull === void 0) {
exitOnNull = false;
}
var decoder = getTextDecoder();
if (decoder) {
var decoded = decoder.decode(array);
if (exitOnNull) {
// grab up to the first null
var idx = decoded.indexOf('\0');
return idx !== -1 ? decoded.substring(0, idx) : decoded;
} // remove any null characters
return decoded.replace(/\0/g, '');
}
var len = array.length;
var c;
var char2;
var char3;
var out = '';
var i = 0;
while (i < len) {
c = array[i++];
if (c === 0x00 && exitOnNull) {
return out;
} else if (c === 0x00 || c === 0x03) {
// If the character is 3 (END_OF_TEXT) or 0 (NULL) then skip it
continue;
}
switch (c >> 4) {
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
// 0xxxxxxx
out += String.fromCharCode(c);
break;
case 12:
case 13:
// 110x xxxx 10xx xxxx
char2 = array[i++];
out += String.fromCharCode((c & 0x1f) << 6 | char2 & 0x3f);
break;
case 14:
// 1110 xxxx 10xx xxxx 10xx xxxx
char2 = array[i++];
char3 = array[i++];
out += String.fromCharCode((c & 0x0f) << 12 | (char2 & 0x3f) << 6 | (char3 & 0x3f) << 0);
break;
default:
}
}
return out;
};
var testables = {
decodeTextFrame: decodeTextFrame
};
var decoder;
function getTextDecoder() {
if (!decoder && typeof self.TextDecoder !== 'undefined') {
decoder = new self.TextDecoder('utf-8');
}
return decoder;
}
/***/ }),
/***/ "./src/demux/mp3demuxer.ts":
/*!*********************************!*\
!*** ./src/demux/mp3demuxer.ts ***!
\*********************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _base_audio_demuxer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base-audio-demuxer */ "./src/demux/base-audio-demuxer.ts");
/* harmony import */ var _demux_id3__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../demux/id3 */ "./src/demux/id3.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/* harmony import */ var _mpegaudio__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./mpegaudio */ "./src/demux/mpegaudio.ts");
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
/**
* MP3 demuxer
*/
var MP3Demuxer = /*#__PURE__*/function (_BaseAudioDemuxer) {
_inheritsLoose(MP3Demuxer, _BaseAudioDemuxer);
function MP3Demuxer() {
return _BaseAudioDemuxer.apply(this, arguments) || this;
}
var _proto = MP3Demuxer.prototype;
_proto.resetInitSegment = function resetInitSegment(audioCodec, videoCodec, duration) {
_BaseAudioDemuxer.prototype.resetInitSegment.call(this, audioCodec, videoCodec, duration);
this._audioTrack = {
container: 'audio/mpeg',
type: 'audio',
id: 0,
pid: -1,
sequenceNumber: 0,
isAAC: false,
samples: [],
manifestCodec: audioCodec,
duration: duration,
inputTimeScale: 90000,
dropped: 0
};
};
MP3Demuxer.probe = function probe(data) {
if (!data) {
return false;
} // check if data contains ID3 timestamp and MPEG sync word
// Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1
// Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III)
// More info http://www.mp3-tech.org/programmer/frame_header.html
var id3Data = _demux_id3__WEBPACK_IMPORTED_MODULE_1__["getID3Data"](data, 0) || [];
var offset = id3Data.length;
for (var length = data.length; offset < length; offset++) {
if (_mpegaudio__WEBPACK_IMPORTED_MODULE_3__["probe"](data, offset)) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('MPEG Audio sync word found !');
return true;
}
}
return false;
};
_proto.canParse = function canParse(data, offset) {
return _mpegaudio__WEBPACK_IMPORTED_MODULE_3__["canParse"](data, offset);
};
_proto.appendFrame = function appendFrame(track, data, offset) {
if (this.initPTS === null) {
return;
}
return _mpegaudio__WEBPACK_IMPORTED_MODULE_3__["appendFrame"](track, data, offset, this.initPTS, this.frameIndex);
};
return MP3Demuxer;
}(_base_audio_demuxer__WEBPACK_IMPORTED_MODULE_0__["default"]);
MP3Demuxer.minProbeByteLength = 4;
/* harmony default export */ __webpack_exports__["default"] = (MP3Demuxer);
/***/ }),
/***/ "./src/demux/mp4demuxer.ts":
/*!*********************************!*\
!*** ./src/demux/mp4demuxer.ts ***!
\*********************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/mp4-tools */ "./src/utils/mp4-tools.ts");
/* harmony import */ var _dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./dummy-demuxed-track */ "./src/demux/dummy-demuxed-track.ts");
/**
* MP4 demuxer
*/
var MP4Demuxer = /*#__PURE__*/function () {
function MP4Demuxer(observer, config) {
this.remainderData = null;
this.config = void 0;
this.config = config;
}
var _proto = MP4Demuxer.prototype;
_proto.resetTimeStamp = function resetTimeStamp() {};
_proto.resetInitSegment = function resetInitSegment() {};
_proto.resetContiguity = function resetContiguity() {};
MP4Demuxer.probe = function probe(data) {
// ensure we find a moof box in the first 16 kB
return Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_0__["findBox"])({
data: data,
start: 0,
end: Math.min(data.length, 16384)
}, ['moof']).length > 0;
};
_proto.demux = function demux(data) {
// Load all data into the avc track. The CMAF remuxer will look for the data in the samples object; the rest of the fields do not matter
var avcSamples = data;
var avcTrack = Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__["dummyTrack"])();
if (this.config.progressive) {
// Split the bytestream into two ranges: one encompassing all data up until the start of the last moof, and everything else.
// This is done to guarantee that we're sending valid data to MSE - when demuxing progressively, we have no guarantee
// that the fetch loader gives us flush moof+mdat pairs. If we push jagged data to MSE, it will throw an exception.
if (this.remainderData) {
avcSamples = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_0__["appendUint8Array"])(this.remainderData, data);
}
var segmentedData = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_0__["segmentValidRange"])(avcSamples);
this.remainderData = segmentedData.remainder;
avcTrack.samples = segmentedData.valid || new Uint8Array();
} else {
avcTrack.samples = avcSamples;
}
return {
audioTrack: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__["dummyTrack"])(),
avcTrack: avcTrack,
id3Track: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__["dummyTrack"])(),
textTrack: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__["dummyTrack"])()
};
};
_proto.flush = function flush() {
var avcTrack = Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__["dummyTrack"])();
avcTrack.samples = this.remainderData || new Uint8Array();
this.remainderData = null;
return {
audioTrack: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__["dummyTrack"])(),
avcTrack: avcTrack,
id3Track: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__["dummyTrack"])(),
textTrack: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__["dummyTrack"])()
};
};
_proto.demuxSampleAes = function demuxSampleAes(data, keyData, timeOffset) {
return Promise.reject(new Error('The MP4 demuxer does not support SAMPLE-AES decryption'));
};
_proto.destroy = function destroy() {};
return MP4Demuxer;
}();
MP4Demuxer.minProbeByteLength = 1024;
/* harmony default export */ __webpack_exports__["default"] = (MP4Demuxer);
/***/ }),
/***/ "./src/demux/mpegaudio.ts":
/*!********************************!*\
!*** ./src/demux/mpegaudio.ts ***!
\********************************/
/*! exports provided: appendFrame, parseHeader, isHeaderPattern, isHeader, canParse, probe */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "appendFrame", function() { return appendFrame; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseHeader", function() { return parseHeader; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isHeaderPattern", function() { return isHeaderPattern; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isHeader", function() { return isHeader; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "canParse", function() { return canParse; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "probe", function() { return probe; });
/**
* MPEG parser helper
*/
var chromeVersion = null;
var BitratesMap = [32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160];
var SamplingRateMap = [44100, 48000, 32000, 22050, 24000, 16000, 11025, 12000, 8000];
var SamplesCoefficients = [// MPEG 2.5
[0, // Reserved
72, // Layer3
144, // Layer2
12 // Layer1
], // Reserved
[0, // Reserved
0, // Layer3
0, // Layer2
0 // Layer1
], // MPEG 2
[0, // Reserved
72, // Layer3
144, // Layer2
12 // Layer1
], // MPEG 1
[0, // Reserved
144, // Layer3
144, // Layer2
12 // Layer1
]];
var BytesInSlot = [0, // Reserved
1, // Layer3
1, // Layer2
4 // Layer1
];
function appendFrame(track, data, offset, pts, frameIndex) {
// Using http://www.datavoyage.com/mpgscript/mpeghdr.htm as a reference
if (offset + 24 > data.length) {
return;
}
var header = parseHeader(data, offset);
if (header && offset + header.frameLength <= data.length) {
var frameDuration = header.samplesPerFrame * 90000 / header.sampleRate;
var stamp = pts + frameIndex * frameDuration;
var sample = {
unit: data.subarray(offset, offset + header.frameLength),
pts: stamp,
dts: stamp
};
track.config = [];
track.channelCount = header.channelCount;
track.samplerate = header.sampleRate;
track.samples.push(sample);
return {
sample: sample,
length: header.frameLength,
missing: 0
};
}
}
function parseHeader(data, offset) {
var mpegVersion = data[offset + 1] >> 3 & 3;
var mpegLayer = data[offset + 1] >> 1 & 3;
var bitRateIndex = data[offset + 2] >> 4 & 15;
var sampleRateIndex = data[offset + 2] >> 2 & 3;
if (mpegVersion !== 1 && bitRateIndex !== 0 && bitRateIndex !== 15 && sampleRateIndex !== 3) {
var paddingBit = data[offset + 2] >> 1 & 1;
var channelMode = data[offset + 3] >> 6;
var columnInBitrates = mpegVersion === 3 ? 3 - mpegLayer : mpegLayer === 3 ? 3 : 4;
var bitRate = BitratesMap[columnInBitrates * 14 + bitRateIndex - 1] * 1000;
var columnInSampleRates = mpegVersion === 3 ? 0 : mpegVersion === 2 ? 1 : 2;
var sampleRate = SamplingRateMap[columnInSampleRates * 3 + sampleRateIndex];
var channelCount = channelMode === 3 ? 1 : 2; // If bits of channel mode are `11` then it is a single channel (Mono)
var sampleCoefficient = SamplesCoefficients[mpegVersion][mpegLayer];
var bytesInSlot = BytesInSlot[mpegLayer];
var samplesPerFrame = sampleCoefficient * 8 * bytesInSlot;
var frameLength = Math.floor(sampleCoefficient * bitRate / sampleRate + paddingBit) * bytesInSlot;
if (chromeVersion === null) {
var userAgent = navigator.userAgent || '';
var result = userAgent.match(/Chrome\/(\d+)/i);
chromeVersion = result ? parseInt(result[1]) : 0;
}
var needChromeFix = !!chromeVersion && chromeVersion <= 87;
if (needChromeFix && mpegLayer === 2 && bitRate >= 224000 && channelMode === 0) {
// Work around bug in Chromium by setting channelMode to dual-channel (01) instead of stereo (00)
data[offset + 3] = data[offset + 3] | 0x80;
}
return {
sampleRate: sampleRate,
channelCount: channelCount,
frameLength: frameLength,
samplesPerFrame: samplesPerFrame
};
}
}
function isHeaderPattern(data, offset) {
return data[offset] === 0xff && (data[offset + 1] & 0xe0) === 0xe0 && (data[offset + 1] & 0x06) !== 0x00;
}
function isHeader(data, offset) {
// Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1
// Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III)
// More info http://www.mp3-tech.org/programmer/frame_header.html
return offset + 1 < data.length && isHeaderPattern(data, offset);
}
function canParse(data, offset) {
var headerSize = 4;
return isHeaderPattern(data, offset) && headerSize <= data.length - offset;
}
function probe(data, offset) {
// same as isHeader but we also check that MPEG frame follows last MPEG frame
// or end of data is reached
if (offset + 1 < data.length && isHeaderPattern(data, offset)) {
// MPEG header Length
var headerLength = 4; // MPEG frame Length
var header = parseHeader(data, offset);
var frameLength = headerLength;
if (header !== null && header !== void 0 && header.frameLength) {
frameLength = header.frameLength;
}
var newOffset = offset + frameLength;
return newOffset === data.length || isHeader(data, newOffset);
}
return false;
}
/***/ }),
/***/ "./src/demux/sample-aes.ts":
/*!*********************************!*\
!*** ./src/demux/sample-aes.ts ***!
\*********************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _crypt_decrypter__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../crypt/decrypter */ "./src/crypt/decrypter.ts");
/* harmony import */ var _tsdemuxer__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./tsdemuxer */ "./src/demux/tsdemuxer.ts");
/**
* SAMPLE-AES decrypter
*/
var SampleAesDecrypter = /*#__PURE__*/function () {
function SampleAesDecrypter(observer, config, keyData) {
this.keyData = void 0;
this.decrypter = void 0;
this.keyData = keyData;
this.decrypter = new _crypt_decrypter__WEBPACK_IMPORTED_MODULE_0__["default"](observer, config, {
removePKCS7Padding: false
});
}
var _proto = SampleAesDecrypter.prototype;
_proto.decryptBuffer = function decryptBuffer(encryptedData, callback) {
this.decrypter.decrypt(encryptedData, this.keyData.key.buffer, this.keyData.iv.buffer, callback);
} // AAC - encrypt all full 16 bytes blocks starting from offset 16
;
_proto.decryptAacSample = function decryptAacSample(samples, sampleIndex, callback, sync) {
var curUnit = samples[sampleIndex].unit;
var encryptedData = curUnit.subarray(16, curUnit.length - curUnit.length % 16);
var encryptedBuffer = encryptedData.buffer.slice(encryptedData.byteOffset, encryptedData.byteOffset + encryptedData.length);
var localthis = this;
this.decryptBuffer(encryptedBuffer, function (decryptedBuffer) {
var decryptedData = new Uint8Array(decryptedBuffer);
curUnit.set(decryptedData, 16);
if (!sync) {
localthis.decryptAacSamples(samples, sampleIndex + 1, callback);
}
});
};
_proto.decryptAacSamples = function decryptAacSamples(samples, sampleIndex, callback) {
for (;; sampleIndex++) {
if (sampleIndex >= samples.length) {
callback();
return;
}
if (samples[sampleIndex].unit.length < 32) {
continue;
}
var sync = this.decrypter.isSync();
this.decryptAacSample(samples, sampleIndex, callback, sync);
if (!sync) {
return;
}
}
} // AVC - encrypt one 16 bytes block out of ten, starting from offset 32
;
_proto.getAvcEncryptedData = function getAvcEncryptedData(decodedData) {
var encryptedDataLen = Math.floor((decodedData.length - 48) / 160) * 16 + 16;
var encryptedData = new Int8Array(encryptedDataLen);
var outputPos = 0;
for (var inputPos = 32; inputPos <= decodedData.length - 16; inputPos += 160, outputPos += 16) {
encryptedData.set(decodedData.subarray(inputPos, inputPos + 16), outputPos);
}
return encryptedData;
};
_proto.getAvcDecryptedUnit = function getAvcDecryptedUnit(decodedData, decryptedData) {
var uint8DecryptedData = new Uint8Array(decryptedData);
var inputPos = 0;
for (var outputPos = 32; outputPos <= decodedData.length - 16; outputPos += 160, inputPos += 16) {
decodedData.set(uint8DecryptedData.subarray(inputPos, inputPos + 16), outputPos);
}
return decodedData;
};
_proto.decryptAvcSample = function decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit, sync) {
var decodedData = Object(_tsdemuxer__WEBPACK_IMPORTED_MODULE_1__["discardEPB"])(curUnit.data);
var encryptedData = this.getAvcEncryptedData(decodedData);
var localthis = this;
this.decryptBuffer(encryptedData.buffer, function (decryptedBuffer) {
curUnit.data = localthis.getAvcDecryptedUnit(decodedData, decryptedBuffer);
if (!sync) {
localthis.decryptAvcSamples(samples, sampleIndex, unitIndex + 1, callback);
}
});
};
_proto.decryptAvcSamples = function decryptAvcSamples(samples, sampleIndex, unitIndex, callback) {
if (samples instanceof Uint8Array) {
throw new Error('Cannot decrypt samples of type Uint8Array');
}
for (;; sampleIndex++, unitIndex = 0) {
if (sampleIndex >= samples.length) {
callback();
return;
}
var curUnits = samples[sampleIndex].units;
for (;; unitIndex++) {
if (unitIndex >= curUnits.length) {
break;
}
var curUnit = curUnits[unitIndex];
if (curUnit.data.length <= 48 || curUnit.type !== 1 && curUnit.type !== 5) {
continue;
}
var sync = this.decrypter.isSync();
this.decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit, sync);
if (!sync) {
return;
}
}
}
};
return SampleAesDecrypter;
}();
/* harmony default export */ __webpack_exports__["default"] = (SampleAesDecrypter);
/***/ }),
/***/ "./src/demux/transmuxer-interface.ts":
/*!*******************************************!*\
!*** ./src/demux/transmuxer-interface.ts ***!
\*******************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return TransmuxerInterface; });
/* harmony import */ var webworkify_webpack__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! webworkify-webpack */ "./node_modules/webworkify-webpack/index.js");
/* harmony import */ var webworkify_webpack__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(webworkify_webpack__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _demux_transmuxer__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../demux/transmuxer */ "./src/demux/transmuxer.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
/* harmony import */ var _utils_mediasource_helper__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/mediasource-helper */ "./src/utils/mediasource-helper.ts");
/* harmony import */ var eventemitter3__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! eventemitter3 */ "./node_modules/eventemitter3/index.js");
/* harmony import */ var eventemitter3__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(eventemitter3__WEBPACK_IMPORTED_MODULE_6__);
var MediaSource = Object(_utils_mediasource_helper__WEBPACK_IMPORTED_MODULE_5__["getMediaSource"])() || {
isTypeSupported: function isTypeSupported() {
return false;
}
};
var TransmuxerInterface = /*#__PURE__*/function () {
function TransmuxerInterface(hls, id, onTransmuxComplete, onFlush) {
var _this = this;
this.hls = void 0;
this.id = void 0;
this.observer = void 0;
this.frag = null;
this.part = null;
this.worker = void 0;
this.onwmsg = void 0;
this.transmuxer = null;
this.onTransmuxComplete = void 0;
this.onFlush = void 0;
this.hls = hls;
this.id = id;
this.onTransmuxComplete = onTransmuxComplete;
this.onFlush = onFlush;
var config = hls.config;
var forwardMessage = function forwardMessage(ev, data) {
data = data || {};
data.frag = _this.frag;
data.id = _this.id;
hls.trigger(ev, data);
}; // forward events to main thread
this.observer = new eventemitter3__WEBPACK_IMPORTED_MODULE_6__["EventEmitter"]();
this.observer.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_DECRYPTED, forwardMessage);
this.observer.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, forwardMessage);
var typeSupported = {
mp4: MediaSource.isTypeSupported('video/mp4'),
mpeg: MediaSource.isTypeSupported('audio/mpeg'),
mp3: MediaSource.isTypeSupported('audio/mp4; codecs="mp3"')
}; // navigator.vendor is not always available in Web Worker
// refer to https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/navigator
var vendor = navigator.vendor;
if (config.enableWorker && typeof Worker !== 'undefined') {
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].log('demuxing in webworker');
var worker;
try {
worker = this.worker = webworkify_webpack__WEBPACK_IMPORTED_MODULE_0__(/*require.resolve*/(/*! ../demux/transmuxer-worker.ts */ "./src/demux/transmuxer-worker.ts"));
this.onwmsg = this.onWorkerMessage.bind(this);
worker.addEventListener('message', this.onwmsg);
worker.onerror = function (event) {
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_4__["ErrorTypes"].OTHER_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_4__["ErrorDetails"].INTERNAL_EXCEPTION,
fatal: true,
event: 'demuxerWorker',
error: new Error(event.message + " (" + event.filename + ":" + event.lineno + ")")
});
};
worker.postMessage({
cmd: 'init',
typeSupported: typeSupported,
vendor: vendor,
id: id,
config: JSON.stringify(config)
});
} catch (err) {
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn('Error in worker:', err);
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].error('Error while initializing DemuxerWorker, fallback to inline');
if (worker) {
// revoke the Object URL that was used to create transmuxer worker, so as not to leak it
self.URL.revokeObjectURL(worker.objectURL);
}
this.transmuxer = new _demux_transmuxer__WEBPACK_IMPORTED_MODULE_2__["default"](this.observer, typeSupported, config, vendor, id);
this.worker = null;
}
} else {
this.transmuxer = new _demux_transmuxer__WEBPACK_IMPORTED_MODULE_2__["default"](this.observer, typeSupported, config, vendor, id);
}
}
var _proto = TransmuxerInterface.prototype;
_proto.destroy = function destroy() {
var w = this.worker;
if (w) {
w.removeEventListener('message', this.onwmsg);
w.terminate();
this.worker = null;
} else {
var transmuxer = this.transmuxer;
if (transmuxer) {
transmuxer.destroy();
this.transmuxer = null;
}
}
var observer = this.observer;
if (observer) {
observer.removeAllListeners();
} // @ts-ignore
this.observer = null;
};
_proto.push = function push(data, initSegmentData, audioCodec, videoCodec, frag, part, duration, accurateTimeOffset, chunkMeta, defaultInitPTS) {
var _this2 = this;
chunkMeta.transmuxing.start = self.performance.now();
var transmuxer = this.transmuxer,
worker = this.worker;
var timeOffset = part ? part.start : frag.start;
var decryptdata = frag.decryptdata;
var lastFrag = this.frag;
var discontinuity = !(lastFrag && frag.cc === lastFrag.cc);
var trackSwitch = !(lastFrag && chunkMeta.level === lastFrag.level);
var snDiff = lastFrag ? chunkMeta.sn - lastFrag.sn : -1;
var partDiff = this.part ? chunkMeta.part - this.part.index : 1;
var contiguous = !trackSwitch && (snDiff === 1 || snDiff === 0 && partDiff === 1);
var now = self.performance.now();
if (trackSwitch || snDiff || frag.stats.parsing.start === 0) {
frag.stats.parsing.start = now;
}
if (part && (partDiff || !contiguous)) {
part.stats.parsing.start = now;
}
var state = new _demux_transmuxer__WEBPACK_IMPORTED_MODULE_2__["TransmuxState"](discontinuity, contiguous, accurateTimeOffset, trackSwitch, timeOffset);
if (!contiguous || discontinuity) {
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].log("[transmuxer-interface, " + frag.type + "]: Starting new transmux session for sn: " + chunkMeta.sn + " p: " + chunkMeta.part + " level: " + chunkMeta.level + " id: " + chunkMeta.id + "\n discontinuity: " + discontinuity + "\n trackSwitch: " + trackSwitch + "\n contiguous: " + contiguous + "\n accurateTimeOffset: " + accurateTimeOffset + "\n timeOffset: " + timeOffset);
var config = new _demux_transmuxer__WEBPACK_IMPORTED_MODULE_2__["TransmuxConfig"](audioCodec, videoCodec, initSegmentData, duration, defaultInitPTS);
this.configureTransmuxer(config);
}
this.frag = frag;
this.part = part; // Frags with sn of 'initSegment' are not transmuxed
if (worker) {
// post fragment payload as transferable objects for ArrayBuffer (no copy)
worker.postMessage({
cmd: 'demux',
data: data,
decryptdata: decryptdata,
chunkMeta: chunkMeta,
state: state
}, data instanceof ArrayBuffer ? [data] : []);
} else if (transmuxer) {
var _transmuxResult = transmuxer.push(data, decryptdata, chunkMeta, state);
if (Object(_demux_transmuxer__WEBPACK_IMPORTED_MODULE_2__["isPromise"])(_transmuxResult)) {
_transmuxResult.then(function (data) {
_this2.handleTransmuxComplete(data);
});
} else {
this.handleTransmuxComplete(_transmuxResult);
}
}
};
_proto.flush = function flush(chunkMeta) {
var _this3 = this;
chunkMeta.transmuxing.start = self.performance.now();
var transmuxer = this.transmuxer,
worker = this.worker;
if (worker) {
worker.postMessage({
cmd: 'flush',
chunkMeta: chunkMeta
});
} else if (transmuxer) {
var _transmuxResult2 = transmuxer.flush(chunkMeta);
if (Object(_demux_transmuxer__WEBPACK_IMPORTED_MODULE_2__["isPromise"])(_transmuxResult2)) {
_transmuxResult2.then(function (data) {
_this3.handleFlushResult(data, chunkMeta);
});
} else {
this.handleFlushResult(_transmuxResult2, chunkMeta);
}
}
};
_proto.handleFlushResult = function handleFlushResult(results, chunkMeta) {
var _this4 = this;
results.forEach(function (result) {
_this4.handleTransmuxComplete(result);
});
this.onFlush(chunkMeta);
};
_proto.onWorkerMessage = function onWorkerMessage(ev) {
var data = ev.data;
var hls = this.hls;
switch (data.event) {
case 'init':
{
// revoke the Object URL that was used to create transmuxer worker, so as not to leak it
self.URL.revokeObjectURL(this.worker.objectURL);
break;
}
case 'transmuxComplete':
{
this.handleTransmuxComplete(data.data);
break;
}
case 'flush':
{
this.onFlush(data.data);
break;
}
/* falls through */
default:
{
data.data = data.data || {};
data.data.frag = this.frag;
data.data.id = this.id;
hls.trigger(data.event, data.data);
break;
}
}
};
_proto.configureTransmuxer = function configureTransmuxer(config) {
var worker = this.worker,
transmuxer = this.transmuxer;
if (worker) {
worker.postMessage({
cmd: 'configure',
config: config
});
} else if (transmuxer) {
transmuxer.configure(config);
}
};
_proto.handleTransmuxComplete = function handleTransmuxComplete(result) {
result.chunkMeta.transmuxing.end = self.performance.now();
this.onTransmuxComplete(result);
};
return TransmuxerInterface;
}();
/***/ }),
/***/ "./src/demux/transmuxer-worker.ts":
/*!****************************************!*\
!*** ./src/demux/transmuxer-worker.ts ***!
\****************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return TransmuxerWorker; });
/* harmony import */ var _demux_transmuxer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../demux/transmuxer */ "./src/demux/transmuxer.ts");
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/* harmony import */ var eventemitter3__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! eventemitter3 */ "./node_modules/eventemitter3/index.js");
/* harmony import */ var eventemitter3__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(eventemitter3__WEBPACK_IMPORTED_MODULE_3__);
function TransmuxerWorker(self) {
var observer = new eventemitter3__WEBPACK_IMPORTED_MODULE_3__["EventEmitter"]();
var forwardMessage = function forwardMessage(ev, data) {
self.postMessage({
event: ev,
data: data
});
}; // forward events to main thread
observer.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_DECRYPTED, forwardMessage);
observer.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, forwardMessage);
self.addEventListener('message', function (ev) {
var data = ev.data;
switch (data.cmd) {
case 'init':
{
var config = JSON.parse(data.config);
self.transmuxer = new _demux_transmuxer__WEBPACK_IMPORTED_MODULE_0__["default"](observer, data.typeSupported, config, data.vendor, data.id);
Object(_utils_logger__WEBPACK_IMPORTED_MODULE_2__["enableLogs"])(config.debug);
forwardMessage('init', null);
break;
}
case 'configure':
{
self.transmuxer.configure(data.config);
break;
}
case 'demux':
{
var transmuxResult = self.transmuxer.push(data.data, data.decryptdata, data.chunkMeta, data.state);
if (Object(_demux_transmuxer__WEBPACK_IMPORTED_MODULE_0__["isPromise"])(transmuxResult)) {
transmuxResult.then(function (data) {
emitTransmuxComplete(self, data);
});
} else {
emitTransmuxComplete(self, transmuxResult);
}
break;
}
case 'flush':
{
var id = data.chunkMeta;
var _transmuxResult = self.transmuxer.flush(id);
if (Object(_demux_transmuxer__WEBPACK_IMPORTED_MODULE_0__["isPromise"])(_transmuxResult)) {
_transmuxResult.then(function (results) {
handleFlushResult(self, results, id);
});
} else {
handleFlushResult(self, _transmuxResult, id);
}
break;
}
default:
break;
}
});
}
function emitTransmuxComplete(self, transmuxResult) {
if (isEmptyResult(transmuxResult.remuxResult)) {
return;
}
var transferable = [];
var _transmuxResult$remux = transmuxResult.remuxResult,
audio = _transmuxResult$remux.audio,
video = _transmuxResult$remux.video;
if (audio) {
addToTransferable(transferable, audio);
}
if (video) {
addToTransferable(transferable, video);
}
self.postMessage({
event: 'transmuxComplete',
data: transmuxResult
}, transferable);
} // Converts data to a transferable object https://developers.google.com/web/updates/2011/12/Transferable-Objects-Lightning-Fast)
// in order to minimize message passing overhead
function addToTransferable(transferable, track) {
if (track.data1) {
transferable.push(track.data1.buffer);
}
if (track.data2) {
transferable.push(track.data2.buffer);
}
}
function handleFlushResult(self, results, chunkMeta) {
results.forEach(function (result) {
emitTransmuxComplete(self, result);
});
self.postMessage({
event: 'flush',
data: chunkMeta
});
}
function isEmptyResult(remuxResult) {
return !remuxResult.audio && !remuxResult.video && !remuxResult.text && !remuxResult.id3 && !remuxResult.initSegment;
}
/***/ }),
/***/ "./src/demux/transmuxer.ts":
/*!*********************************!*\
!*** ./src/demux/transmuxer.ts ***!
\*********************************/
/*! exports provided: default, isPromise, TransmuxConfig, TransmuxState */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Transmuxer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isPromise", function() { return isPromise; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TransmuxConfig", function() { return TransmuxConfig; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TransmuxState", function() { return TransmuxState; });
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
/* harmony import */ var _crypt_decrypter__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../crypt/decrypter */ "./src/crypt/decrypter.ts");
/* harmony import */ var _demux_aacdemuxer__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../demux/aacdemuxer */ "./src/demux/aacdemuxer.ts");
/* harmony import */ var _demux_mp4demuxer__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../demux/mp4demuxer */ "./src/demux/mp4demuxer.ts");
/* harmony import */ var _demux_tsdemuxer__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../demux/tsdemuxer */ "./src/demux/tsdemuxer.ts");
/* harmony import */ var _demux_mp3demuxer__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../demux/mp3demuxer */ "./src/demux/mp3demuxer.ts");
/* harmony import */ var _remux_mp4_remuxer__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../remux/mp4-remuxer */ "./src/remux/mp4-remuxer.ts");
/* harmony import */ var _remux_passthrough_remuxer__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../remux/passthrough-remuxer */ "./src/remux/passthrough-remuxer.ts");
/* harmony import */ var _chunk_cache__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./chunk-cache */ "./src/demux/chunk-cache.ts");
/* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../utils/mp4-tools */ "./src/utils/mp4-tools.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
var now; // performance.now() not available on WebWorker, at least on Safari Desktop
try {
now = self.performance.now.bind(self.performance);
} catch (err) {
_utils_logger__WEBPACK_IMPORTED_MODULE_11__["logger"].debug('Unable to use Performance API on this environment');
now = self.Date.now;
}
var muxConfig = [{
demux: _demux_tsdemuxer__WEBPACK_IMPORTED_MODULE_5__["default"],
remux: _remux_mp4_remuxer__WEBPACK_IMPORTED_MODULE_7__["default"]
}, {
demux: _demux_mp4demuxer__WEBPACK_IMPORTED_MODULE_4__["default"],
remux: _remux_passthrough_remuxer__WEBPACK_IMPORTED_MODULE_8__["default"]
}, {
demux: _demux_aacdemuxer__WEBPACK_IMPORTED_MODULE_3__["default"],
remux: _remux_mp4_remuxer__WEBPACK_IMPORTED_MODULE_7__["default"]
}, {
demux: _demux_mp3demuxer__WEBPACK_IMPORTED_MODULE_6__["default"],
remux: _remux_mp4_remuxer__WEBPACK_IMPORTED_MODULE_7__["default"]
}];
var minProbeByteLength = 1024;
muxConfig.forEach(function (_ref) {
var demux = _ref.demux;
minProbeByteLength = Math.max(minProbeByteLength, demux.minProbeByteLength);
});
var Transmuxer = /*#__PURE__*/function () {
function Transmuxer(observer, typeSupported, config, vendor, id) {
this.observer = void 0;
this.typeSupported = void 0;
this.config = void 0;
this.vendor = void 0;
this.id = void 0;
this.demuxer = void 0;
this.remuxer = void 0;
this.decrypter = void 0;
this.probe = void 0;
this.decryptionPromise = null;
this.transmuxConfig = void 0;
this.currentTransmuxState = void 0;
this.cache = new _chunk_cache__WEBPACK_IMPORTED_MODULE_9__["default"]();
this.observer = observer;
this.typeSupported = typeSupported;
this.config = config;
this.vendor = vendor;
this.id = id;
}
var _proto = Transmuxer.prototype;
_proto.configure = function configure(transmuxConfig) {
this.transmuxConfig = transmuxConfig;
if (this.decrypter) {
this.decrypter.reset();
}
};
_proto.push = function push(data, decryptdata, chunkMeta, state) {
var _this = this;
var stats = chunkMeta.transmuxing;
stats.executeStart = now();
var uintData = new Uint8Array(data);
var cache = this.cache,
config = this.config,
currentTransmuxState = this.currentTransmuxState,
transmuxConfig = this.transmuxConfig;
if (state) {
this.currentTransmuxState = state;
}
var keyData = getEncryptionType(uintData, decryptdata);
if (keyData && keyData.method === 'AES-128') {
var decrypter = this.getDecrypter(); // Software decryption is synchronous; webCrypto is not
if (config.enableSoftwareAES) {
// Software decryption is progressive. Progressive decryption may not return a result on each call. Any cached
// data is handled in the flush() call
var decryptedData = decrypter.softwareDecrypt(uintData, keyData.key.buffer, keyData.iv.buffer);
if (!decryptedData) {
stats.executeEnd = now();
return emptyResult(chunkMeta);
}
uintData = new Uint8Array(decryptedData);
} else {
this.decryptionPromise = decrypter.webCryptoDecrypt(uintData, keyData.key.buffer, keyData.iv.buffer).then(function (decryptedData) {
// Calling push here is important; if flush() is called while this is still resolving, this ensures that
// the decrypted data has been transmuxed
var result = _this.push(decryptedData, null, chunkMeta);
_this.decryptionPromise = null;
return result;
});
return this.decryptionPromise;
}
}
var _ref2 = state || currentTransmuxState,
contiguous = _ref2.contiguous,
discontinuity = _ref2.discontinuity,
trackSwitch = _ref2.trackSwitch,
accurateTimeOffset = _ref2.accurateTimeOffset,
timeOffset = _ref2.timeOffset;
var audioCodec = transmuxConfig.audioCodec,
videoCodec = transmuxConfig.videoCodec,
defaultInitPts = transmuxConfig.defaultInitPts,
duration = transmuxConfig.duration,
initSegmentData = transmuxConfig.initSegmentData; // Reset muxers before probing to ensure that their state is clean, even if flushing occurs before a successful probe
if (discontinuity || trackSwitch) {
this.resetInitSegment(initSegmentData, audioCodec, videoCodec, duration);
}
if (discontinuity) {
this.resetInitialTimestamp(defaultInitPts);
}
if (!contiguous) {
this.resetContiguity();
}
if (this.needsProbing(uintData, discontinuity, trackSwitch)) {
if (cache.dataLength) {
var cachedData = cache.flush();
uintData = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_10__["appendUint8Array"])(cachedData, uintData);
}
this.configureTransmuxer(uintData, transmuxConfig);
}
var result = this.transmux(uintData, keyData, timeOffset, accurateTimeOffset, chunkMeta);
var currentState = this.currentTransmuxState;
currentState.contiguous = true;
currentState.discontinuity = false;
currentState.trackSwitch = false;
stats.executeEnd = now();
return result;
} // Due to data caching, flush calls can produce more than one TransmuxerResult (hence the Array type)
;
_proto.flush = function flush(chunkMeta) {
var _this2 = this;
var stats = chunkMeta.transmuxing;
stats.executeStart = now();
var decrypter = this.decrypter,
cache = this.cache,
currentTransmuxState = this.currentTransmuxState,
decryptionPromise = this.decryptionPromise;
if (decryptionPromise) {
// Upon resolution, the decryption promise calls push() and returns its TransmuxerResult up the stack. Therefore
// only flushing is required for async decryption
return decryptionPromise.then(function () {
return _this2.flush(chunkMeta);
});
}
var transmuxResults = [];
var timeOffset = currentTransmuxState.timeOffset;
if (decrypter) {
// The decrypter may have data cached, which needs to be demuxed. In this case we'll have two TransmuxResults
// This happens in the case that we receive only 1 push call for a segment (either for non-progressive downloads,
// or for progressive downloads with small segments)
var decryptedData = decrypter.flush();
if (decryptedData) {
// Push always returns a TransmuxerResult if decryptdata is null
transmuxResults.push(this.push(decryptedData, null, chunkMeta));
}
}
var bytesSeen = cache.dataLength;
cache.reset();
var demuxer = this.demuxer,
remuxer = this.remuxer;
if (!demuxer || !remuxer) {
// If probing failed, and each demuxer saw enough bytes to be able to probe, then Hls.js has been given content its not able to handle
if (bytesSeen >= minProbeByteLength) {
this.observer.emit(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, _events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].MEDIA_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].FRAG_PARSING_ERROR,
fatal: true,
reason: 'no demux matching with content found'
});
}
stats.executeEnd = now();
return [emptyResult(chunkMeta)];
}
var demuxResultOrPromise = demuxer.flush(timeOffset);
if (isPromise(demuxResultOrPromise)) {
// Decrypt final SAMPLE-AES samples
return demuxResultOrPromise.then(function (demuxResult) {
_this2.flushRemux(transmuxResults, demuxResult, chunkMeta);
return transmuxResults;
});
}
this.flushRemux(transmuxResults, demuxResultOrPromise, chunkMeta);
return transmuxResults;
};
_proto.flushRemux = function flushRemux(transmuxResults, demuxResult, chunkMeta) {
var audioTrack = demuxResult.audioTrack,
avcTrack = demuxResult.avcTrack,
id3Track = demuxResult.id3Track,
textTrack = demuxResult.textTrack;
var _this$currentTransmux = this.currentTransmuxState,
accurateTimeOffset = _this$currentTransmux.accurateTimeOffset,
timeOffset = _this$currentTransmux.timeOffset;
_utils_logger__WEBPACK_IMPORTED_MODULE_11__["logger"].log("[transmuxer.ts]: Flushed fragment " + chunkMeta.sn + (chunkMeta.part > -1 ? ' p: ' + chunkMeta.part : '') + " of level " + chunkMeta.level);
var remuxResult = this.remuxer.remux(audioTrack, avcTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, true, this.id);
transmuxResults.push({
remuxResult: remuxResult,
chunkMeta: chunkMeta
});
chunkMeta.transmuxing.executeEnd = now();
};
_proto.resetInitialTimestamp = function resetInitialTimestamp(defaultInitPts) {
var demuxer = this.demuxer,
remuxer = this.remuxer;
if (!demuxer || !remuxer) {
return;
}
demuxer.resetTimeStamp(defaultInitPts);
remuxer.resetTimeStamp(defaultInitPts);
};
_proto.resetContiguity = function resetContiguity() {
var demuxer = this.demuxer,
remuxer = this.remuxer;
if (!demuxer || !remuxer) {
return;
}
demuxer.resetContiguity();
remuxer.resetNextTimestamp();
};
_proto.resetInitSegment = function resetInitSegment(initSegmentData, audioCodec, videoCodec, duration) {
var demuxer = this.demuxer,
remuxer = this.remuxer;
if (!demuxer || !remuxer) {
return;
}
demuxer.resetInitSegment(audioCodec, videoCodec, duration);
remuxer.resetInitSegment(initSegmentData, audioCodec, videoCodec);
};
_proto.destroy = function destroy() {
if (this.demuxer) {
this.demuxer.destroy();
this.demuxer = undefined;
}
if (this.remuxer) {
this.remuxer.destroy();
this.remuxer = undefined;
}
};
_proto.transmux = function transmux(data, keyData, timeOffset, accurateTimeOffset, chunkMeta) {
var result;
if (keyData && keyData.method === 'SAMPLE-AES') {
result = this.transmuxSampleAes(data, keyData, timeOffset, accurateTimeOffset, chunkMeta);
} else {
result = this.transmuxUnencrypted(data, timeOffset, accurateTimeOffset, chunkMeta);
}
return result;
};
_proto.transmuxUnencrypted = function transmuxUnencrypted(data, timeOffset, accurateTimeOffset, chunkMeta) {
var _demux = this.demuxer.demux(data, timeOffset, false, !this.config.progressive),
audioTrack = _demux.audioTrack,
avcTrack = _demux.avcTrack,
id3Track = _demux.id3Track,
textTrack = _demux.textTrack;
var remuxResult = this.remuxer.remux(audioTrack, avcTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, false, this.id);
return {
remuxResult: remuxResult,
chunkMeta: chunkMeta
};
};
_proto.transmuxSampleAes = function transmuxSampleAes(data, decryptData, timeOffset, accurateTimeOffset, chunkMeta) {
var _this3 = this;
return this.demuxer.demuxSampleAes(data, decryptData, timeOffset).then(function (demuxResult) {
var remuxResult = _this3.remuxer.remux(demuxResult.audioTrack, demuxResult.avcTrack, demuxResult.id3Track, demuxResult.textTrack, timeOffset, accurateTimeOffset, false, _this3.id);
return {
remuxResult: remuxResult,
chunkMeta: chunkMeta
};
});
};
_proto.configureTransmuxer = function configureTransmuxer(data, transmuxConfig) {
var config = this.config,
observer = this.observer,
typeSupported = this.typeSupported,
vendor = this.vendor;
var audioCodec = transmuxConfig.audioCodec,
defaultInitPts = transmuxConfig.defaultInitPts,
duration = transmuxConfig.duration,
initSegmentData = transmuxConfig.initSegmentData,
videoCodec = transmuxConfig.videoCodec; // probe for content type
var mux;
for (var i = 0, len = muxConfig.length; i < len; i++) {
if (muxConfig[i].demux.probe(data)) {
mux = muxConfig[i];
break;
}
}
if (!mux) {
// If probing previous configs fail, use mp4 passthrough
_utils_logger__WEBPACK_IMPORTED_MODULE_11__["logger"].warn('Failed to find demuxer by probing frag, treating as mp4 passthrough');
mux = {
demux: _demux_mp4demuxer__WEBPACK_IMPORTED_MODULE_4__["default"],
remux: _remux_passthrough_remuxer__WEBPACK_IMPORTED_MODULE_8__["default"]
};
} // so let's check that current remuxer and demuxer are still valid
var demuxer = this.demuxer;
var remuxer = this.remuxer;
var Remuxer = mux.remux;
var Demuxer = mux.demux;
if (!remuxer || !(remuxer instanceof Remuxer)) {
this.remuxer = new Remuxer(observer, config, typeSupported, vendor);
}
if (!demuxer || !(demuxer instanceof Demuxer)) {
this.demuxer = new Demuxer(observer, config, typeSupported);
this.probe = Demuxer.probe;
} // Ensure that muxers are always initialized with an initSegment
this.resetInitSegment(initSegmentData, audioCodec, videoCodec, duration);
this.resetInitialTimestamp(defaultInitPts);
};
_proto.needsProbing = function needsProbing(data, discontinuity, trackSwitch) {
// in case of continuity change, or track switch
// we might switch from content type (AAC container to TS container, or TS to fmp4 for example)
return !this.demuxer || !this.remuxer || discontinuity || trackSwitch;
};
_proto.getDecrypter = function getDecrypter() {
var decrypter = this.decrypter;
if (!decrypter) {
decrypter = this.decrypter = new _crypt_decrypter__WEBPACK_IMPORTED_MODULE_2__["default"](this.observer, this.config);
}
return decrypter;
};
return Transmuxer;
}();
function getEncryptionType(data, decryptData) {
var encryptionType = null;
if (data.byteLength > 0 && decryptData != null && decryptData.key != null && decryptData.iv !== null && decryptData.method != null) {
encryptionType = decryptData;
}
return encryptionType;
}
var emptyResult = function emptyResult(chunkMeta) {
return {
remuxResult: {},
chunkMeta: chunkMeta
};
};
function isPromise(p) {
return 'then' in p && p.then instanceof Function;
}
var TransmuxConfig = function TransmuxConfig(audioCodec, videoCodec, initSegmentData, duration, defaultInitPts) {
this.audioCodec = void 0;
this.videoCodec = void 0;
this.initSegmentData = void 0;
this.duration = void 0;
this.defaultInitPts = void 0;
this.audioCodec = audioCodec;
this.videoCodec = videoCodec;
this.initSegmentData = initSegmentData;
this.duration = duration;
this.defaultInitPts = defaultInitPts;
};
var TransmuxState = function TransmuxState(discontinuity, contiguous, accurateTimeOffset, trackSwitch, timeOffset) {
this.discontinuity = void 0;
this.contiguous = void 0;
this.accurateTimeOffset = void 0;
this.trackSwitch = void 0;
this.timeOffset = void 0;
this.discontinuity = discontinuity;
this.contiguous = contiguous;
this.accurateTimeOffset = accurateTimeOffset;
this.trackSwitch = trackSwitch;
this.timeOffset = timeOffset;
};
/***/ }),
/***/ "./src/demux/tsdemuxer.ts":
/*!********************************!*\
!*** ./src/demux/tsdemuxer.ts ***!
\********************************/
/*! exports provided: discardEPB, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "discardEPB", function() { return discardEPB; });
/* harmony import */ var _adts__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./adts */ "./src/demux/adts.ts");
/* harmony import */ var _mpegaudio__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./mpegaudio */ "./src/demux/mpegaudio.ts");
/* harmony import */ var _exp_golomb__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./exp-golomb */ "./src/demux/exp-golomb.ts");
/* harmony import */ var _id3__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./id3 */ "./src/demux/id3.ts");
/* harmony import */ var _sample_aes__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./sample-aes */ "./src/demux/sample-aes.ts");
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../utils/mp4-tools */ "./src/utils/mp4-tools.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
/**
* highly optimized TS demuxer:
* parse PAT, PMT
* extract PES packet from audio and video PIDs
* extract AVC/H264 NAL units and AAC/ADTS samples from PES packet
* trigger the remuxer upon parsing completion
* it also tries to workaround as best as it can audio codec switch (HE-AAC to AAC and vice versa), without having to restart the MediaSource.
* it also controls the remuxing process :
* upon discontinuity or level switch detection, it will also notifies the remuxer so that it can reset its state.
*/
// We are using fixed track IDs for driving the MP4 remuxer
// instead of following the TS PIDs.
// There is no reason not to do this and some browsers/SourceBuffer-demuxers
// may not like if there are TrackID "switches"
// See https://github.com/video-dev/hls.js/issues/1331
// Here we are mapping our internal track types to constant MP4 track IDs
// With MSE currently one can only have one track of each, and we are muxing
// whatever video/audio rendition in them.
var RemuxerTrackIdConfig = {
video: 1,
audio: 2,
id3: 3,
text: 4
};
var TSDemuxer = /*#__PURE__*/function () {
function TSDemuxer(observer, config, typeSupported) {
this.observer = void 0;
this.config = void 0;
this.typeSupported = void 0;
this.sampleAes = null;
this.pmtParsed = false;
this.audioCodec = void 0;
this.videoCodec = void 0;
this._duration = 0;
this.aacLastPTS = null;
this._initPTS = null;
this._initDTS = null;
this._pmtId = -1;
this._avcTrack = void 0;
this._audioTrack = void 0;
this._id3Track = void 0;
this._txtTrack = void 0;
this.aacOverFlow = null;
this.avcSample = null;
this.remainderData = null;
this.observer = observer;
this.config = config;
this.typeSupported = typeSupported;
}
TSDemuxer.probe = function probe(data) {
var syncOffset = TSDemuxer.syncOffset(data);
if (syncOffset < 0) {
return false;
} else {
if (syncOffset) {
_utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].warn("MPEG2-TS detected but first sync word found @ offset " + syncOffset + ", junk ahead ?");
}
return true;
}
};
TSDemuxer.syncOffset = function syncOffset(data) {
// scan 1000 first bytes
var scanwindow = Math.min(1000, data.length - 3 * 188);
var i = 0;
while (i < scanwindow) {
// a TS fragment should contain at least 3 TS packets, a PAT, a PMT, and one PID, each starting with 0x47
if (data[i] === 0x47 && data[i + 188] === 0x47 && data[i + 2 * 188] === 0x47) {
return i;
} else {
i++;
}
}
return -1;
}
/**
* Creates a track model internal to demuxer used to drive remuxing input
*
* @param type 'audio' | 'video' | 'id3' | 'text'
* @param duration
* @return TSDemuxer's internal track model
*/
;
TSDemuxer.createTrack = function createTrack(type, duration) {
return {
container: type === 'video' || type === 'audio' ? 'video/mp2t' : undefined,
type: type,
id: RemuxerTrackIdConfig[type],
pid: -1,
inputTimeScale: 90000,
sequenceNumber: 0,
samples: [],
dropped: 0,
duration: type === 'audio' ? duration : undefined
};
}
/**
* Initializes a new init segment on the demuxer/remuxer interface. Needed for discontinuities/track-switches (or at stream start)
* Resets all internal track instances of the demuxer.
*/
;
var _proto = TSDemuxer.prototype;
_proto.resetInitSegment = function resetInitSegment(audioCodec, videoCodec, duration) {
this.pmtParsed = false;
this._pmtId = -1;
this._avcTrack = TSDemuxer.createTrack('video', duration);
this._audioTrack = TSDemuxer.createTrack('audio', duration);
this._id3Track = TSDemuxer.createTrack('id3', duration);
this._txtTrack = TSDemuxer.createTrack('text', duration);
this._audioTrack.isAAC = true; // flush any partial content
this.aacOverFlow = null;
this.aacLastPTS = null;
this.avcSample = null;
this.audioCodec = audioCodec;
this.videoCodec = videoCodec;
this._duration = duration;
};
_proto.resetTimeStamp = function resetTimeStamp() {};
_proto.resetContiguity = function resetContiguity() {
var _audioTrack = this._audioTrack,
_avcTrack = this._avcTrack,
_id3Track = this._id3Track;
if (_audioTrack) {
_audioTrack.pesData = null;
}
if (_avcTrack) {
_avcTrack.pesData = null;
}
if (_id3Track) {
_id3Track.pesData = null;
}
this.aacOverFlow = null;
this.aacLastPTS = null;
};
_proto.demux = function demux(data, timeOffset, isSampleAes, flush) {
if (isSampleAes === void 0) {
isSampleAes = false;
}
if (flush === void 0) {
flush = false;
}
if (!isSampleAes) {
this.sampleAes = null;
}
var pes;
var avcTrack = this._avcTrack;
var audioTrack = this._audioTrack;
var id3Track = this._id3Track;
var avcId = avcTrack.pid;
var avcData = avcTrack.pesData;
var audioId = audioTrack.pid;
var id3Id = id3Track.pid;
var audioData = audioTrack.pesData;
var id3Data = id3Track.pesData;
var unknownPIDs = false;
var pmtParsed = this.pmtParsed;
var pmtId = this._pmtId;
var len = data.length;
if (this.remainderData) {
data = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_6__["appendUint8Array"])(this.remainderData, data);
len = data.length;
this.remainderData = null;
}
if (len < 188 && !flush) {
this.remainderData = data;
return {
audioTrack: audioTrack,
avcTrack: avcTrack,
id3Track: id3Track,
textTrack: this._txtTrack
};
}
var syncOffset = Math.max(0, TSDemuxer.syncOffset(data));
len -= (len + syncOffset) % 188;
if (len < data.byteLength && !flush) {
this.remainderData = new Uint8Array(data.buffer, len, data.buffer.byteLength - len);
} // loop through TS packets
for (var start = syncOffset; start < len; start += 188) {
if (data[start] === 0x47) {
var stt = !!(data[start + 1] & 0x40); // pid is a 13-bit field starting at the last bit of TS[1]
var pid = ((data[start + 1] & 0x1f) << 8) + data[start + 2];
var atf = (data[start + 3] & 0x30) >> 4; // if an adaption field is present, its length is specified by the fifth byte of the TS packet header.
var offset = void 0;
if (atf > 1) {
offset = start + 5 + data[start + 4]; // continue if there is only adaptation field
if (offset === start + 188) {
continue;
}
} else {
offset = start + 4;
}
switch (pid) {
case avcId:
if (stt) {
if (avcData && (pes = parsePES(avcData))) {
this.parseAVCPES(pes, false);
}
avcData = {
data: [],
size: 0
};
}
if (avcData) {
avcData.data.push(data.subarray(offset, start + 188));
avcData.size += start + 188 - offset;
}
break;
case audioId:
if (stt) {
if (audioData && (pes = parsePES(audioData))) {
if (audioTrack.isAAC) {
this.parseAACPES(pes);
} else {
this.parseMPEGPES(pes);
}
}
audioData = {
data: [],
size: 0
};
}
if (audioData) {
audioData.data.push(data.subarray(offset, start + 188));
audioData.size += start + 188 - offset;
}
break;
case id3Id:
if (stt) {
if (id3Data && (pes = parsePES(id3Data))) {
this.parseID3PES(pes);
}
id3Data = {
data: [],
size: 0
};
}
if (id3Data) {
id3Data.data.push(data.subarray(offset, start + 188));
id3Data.size += start + 188 - offset;
}
break;
case 0:
if (stt) {
offset += data[offset] + 1;
}
pmtId = this._pmtId = parsePAT(data, offset);
break;
case pmtId:
{
if (stt) {
offset += data[offset] + 1;
}
var parsedPIDs = parsePMT(data, offset, this.typeSupported.mpeg === true || this.typeSupported.mp3 === true, isSampleAes); // only update track id if track PID found while parsing PMT
// this is to avoid resetting the PID to -1 in case
// track PID transiently disappears from the stream
// this could happen in case of transient missing audio samples for example
// NOTE this is only the PID of the track as found in TS,
// but we are not using this for MP4 track IDs.
avcId = parsedPIDs.avc;
if (avcId > 0) {
avcTrack.pid = avcId;
}
audioId = parsedPIDs.audio;
if (audioId > 0) {
audioTrack.pid = audioId;
audioTrack.isAAC = parsedPIDs.isAAC;
}
id3Id = parsedPIDs.id3;
if (id3Id > 0) {
id3Track.pid = id3Id;
}
if (unknownPIDs && !pmtParsed) {
_utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].log('reparse from beginning');
unknownPIDs = false; // we set it to -188, the += 188 in the for loop will reset start to 0
start = syncOffset - 188;
}
pmtParsed = this.pmtParsed = true;
break;
}
case 17:
case 0x1fff:
break;
default:
unknownPIDs = true;
break;
}
} else {
this.observer.emit(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].ERROR, _events__WEBPACK_IMPORTED_MODULE_5__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_8__["ErrorTypes"].MEDIA_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_8__["ErrorDetails"].FRAG_PARSING_ERROR,
fatal: false,
reason: 'TS packet did not start with 0x47'
});
}
}
avcTrack.pesData = avcData;
audioTrack.pesData = audioData;
id3Track.pesData = id3Data;
var demuxResult = {
audioTrack: audioTrack,
avcTrack: avcTrack,
id3Track: id3Track,
textTrack: this._txtTrack
};
if (flush) {
this.extractRemainingSamples(demuxResult);
}
return demuxResult;
};
_proto.flush = function flush() {
var remainderData = this.remainderData;
this.remainderData = null;
var result;
if (remainderData) {
result = this.demux(remainderData, -1, false, true);
} else {
result = {
audioTrack: this._audioTrack,
avcTrack: this._avcTrack,
textTrack: this._txtTrack,
id3Track: this._id3Track
};
}
this.extractRemainingSamples(result);
if (this.sampleAes) {
return this.decrypt(result, this.sampleAes);
}
return result;
};
_proto.extractRemainingSamples = function extractRemainingSamples(demuxResult) {
var audioTrack = demuxResult.audioTrack,
avcTrack = demuxResult.avcTrack,
id3Track = demuxResult.id3Track;
var avcData = avcTrack.pesData;
var audioData = audioTrack.pesData;
var id3Data = id3Track.pesData; // try to parse last PES packets
var pes;
if (avcData && (pes = parsePES(avcData))) {
this.parseAVCPES(pes, true);
avcTrack.pesData = null;
} else {
// either avcData null or PES truncated, keep it for next frag parsing
avcTrack.pesData = avcData;
}
if (audioData && (pes = parsePES(audioData))) {
if (audioTrack.isAAC) {
this.parseAACPES(pes);
} else {
this.parseMPEGPES(pes);
}
audioTrack.pesData = null;
} else {
if (audioData !== null && audioData !== void 0 && audioData.size) {
_utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].log('last AAC PES packet truncated,might overlap between fragments');
} // either audioData null or PES truncated, keep it for next frag parsing
audioTrack.pesData = audioData;
}
if (id3Data && (pes = parsePES(id3Data))) {
this.parseID3PES(pes);
id3Track.pesData = null;
} else {
// either id3Data null or PES truncated, keep it for next frag parsing
id3Track.pesData = id3Data;
}
};
_proto.demuxSampleAes = function demuxSampleAes(data, keyData, timeOffset) {
var demuxResult = this.demux(data, timeOffset, true, !this.config.progressive);
var sampleAes = this.sampleAes = new _sample_aes__WEBPACK_IMPORTED_MODULE_4__["default"](this.observer, this.config, keyData);
return this.decrypt(demuxResult, sampleAes);
};
_proto.decrypt = function decrypt(demuxResult, sampleAes) {
return new Promise(function (resolve) {
var audioTrack = demuxResult.audioTrack,
avcTrack = demuxResult.avcTrack;
if (audioTrack.samples && audioTrack.isAAC) {
sampleAes.decryptAacSamples(audioTrack.samples, 0, function () {
if (avcTrack.samples) {
sampleAes.decryptAvcSamples(avcTrack.samples, 0, 0, function () {
resolve(demuxResult);
});
} else {
resolve(demuxResult);
}
});
} else if (avcTrack.samples) {
sampleAes.decryptAvcSamples(avcTrack.samples, 0, 0, function () {
resolve(demuxResult);
});
}
});
};
_proto.destroy = function destroy() {
this._initPTS = this._initDTS = null;
this._duration = 0;
};
_proto.parseAVCPES = function parseAVCPES(pes, last) {
var _this = this;
var track = this._avcTrack;
var units = this.parseAVCNALu(pes.data);
var debug = false;
var avcSample = this.avcSample;
var push;
var spsfound = false; // free pes.data to save up some memory
pes.data = null; // if new NAL units found and last sample still there, let's push ...
// this helps parsing streams with missing AUD (only do this if AUD never found)
if (avcSample && units.length && !track.audFound) {
pushAccessUnit(avcSample, track);
avcSample = this.avcSample = createAVCSample(false, pes.pts, pes.dts, '');
}
units.forEach(function (unit) {
switch (unit.type) {
// NDR
case 1:
{
push = true;
if (!avcSample) {
avcSample = _this.avcSample = createAVCSample(true, pes.pts, pes.dts, '');
}
if (debug) {
avcSample.debug += 'NDR ';
}
avcSample.frame = true;
var data = unit.data; // only check slice type to detect KF in case SPS found in same packet (any keyframe is preceded by SPS ...)
if (spsfound && data.length > 4) {
// retrieve slice type by parsing beginning of NAL unit (follow H264 spec, slice_header definition) to detect keyframe embedded in NDR
var sliceType = new _exp_golomb__WEBPACK_IMPORTED_MODULE_2__["default"](data).readSliceType(); // 2 : I slice, 4 : SI slice, 7 : I slice, 9: SI slice
// SI slice : A slice that is coded using intra prediction only and using quantisation of the prediction samples.
// An SI slice can be coded such that its decoded samples can be constructed identically to an SP slice.
// I slice: A slice that is not an SI slice that is decoded using intra prediction only.
// if (sliceType === 2 || sliceType === 7) {
if (sliceType === 2 || sliceType === 4 || sliceType === 7 || sliceType === 9) {
avcSample.key = true;
}
}
break; // IDR
}
case 5:
push = true; // handle PES not starting with AUD
if (!avcSample) {
avcSample = _this.avcSample = createAVCSample(true, pes.pts, pes.dts, '');
}
if (debug) {
avcSample.debug += 'IDR ';
}
avcSample.key = true;
avcSample.frame = true;
break;
// SEI
case 6:
{
push = true;
if (debug && avcSample) {
avcSample.debug += 'SEI ';
}
var expGolombDecoder = new _exp_golomb__WEBPACK_IMPORTED_MODULE_2__["default"](discardEPB(unit.data)); // skip frameType
expGolombDecoder.readUByte();
var payloadType = 0;
var payloadSize = 0;
var endOfCaptions = false;
var b = 0;
while (!endOfCaptions && expGolombDecoder.bytesAvailable > 1) {
payloadType = 0;
do {
b = expGolombDecoder.readUByte();
payloadType += b;
} while (b === 0xff); // Parse payload size.
payloadSize = 0;
do {
b = expGolombDecoder.readUByte();
payloadSize += b;
} while (b === 0xff); // TODO: there can be more than one payload in an SEI packet...
// TODO: need to read type and size in a while loop to get them all
if (payloadType === 4 && expGolombDecoder.bytesAvailable !== 0) {
endOfCaptions = true;
var countryCode = expGolombDecoder.readUByte();
if (countryCode === 181) {
var providerCode = expGolombDecoder.readUShort();
if (providerCode === 49) {
var userStructure = expGolombDecoder.readUInt();
if (userStructure === 0x47413934) {
var userDataType = expGolombDecoder.readUByte(); // Raw CEA-608 bytes wrapped in CEA-708 packet
if (userDataType === 3) {
var firstByte = expGolombDecoder.readUByte();
var secondByte = expGolombDecoder.readUByte();
var totalCCs = 31 & firstByte;
var byteArray = [firstByte, secondByte];
for (var i = 0; i < totalCCs; i++) {
// 3 bytes per CC
byteArray.push(expGolombDecoder.readUByte());
byteArray.push(expGolombDecoder.readUByte());
byteArray.push(expGolombDecoder.readUByte());
}
insertSampleInOrder(_this._txtTrack.samples, {
type: 3,
pts: pes.pts,
bytes: byteArray
});
}
}
}
}
} else if (payloadType === 5 && expGolombDecoder.bytesAvailable !== 0) {
endOfCaptions = true;
if (payloadSize > 16) {
var uuidStrArray = [];
for (var _i = 0; _i < 16; _i++) {
uuidStrArray.push(expGolombDecoder.readUByte().toString(16));
if (_i === 3 || _i === 5 || _i === 7 || _i === 9) {
uuidStrArray.push('-');
}
}
var length = payloadSize - 16;
var userDataPayloadBytes = new Uint8Array(length);
for (var _i2 = 0; _i2 < length; _i2++) {
userDataPayloadBytes[_i2] = expGolombDecoder.readUByte();
}
insertSampleInOrder(_this._txtTrack.samples, {
pts: pes.pts,
payloadType: payloadType,
uuid: uuidStrArray.join(''),
userData: Object(_id3__WEBPACK_IMPORTED_MODULE_3__["utf8ArrayToStr"])(userDataPayloadBytes),
userDataBytes: userDataPayloadBytes
});
}
} else if (payloadSize < expGolombDecoder.bytesAvailable) {
for (var _i3 = 0; _i3 < payloadSize; _i3++) {
expGolombDecoder.readUByte();
}
}
}
break; // SPS
}
case 7:
push = true;
spsfound = true;
if (debug && avcSample) {
avcSample.debug += 'SPS ';
}
if (!track.sps) {
var _expGolombDecoder = new _exp_golomb__WEBPACK_IMPORTED_MODULE_2__["default"](unit.data);
var config = _expGolombDecoder.readSPS();
track.width = config.width;
track.height = config.height;
track.pixelRatio = config.pixelRatio; // TODO: `track.sps` is defined as a `number[]`, but we're setting it to a `Uint8Array[]`.
track.sps = [unit.data];
track.duration = _this._duration;
var codecarray = unit.data.subarray(1, 4);
var codecstring = 'avc1.';
for (var _i4 = 0; _i4 < 3; _i4++) {
var h = codecarray[_i4].toString(16);
if (h.length < 2) {
h = '0' + h;
}
codecstring += h;
}
track.codec = codecstring;
}
break;
// PPS
case 8:
push = true;
if (debug && avcSample) {
avcSample.debug += 'PPS ';
}
if (!track.pps) {
// TODO: `track.pss` is defined as a `number[]`, but we're setting it to a `Uint8Array[]`.
track.pps = [unit.data];
}
break;
// AUD
case 9:
push = false;
track.audFound = true;
if (avcSample) {
pushAccessUnit(avcSample, track);
}
avcSample = _this.avcSample = createAVCSample(false, pes.pts, pes.dts, debug ? 'AUD ' : '');
break;
// Filler Data
case 12:
push = false;
break;
default:
push = false;
if (avcSample) {
avcSample.debug += 'unknown NAL ' + unit.type + ' ';
}
break;
}
if (avcSample && push) {
var _units = avcSample.units;
_units.push(unit);
}
}); // if last PES packet, push samples
if (last && avcSample) {
pushAccessUnit(avcSample, track);
this.avcSample = null;
}
};
_proto.getLastNalUnit = function getLastNalUnit() {
var _avcSample;
var avcSample = this.avcSample;
var lastUnit; // try to fallback to previous sample if current one is empty
if (!avcSample || avcSample.units.length === 0) {
var samples = this._avcTrack.samples;
avcSample = samples[samples.length - 1];
}
if ((_avcSample = avcSample) !== null && _avcSample !== void 0 && _avcSample.units) {
var units = avcSample.units;
lastUnit = units[units.length - 1];
}
return lastUnit;
};
_proto.parseAVCNALu = function parseAVCNALu(array) {
var len = array.byteLength;
var track = this._avcTrack;
var state = track.naluState || 0;
var lastState = state;
var units = [];
var i = 0;
var value;
var overflow;
var unitType;
var lastUnitStart = -1;
var lastUnitType = 0; // logger.log('PES:' + Hex.hexDump(array));
if (state === -1) {
// special use case where we found 3 or 4-byte start codes exactly at the end of previous PES packet
lastUnitStart = 0; // NALu type is value read from offset 0
lastUnitType = array[0] & 0x1f;
state = 0;
i = 1;
}
while (i < len) {
value = array[i++]; // optimization. state 0 and 1 are the predominant case. let's handle them outside of the switch/case
if (!state) {
state = value ? 0 : 1;
continue;
}
if (state === 1) {
state = value ? 0 : 2;
continue;
} // here we have state either equal to 2 or 3
if (!value) {
state = 3;
} else if (value === 1) {
if (lastUnitStart >= 0) {
var unit = {
data: array.subarray(lastUnitStart, i - state - 1),
type: lastUnitType
}; // logger.log('pushing NALU, type/size:' + unit.type + '/' + unit.data.byteLength);
units.push(unit);
} else {
// lastUnitStart is undefined => this is the first start code found in this PES packet
// first check if start code delimiter is overlapping between 2 PES packets,
// ie it started in last packet (lastState not zero)
// and ended at the beginning of this PES packet (i <= 4 - lastState)
var lastUnit = this.getLastNalUnit();
if (lastUnit) {
if (lastState && i <= 4 - lastState) {
// start delimiter overlapping between PES packets
// strip start delimiter bytes from the end of last NAL unit
// check if lastUnit had a state different from zero
if (lastUnit.state) {
// strip last bytes
lastUnit.data = lastUnit.data.subarray(0, lastUnit.data.byteLength - lastState);
}
} // If NAL units are not starting right at the beginning of the PES packet, push preceding data into previous NAL unit.
overflow = i - state - 1;
if (overflow > 0) {
// logger.log('first NALU found with overflow:' + overflow);
var tmp = new Uint8Array(lastUnit.data.byteLength + overflow);
tmp.set(lastUnit.data, 0);
tmp.set(array.subarray(0, overflow), lastUnit.data.byteLength);
lastUnit.data = tmp;
}
}
} // check if we can read unit type
if (i < len) {
unitType = array[i] & 0x1f; // logger.log('find NALU @ offset:' + i + ',type:' + unitType);
lastUnitStart = i;
lastUnitType = unitType;
state = 0;
} else {
// not enough byte to read unit type. let's read it on next PES parsing
state = -1;
}
} else {
state = 0;
}
}
if (lastUnitStart >= 0 && state >= 0) {
var _unit = {
data: array.subarray(lastUnitStart, len),
type: lastUnitType,
state: state
};
units.push(_unit); // logger.log('pushing NALU, type/size/state:' + unit.type + '/' + unit.data.byteLength + '/' + state);
} // no NALu found
if (units.length === 0) {
// append pes.data to previous NAL unit
var _lastUnit = this.getLastNalUnit();
if (_lastUnit) {
var _tmp = new Uint8Array(_lastUnit.data.byteLength + array.byteLength);
_tmp.set(_lastUnit.data, 0);
_tmp.set(array, _lastUnit.data.byteLength);
_lastUnit.data = _tmp;
}
}
track.naluState = state;
return units;
};
_proto.parseAACPES = function parseAACPES(pes) {
var startOffset = 0;
var track = this._audioTrack;
var aacOverFlow = this.aacOverFlow;
var data = pes.data;
if (aacOverFlow) {
this.aacOverFlow = null;
var sampleLength = aacOverFlow.sample.unit.byteLength;
var frameMissingBytes = Math.min(aacOverFlow.missing, sampleLength);
var frameOverflowBytes = sampleLength - frameMissingBytes;
aacOverFlow.sample.unit.set(data.subarray(0, frameMissingBytes), frameOverflowBytes);
track.samples.push(aacOverFlow.sample); // logger.log(`AAC: append overflowing ${frameOverflowBytes} bytes to beginning of new PES`);
startOffset = aacOverFlow.missing;
} // look for ADTS header (0xFFFx)
var offset;
var len;
for (offset = startOffset, len = data.length; offset < len - 1; offset++) {
if (_adts__WEBPACK_IMPORTED_MODULE_0__["isHeader"](data, offset)) {
break;
}
} // if ADTS header does not start straight from the beginning of the PES payload, raise an error
if (offset !== startOffset) {
var reason;
var fatal;
if (offset < len - 1) {
reason = "AAC PES did not start with ADTS header,offset:" + offset;
fatal = false;
} else {
reason = 'no ADTS header found in AAC PES';
fatal = true;
}
_utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].warn("parsing error:" + reason);
this.observer.emit(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].ERROR, _events__WEBPACK_IMPORTED_MODULE_5__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_8__["ErrorTypes"].MEDIA_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_8__["ErrorDetails"].FRAG_PARSING_ERROR,
fatal: fatal,
reason: reason
});
if (fatal) {
return;
}
}
_adts__WEBPACK_IMPORTED_MODULE_0__["initTrackConfig"](track, this.observer, data, offset, this.audioCodec);
var pts;
if (pes.pts !== undefined) {
pts = pes.pts;
} else if (aacOverFlow) {
// if last AAC frame is overflowing, we should ensure timestamps are contiguous:
// first sample PTS should be equal to last sample PTS + frameDuration
var frameDuration = _adts__WEBPACK_IMPORTED_MODULE_0__["getFrameDuration"](track.samplerate);
pts = aacOverFlow.sample.pts + frameDuration;
} else {
_utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].warn('[tsdemuxer]: AAC PES unknown PTS');
return;
} // scan for aac samples
var frameIndex = 0;
while (offset < len) {
if (_adts__WEBPACK_IMPORTED_MODULE_0__["isHeader"](data, offset)) {
if (offset + 5 < len) {
var frame = _adts__WEBPACK_IMPORTED_MODULE_0__["appendFrame"](track, data, offset, pts, frameIndex);
if (frame) {
if (frame.missing) {
this.aacOverFlow = frame;
} else {
offset += frame.length;
frameIndex++;
continue;
}
}
} // We are at an ADTS header, but do not have enough data for a frame
// Remaining data will be added to aacOverFlow
break;
} else {
// nothing found, keep looking
offset++;
}
}
};
_proto.parseMPEGPES = function parseMPEGPES(pes) {
var data = pes.data;
var length = data.length;
var frameIndex = 0;
var offset = 0;
var pts = pes.pts;
if (pts === undefined) {
_utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].warn('[tsdemuxer]: MPEG PES unknown PTS');
return;
}
while (offset < length) {
if (_mpegaudio__WEBPACK_IMPORTED_MODULE_1__["isHeader"](data, offset)) {
var frame = _mpegaudio__WEBPACK_IMPORTED_MODULE_1__["appendFrame"](this._audioTrack, data, offset, pts, frameIndex);
if (frame) {
offset += frame.length;
frameIndex++;
} else {
// logger.log('Unable to parse Mpeg audio frame');
break;
}
} else {
// nothing found, keep looking
offset++;
}
}
};
_proto.parseID3PES = function parseID3PES(pes) {
if (pes.pts === undefined) {
_utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].warn('[tsdemuxer]: ID3 PES unknown PTS');
return;
}
this._id3Track.samples.push(pes);
};
return TSDemuxer;
}();
TSDemuxer.minProbeByteLength = 188;
function createAVCSample(key, pts, dts, debug) {
return {
key: key,
frame: false,
pts: pts,
dts: dts,
units: [],
debug: debug,
length: 0
};
}
function parsePAT(data, offset) {
// skip the PSI header and parse the first PMT entry
return (data[offset + 10] & 0x1f) << 8 | data[offset + 11]; // logger.log('PMT PID:' + this._pmtId);
}
function parsePMT(data, offset, mpegSupported, isSampleAes) {
var result = {
audio: -1,
avc: -1,
id3: -1,
isAAC: true
};
var sectionLength = (data[offset + 1] & 0x0f) << 8 | data[offset + 2];
var tableEnd = offset + 3 + sectionLength - 4; // to determine where the table is, we have to figure out how
// long the program info descriptors are
var programInfoLength = (data[offset + 10] & 0x0f) << 8 | data[offset + 11]; // advance the offset to the first entry in the mapping table
offset += 12 + programInfoLength;
while (offset < tableEnd) {
var pid = (data[offset + 1] & 0x1f) << 8 | data[offset + 2];
switch (data[offset]) {
case 0xcf:
// SAMPLE-AES AAC
if (!isSampleAes) {
_utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].log('ADTS AAC with AES-128-CBC frame encryption found in unencrypted stream');
break;
}
/* falls through */
case 0x0f:
// ISO/IEC 13818-7 ADTS AAC (MPEG-2 lower bit-rate audio)
// logger.log('AAC PID:' + pid);
if (result.audio === -1) {
result.audio = pid;
}
break;
// Packetized metadata (ID3)
case 0x15:
// logger.log('ID3 PID:' + pid);
if (result.id3 === -1) {
result.id3 = pid;
}
break;
case 0xdb:
// SAMPLE-AES AVC
if (!isSampleAes) {
_utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].log('H.264 with AES-128-CBC slice encryption found in unencrypted stream');
break;
}
/* falls through */
case 0x1b:
// ITU-T Rec. H.264 and ISO/IEC 14496-10 (lower bit-rate video)
// logger.log('AVC PID:' + pid);
if (result.avc === -1) {
result.avc = pid;
}
break;
// ISO/IEC 11172-3 (MPEG-1 audio)
// or ISO/IEC 13818-3 (MPEG-2 halved sample rate audio)
case 0x03:
case 0x04:
// logger.log('MPEG PID:' + pid);
if (!mpegSupported) {
_utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].log('MPEG audio found, not supported in this browser');
} else if (result.audio === -1) {
result.audio = pid;
result.isAAC = false;
}
break;
case 0x24:
_utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].warn('Unsupported HEVC stream type found');
break;
default:
// logger.log('unknown stream type:' + data[offset]);
break;
} // move to the next table entry
// skip past the elementary stream descriptors, if present
offset += ((data[offset + 3] & 0x0f) << 8 | data[offset + 4]) + 5;
}
return result;
}
function parsePES(stream) {
var i = 0;
var frag;
var pesLen;
var pesHdrLen;
var pesPts;
var pesDts;
var data = stream.data; // safety check
if (!stream || stream.size === 0) {
return null;
} // we might need up to 19 bytes to read PES header
// if first chunk of data is less than 19 bytes, let's merge it with following ones until we get 19 bytes
// usually only one merge is needed (and this is rare ...)
while (data[0].length < 19 && data.length > 1) {
var newData = new Uint8Array(data[0].length + data[1].length);
newData.set(data[0]);
newData.set(data[1], data[0].length);
data[0] = newData;
data.splice(1, 1);
} // retrieve PTS/DTS from first fragment
frag = data[0];
var pesPrefix = (frag[0] << 16) + (frag[1] << 8) + frag[2];
if (pesPrefix === 1) {
pesLen = (frag[4] << 8) + frag[5]; // if PES parsed length is not zero and greater than total received length, stop parsing. PES might be truncated
// minus 6 : PES header size
if (pesLen && pesLen > stream.size - 6) {
return null;
}
var pesFlags = frag[7];
if (pesFlags & 0xc0) {
/* PES header described here : http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
as PTS / DTS is 33 bit we cannot use bitwise operator in JS,
as Bitwise operators treat their operands as a sequence of 32 bits */
pesPts = (frag[9] & 0x0e) * 536870912 + // 1 << 29
(frag[10] & 0xff) * 4194304 + // 1 << 22
(frag[11] & 0xfe) * 16384 + // 1 << 14
(frag[12] & 0xff) * 128 + // 1 << 7
(frag[13] & 0xfe) / 2;
if (pesFlags & 0x40) {
pesDts = (frag[14] & 0x0e) * 536870912 + // 1 << 29
(frag[15] & 0xff) * 4194304 + // 1 << 22
(frag[16] & 0xfe) * 16384 + // 1 << 14
(frag[17] & 0xff) * 128 + // 1 << 7
(frag[18] & 0xfe) / 2;
if (pesPts - pesDts > 60 * 90000) {
_utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].warn(Math.round((pesPts - pesDts) / 90000) + "s delta between PTS and DTS, align them");
pesPts = pesDts;
}
} else {
pesDts = pesPts;
}
}
pesHdrLen = frag[8]; // 9 bytes : 6 bytes for PES header + 3 bytes for PES extension
var payloadStartOffset = pesHdrLen + 9;
if (stream.size <= payloadStartOffset) {
return null;
}
stream.size -= payloadStartOffset; // reassemble PES packet
var pesData = new Uint8Array(stream.size);
for (var j = 0, dataLen = data.length; j < dataLen; j++) {
frag = data[j];
var len = frag.byteLength;
if (payloadStartOffset) {
if (payloadStartOffset > len) {
// trim full frag if PES header bigger than frag
payloadStartOffset -= len;
continue;
} else {
// trim partial frag if PES header smaller than frag
frag = frag.subarray(payloadStartOffset);
len -= payloadStartOffset;
payloadStartOffset = 0;
}
}
pesData.set(frag, i);
i += len;
}
if (pesLen) {
// payload size : remove PES header + PES extension
pesLen -= pesHdrLen + 3;
}
return {
data: pesData,
pts: pesPts,
dts: pesDts,
len: pesLen
};
}
return null;
}
function pushAccessUnit(avcSample, avcTrack) {
if (avcSample.units.length && avcSample.frame) {
// if sample does not have PTS/DTS, patch with last sample PTS/DTS
if (avcSample.pts === undefined) {
var samples = avcTrack.samples;
var nbSamples = samples.length;
if (nbSamples) {
var lastSample = samples[nbSamples - 1];
avcSample.pts = lastSample.pts;
avcSample.dts = lastSample.dts;
} else {
// dropping samples, no timestamp found
avcTrack.dropped++;
return;
}
}
avcTrack.samples.push(avcSample);
}
if (avcSample.debug.length) {
_utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].log(avcSample.pts + '/' + avcSample.dts + ':' + avcSample.debug);
}
}
function insertSampleInOrder(arr, data) {
var len = arr.length;
if (len > 0) {
if (data.pts >= arr[len - 1].pts) {
arr.push(data);
} else {
for (var pos = len - 1; pos >= 0; pos--) {
if (data.pts < arr[pos].pts) {
arr.splice(pos, 0, data);
break;
}
}
}
} else {
arr.push(data);
}
}
/**
* remove Emulation Prevention bytes from a RBSP
*/
function discardEPB(data) {
var length = data.byteLength;
var EPBPositions = [];
var i = 1; // Find all `Emulation Prevention Bytes`
while (i < length - 2) {
if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
EPBPositions.push(i + 2);
i += 2;
} else {
i++;
}
} // If no Emulation Prevention Bytes were found just return the original
// array
if (EPBPositions.length === 0) {
return data;
} // Create a new array to hold the NAL unit data
var newLength = length - EPBPositions.length;
var newData = new Uint8Array(newLength);
var sourceIndex = 0;
for (i = 0; i < newLength; sourceIndex++, i++) {
if (sourceIndex === EPBPositions[0]) {
// Skip this byte
sourceIndex++; // Remove this position index
EPBPositions.shift();
}
newData[i] = data[sourceIndex];
}
return newData;
}
/* harmony default export */ __webpack_exports__["default"] = (TSDemuxer);
/***/ }),
/***/ "./src/empty.js":
/*!**********************!*\
!*** ./src/empty.js ***!
\**********************/
/*! no static exports found */
/***/ (function(module, exports) {
// This file is inserted as a shim for modules which we do not want to include into the distro.
// This replacement is done in the "resolve" section of the webpack config.
module.exports = undefined;
/***/ }),
/***/ "./src/errors.ts":
/*!***********************!*\
!*** ./src/errors.ts ***!
\***********************/
/*! exports provided: ErrorTypes, ErrorDetails */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ErrorTypes", function() { return ErrorTypes; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ErrorDetails", function() { return ErrorDetails; });
var ErrorTypes;
/**
* @enum {ErrorDetails}
* @typedef {string} ErrorDetail
*/
(function (ErrorTypes) {
ErrorTypes["NETWORK_ERROR"] = "networkError";
ErrorTypes["MEDIA_ERROR"] = "mediaError";
ErrorTypes["KEY_SYSTEM_ERROR"] = "keySystemError";
ErrorTypes["MUX_ERROR"] = "muxError";
ErrorTypes["OTHER_ERROR"] = "otherError";
})(ErrorTypes || (ErrorTypes = {}));
var ErrorDetails;
(function (ErrorDetails) {
ErrorDetails["KEY_SYSTEM_NO_KEYS"] = "keySystemNoKeys";
ErrorDetails["KEY_SYSTEM_NO_ACCESS"] = "keySystemNoAccess";
ErrorDetails["KEY_SYSTEM_NO_SESSION"] = "keySystemNoSession";
ErrorDetails["KEY_SYSTEM_LICENSE_REQUEST_FAILED"] = "keySystemLicenseRequestFailed";
ErrorDetails["KEY_SYSTEM_NO_INIT_DATA"] = "keySystemNoInitData";
ErrorDetails["MANIFEST_LOAD_ERROR"] = "manifestLoadError";
ErrorDetails["MANIFEST_LOAD_TIMEOUT"] = "manifestLoadTimeOut";
ErrorDetails["MANIFEST_PARSING_ERROR"] = "manifestParsingError";
ErrorDetails["MANIFEST_INCOMPATIBLE_CODECS_ERROR"] = "manifestIncompatibleCodecsError";
ErrorDetails["LEVEL_EMPTY_ERROR"] = "levelEmptyError";
ErrorDetails["LEVEL_LOAD_ERROR"] = "levelLoadError";
ErrorDetails["LEVEL_LOAD_TIMEOUT"] = "levelLoadTimeOut";
ErrorDetails["LEVEL_SWITCH_ERROR"] = "levelSwitchError";
ErrorDetails["AUDIO_TRACK_LOAD_ERROR"] = "audioTrackLoadError";
ErrorDetails["AUDIO_TRACK_LOAD_TIMEOUT"] = "audioTrackLoadTimeOut";
ErrorDetails["SUBTITLE_LOAD_ERROR"] = "subtitleTrackLoadError";
ErrorDetails["SUBTITLE_TRACK_LOAD_TIMEOUT"] = "subtitleTrackLoadTimeOut";
ErrorDetails["FRAG_LOAD_ERROR"] = "fragLoadError";
ErrorDetails["FRAG_LOAD_TIMEOUT"] = "fragLoadTimeOut";
ErrorDetails["FRAG_DECRYPT_ERROR"] = "fragDecryptError";
ErrorDetails["FRAG_PARSING_ERROR"] = "fragParsingError";
ErrorDetails["REMUX_ALLOC_ERROR"] = "remuxAllocError";
ErrorDetails["KEY_LOAD_ERROR"] = "keyLoadError";
ErrorDetails["KEY_LOAD_TIMEOUT"] = "keyLoadTimeOut";
ErrorDetails["BUFFER_ADD_CODEC_ERROR"] = "bufferAddCodecError";
ErrorDetails["BUFFER_INCOMPATIBLE_CODECS_ERROR"] = "bufferIncompatibleCodecsError";
ErrorDetails["BUFFER_APPEND_ERROR"] = "bufferAppendError";
ErrorDetails["BUFFER_APPENDING_ERROR"] = "bufferAppendingError";
ErrorDetails["BUFFER_STALLED_ERROR"] = "bufferStalledError";
ErrorDetails["BUFFER_FULL_ERROR"] = "bufferFullError";
ErrorDetails["BUFFER_SEEK_OVER_HOLE"] = "bufferSeekOverHole";
ErrorDetails["BUFFER_NUDGE_ON_STALL"] = "bufferNudgeOnStall";
ErrorDetails["INTERNAL_EXCEPTION"] = "internalException";
ErrorDetails["INTERNAL_ABORTED"] = "aborted";
ErrorDetails["UNKNOWN"] = "unknown";
})(ErrorDetails || (ErrorDetails = {}));
/***/ }),
/***/ "./src/events.ts":
/*!***********************!*\
!*** ./src/events.ts ***!
\***********************/
/*! exports provided: Events */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Events", function() { return Events; });
/**
* @readonly
* @enum {string}
*/
var Events;
(function (Events) {
Events["MEDIA_ATTACHING"] = "hlsMediaAttaching";
Events["MEDIA_ATTACHED"] = "hlsMediaAttached";
Events["MEDIA_DETACHING"] = "hlsMediaDetaching";
Events["MEDIA_DETACHED"] = "hlsMediaDetached";
Events["BUFFER_RESET"] = "hlsBufferReset";
Events["BUFFER_CODECS"] = "hlsBufferCodecs";
Events["BUFFER_CREATED"] = "hlsBufferCreated";
Events["BUFFER_APPENDING"] = "hlsBufferAppending";
Events["BUFFER_APPENDED"] = "hlsBufferAppended";
Events["BUFFER_EOS"] = "hlsBufferEos";
Events["BUFFER_FLUSHING"] = "hlsBufferFlushing";
Events["BUFFER_FLUSHED"] = "hlsBufferFlushed";
Events["MANIFEST_LOADING"] = "hlsManifestLoading";
Events["MANIFEST_LOADED"] = "hlsManifestLoaded";
Events["MANIFEST_PARSED"] = "hlsManifestParsed";
Events["LEVEL_SWITCHING"] = "hlsLevelSwitching";
Events["LEVEL_SWITCHED"] = "hlsLevelSwitched";
Events["LEVEL_LOADING"] = "hlsLevelLoading";
Events["LEVEL_LOADED"] = "hlsLevelLoaded";
Events["LEVEL_UPDATED"] = "hlsLevelUpdated";
Events["LEVEL_PTS_UPDATED"] = "hlsLevelPtsUpdated";
Events["LEVELS_UPDATED"] = "hlsLevelsUpdated";
Events["AUDIO_TRACKS_UPDATED"] = "hlsAudioTracksUpdated";
Events["AUDIO_TRACK_SWITCHING"] = "hlsAudioTrackSwitching";
Events["AUDIO_TRACK_SWITCHED"] = "hlsAudioTrackSwitched";
Events["AUDIO_TRACK_LOADING"] = "hlsAudioTrackLoading";
Events["AUDIO_TRACK_LOADED"] = "hlsAudioTrackLoaded";
Events["SUBTITLE_TRACKS_UPDATED"] = "hlsSubtitleTracksUpdated";
Events["SUBTITLE_TRACKS_CLEARED"] = "hlsSubtitleTracksCleared";
Events["SUBTITLE_TRACK_SWITCH"] = "hlsSubtitleTrackSwitch";
Events["SUBTITLE_TRACK_LOADING"] = "hlsSubtitleTrackLoading";
Events["SUBTITLE_TRACK_LOADED"] = "hlsSubtitleTrackLoaded";
Events["SUBTITLE_FRAG_PROCESSED"] = "hlsSubtitleFragProcessed";
Events["CUES_PARSED"] = "hlsCuesParsed";
Events["NON_NATIVE_TEXT_TRACKS_FOUND"] = "hlsNonNativeTextTracksFound";
Events["INIT_PTS_FOUND"] = "hlsInitPtsFound";
Events["FRAG_LOADING"] = "hlsFragLoading";
Events["FRAG_LOAD_EMERGENCY_ABORTED"] = "hlsFragLoadEmergencyAborted";
Events["FRAG_LOADED"] = "hlsFragLoaded";
Events["FRAG_DECRYPTED"] = "hlsFragDecrypted";
Events["FRAG_PARSING_INIT_SEGMENT"] = "hlsFragParsingInitSegment";
Events["FRAG_PARSING_USERDATA"] = "hlsFragParsingUserdata";
Events["FRAG_PARSING_METADATA"] = "hlsFragParsingMetadata";
Events["FRAG_PARSED"] = "hlsFragParsed";
Events["FRAG_BUFFERED"] = "hlsFragBuffered";
Events["FRAG_CHANGED"] = "hlsFragChanged";
Events["FPS_DROP"] = "hlsFpsDrop";
Events["FPS_DROP_LEVEL_CAPPING"] = "hlsFpsDropLevelCapping";
Events["ERROR"] = "hlsError";
Events["DESTROYING"] = "hlsDestroying";
Events["KEY_LOADING"] = "hlsKeyLoading";
Events["KEY_LOADED"] = "hlsKeyLoaded";
Events["LIVE_BACK_BUFFER_REACHED"] = "hlsLiveBackBufferReached";
Events["BACK_BUFFER_REACHED"] = "hlsBackBufferReached";
})(Events || (Events = {}));
/***/ }),
/***/ "./src/hls.ts":
/*!********************!*\
!*** ./src/hls.ts ***!
\********************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Hls; });
/* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! url-toolkit */ "./node_modules/url-toolkit/src/url-toolkit.js");
/* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(url_toolkit__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _loader_playlist_loader__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./loader/playlist-loader */ "./src/loader/playlist-loader.ts");
/* harmony import */ var _loader_key_loader__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./loader/key-loader */ "./src/loader/key-loader.ts");
/* harmony import */ var _controller_id3_track_controller__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./controller/id3-track-controller */ "./src/controller/id3-track-controller.ts");
/* harmony import */ var _controller_latency_controller__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./controller/latency-controller */ "./src/controller/latency-controller.ts");
/* harmony import */ var _controller_level_controller__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./controller/level-controller */ "./src/controller/level-controller.ts");
/* harmony import */ var _controller_fragment_tracker__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./controller/fragment-tracker */ "./src/controller/fragment-tracker.ts");
/* harmony import */ var _controller_stream_controller__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./controller/stream-controller */ "./src/controller/stream-controller.ts");
/* harmony import */ var _is_supported__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./is-supported */ "./src/is-supported.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./utils/logger */ "./src/utils/logger.ts");
/* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./config */ "./src/config.ts");
/* harmony import */ var eventemitter3__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! eventemitter3 */ "./node_modules/eventemitter3/index.js");
/* harmony import */ var eventemitter3__WEBPACK_IMPORTED_MODULE_11___default = /*#__PURE__*/__webpack_require__.n(eventemitter3__WEBPACK_IMPORTED_MODULE_11__);
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./events */ "./src/events.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./errors */ "./src/errors.ts");
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
/**
* @module Hls
* @class
* @constructor
*/
var Hls = /*#__PURE__*/function () {
Hls.isSupported = function isSupported() {
return Object(_is_supported__WEBPACK_IMPORTED_MODULE_8__["isSupported"])();
};
/**
* Creates an instance of an HLS client that can attach to exactly one `HTMLMediaElement`.
*
* @constructs Hls
* @param {HlsConfig} config
*/
function Hls(userConfig) {
if (userConfig === void 0) {
userConfig = {};
}
this.config = void 0;
this.userConfig = void 0;
this.coreComponents = void 0;
this.networkControllers = void 0;
this._emitter = new eventemitter3__WEBPACK_IMPORTED_MODULE_11__["EventEmitter"]();
this._autoLevelCapping = void 0;
this.abrController = void 0;
this.bufferController = void 0;
this.capLevelController = void 0;
this.latencyController = void 0;
this.levelController = void 0;
this.streamController = void 0;
this.audioTrackController = void 0;
this.subtitleTrackController = void 0;
this.emeController = void 0;
this.cmcdController = void 0;
this._media = null;
this.url = null;
var config = this.config = Object(_config__WEBPACK_IMPORTED_MODULE_10__["mergeConfig"])(Hls.DefaultConfig, userConfig);
this.userConfig = userConfig;
Object(_utils_logger__WEBPACK_IMPORTED_MODULE_9__["enableLogs"])(config.debug);
this._autoLevelCapping = -1;
if (config.progressive) {
Object(_config__WEBPACK_IMPORTED_MODULE_10__["enableStreamingMode"])(config);
} // core controllers and network loaders
var ConfigAbrController = config.abrController,
ConfigBufferController = config.bufferController,
ConfigCapLevelController = config.capLevelController,
ConfigFpsController = config.fpsController;
var abrController = this.abrController = new ConfigAbrController(this);
var bufferController = this.bufferController = new ConfigBufferController(this);
var capLevelController = this.capLevelController = new ConfigCapLevelController(this);
var fpsController = new ConfigFpsController(this);
var playListLoader = new _loader_playlist_loader__WEBPACK_IMPORTED_MODULE_1__["default"](this);
var keyLoader = new _loader_key_loader__WEBPACK_IMPORTED_MODULE_2__["default"](this);
var id3TrackController = new _controller_id3_track_controller__WEBPACK_IMPORTED_MODULE_3__["default"](this); // network controllers
var levelController = this.levelController = new _controller_level_controller__WEBPACK_IMPORTED_MODULE_5__["default"](this); // FragmentTracker must be defined before StreamController because the order of event handling is important
var fragmentTracker = new _controller_fragment_tracker__WEBPACK_IMPORTED_MODULE_6__["FragmentTracker"](this);
var streamController = this.streamController = new _controller_stream_controller__WEBPACK_IMPORTED_MODULE_7__["default"](this, fragmentTracker); // Cap level controller uses streamController to flush the buffer
capLevelController.setStreamController(streamController); // fpsController uses streamController to switch when frames are being dropped
fpsController.setStreamController(streamController);
var networkControllers = [levelController, streamController];
this.networkControllers = networkControllers;
var coreComponents = [playListLoader, keyLoader, abrController, bufferController, capLevelController, fpsController, id3TrackController, fragmentTracker];
this.audioTrackController = this.createController(config.audioTrackController, null, networkControllers);
this.createController(config.audioStreamController, fragmentTracker, networkControllers); // subtitleTrackController must be defined before because the order of event handling is important
this.subtitleTrackController = this.createController(config.subtitleTrackController, null, networkControllers);
this.createController(config.subtitleStreamController, fragmentTracker, networkControllers);
this.createController(config.timelineController, null, coreComponents);
this.emeController = this.createController(config.emeController, null, coreComponents);
this.cmcdController = this.createController(config.cmcdController, null, coreComponents);
this.latencyController = this.createController(_controller_latency_controller__WEBPACK_IMPORTED_MODULE_4__["default"], null, coreComponents);
this.coreComponents = coreComponents;
}
var _proto = Hls.prototype;
_proto.createController = function createController(ControllerClass, fragmentTracker, components) {
if (ControllerClass) {
var controllerInstance = fragmentTracker ? new ControllerClass(this, fragmentTracker) : new ControllerClass(this);
if (components) {
components.push(controllerInstance);
}
return controllerInstance;
}
return null;
} // Delegate the EventEmitter through the public API of Hls.js
;
_proto.on = function on(event, listener, context) {
if (context === void 0) {
context = this;
}
this._emitter.on(event, listener, context);
};
_proto.once = function once(event, listener, context) {
if (context === void 0) {
context = this;
}
this._emitter.once(event, listener, context);
};
_proto.removeAllListeners = function removeAllListeners(event) {
this._emitter.removeAllListeners(event);
};
_proto.off = function off(event, listener, context, once) {
if (context === void 0) {
context = this;
}
this._emitter.off(event, listener, context, once);
};
_proto.listeners = function listeners(event) {
return this._emitter.listeners(event);
};
_proto.emit = function emit(event, name, eventObject) {
return this._emitter.emit(event, name, eventObject);
};
_proto.trigger = function trigger(event, eventObject) {
if (this.config.debug) {
return this.emit(event, event, eventObject);
} else {
try {
return this.emit(event, event, eventObject);
} catch (e) {
_utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].error('An internal error happened while handling event ' + event + '. Error message: "' + e.message + '". Here is a stacktrace:', e);
this.trigger(_events__WEBPACK_IMPORTED_MODULE_12__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_13__["ErrorTypes"].OTHER_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_13__["ErrorDetails"].INTERNAL_EXCEPTION,
fatal: false,
event: event,
error: e
});
}
}
return false;
};
_proto.listenerCount = function listenerCount(event) {
return this._emitter.listenerCount(event);
}
/**
* Dispose of the instance
*/
;
_proto.destroy = function destroy() {
_utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log('destroy');
this.trigger(_events__WEBPACK_IMPORTED_MODULE_12__["Events"].DESTROYING, undefined);
this.detachMedia();
this.removeAllListeners();
this._autoLevelCapping = -1;
this.url = null;
this.networkControllers.forEach(function (component) {
return component.destroy();
});
this.networkControllers.length = 0;
this.coreComponents.forEach(function (component) {
return component.destroy();
});
this.coreComponents.length = 0;
}
/**
* Attaches Hls.js to a media element
* @param {HTMLMediaElement} media
*/
;
_proto.attachMedia = function attachMedia(media) {
_utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log('attachMedia');
this._media = media;
this.trigger(_events__WEBPACK_IMPORTED_MODULE_12__["Events"].MEDIA_ATTACHING, {
media: media
});
}
/**
* Detach Hls.js from the media
*/
;
_proto.detachMedia = function detachMedia() {
_utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log('detachMedia');
this.trigger(_events__WEBPACK_IMPORTED_MODULE_12__["Events"].MEDIA_DETACHING, undefined);
this._media = null;
}
/**
* Set the source URL. Can be relative or absolute.
* @param {string} url
*/
;
_proto.loadSource = function loadSource(url) {
this.stopLoad();
var media = this.media;
var loadedSource = this.url;
var loadingSource = this.url = url_toolkit__WEBPACK_IMPORTED_MODULE_0__["buildAbsoluteURL"](self.location.href, url, {
alwaysNormalize: true
});
_utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log("loadSource:" + loadingSource);
if (media && loadedSource && loadedSource !== loadingSource && this.bufferController.hasSourceTypes()) {
this.detachMedia();
this.attachMedia(media);
} // when attaching to a source URL, trigger a playlist load
this.trigger(_events__WEBPACK_IMPORTED_MODULE_12__["Events"].MANIFEST_LOADING, {
url: url
});
}
/**
* Start loading data from the stream source.
* Depending on default config, client starts loading automatically when a source is set.
*
* @param {number} startPosition Set the start position to stream from
* @default -1 None (from earliest point)
*/
;
_proto.startLoad = function startLoad(startPosition) {
if (startPosition === void 0) {
startPosition = -1;
}
_utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log("startLoad(" + startPosition + ")");
this.networkControllers.forEach(function (controller) {
controller.startLoad(startPosition);
});
}
/**
* Stop loading of any stream data.
*/
;
_proto.stopLoad = function stopLoad() {
_utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log('stopLoad');
this.networkControllers.forEach(function (controller) {
controller.stopLoad();
});
}
/**
* Swap through possible audio codecs in the stream (for example to switch from stereo to 5.1)
*/
;
_proto.swapAudioCodec = function swapAudioCodec() {
_utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log('swapAudioCodec');
this.streamController.swapAudioCodec();
}
/**
* When the media-element fails, this allows to detach and then re-attach it
* as one call (convenience method).
*
* Automatic recovery of media-errors by this process is configurable.
*/
;
_proto.recoverMediaError = function recoverMediaError() {
_utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log('recoverMediaError');
var media = this._media;
this.detachMedia();
if (media) {
this.attachMedia(media);
}
};
_proto.removeLevel = function removeLevel(levelIndex, urlId) {
if (urlId === void 0) {
urlId = 0;
}
this.levelController.removeLevel(levelIndex, urlId);
}
/**
* @type {Level[]}
*/
;
_createClass(Hls, [{
key: "levels",
get: function get() {
var levels = this.levelController.levels;
return levels ? levels : [];
}
/**
* Index of quality level currently played
* @type {number}
*/
}, {
key: "currentLevel",
get: function get() {
return this.streamController.currentLevel;
}
/**
* Set quality level index immediately .
* This will flush the current buffer to replace the quality asap.
* That means playback will interrupt at least shortly to re-buffer and re-sync eventually.
* @type {number} -1 for automatic level selection
*/
,
set: function set(newLevel) {
_utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log("set currentLevel:" + newLevel);
this.loadLevel = newLevel;
this.abrController.clearTimer();
this.streamController.immediateLevelSwitch();
}
/**
* Index of next quality level loaded as scheduled by stream controller.
* @type {number}
*/
}, {
key: "nextLevel",
get: function get() {
return this.streamController.nextLevel;
}
/**
* Set quality level index for next loaded data.
* This will switch the video quality asap, without interrupting playback.
* May abort current loading of data, and flush parts of buffer (outside currently played fragment region).
* @type {number} -1 for automatic level selection
*/
,
set: function set(newLevel) {
_utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log("set nextLevel:" + newLevel);
this.levelController.manualLevel = newLevel;
this.streamController.nextLevelSwitch();
}
/**
* Return the quality level of the currently or last (of none is loaded currently) segment
* @type {number}
*/
}, {
key: "loadLevel",
get: function get() {
return this.levelController.level;
}
/**
* Set quality level index for next loaded data in a conservative way.
* This will switch the quality without flushing, but interrupt current loading.
* Thus the moment when the quality switch will appear in effect will only be after the already existing buffer.
* @type {number} newLevel -1 for automatic level selection
*/
,
set: function set(newLevel) {
_utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log("set loadLevel:" + newLevel);
this.levelController.manualLevel = newLevel;
}
/**
* get next quality level loaded
* @type {number}
*/
}, {
key: "nextLoadLevel",
get: function get() {
return this.levelController.nextLoadLevel;
}
/**
* Set quality level of next loaded segment in a fully "non-destructive" way.
* Same as `loadLevel` but will wait for next switch (until current loading is done).
* @type {number} level
*/
,
set: function set(level) {
this.levelController.nextLoadLevel = level;
}
/**
* Return "first level": like a default level, if not set,
* falls back to index of first level referenced in manifest
* @type {number}
*/
}, {
key: "firstLevel",
get: function get() {
return Math.max(this.levelController.firstLevel, this.minAutoLevel);
}
/**
* Sets "first-level", see getter.
* @type {number}
*/
,
set: function set(newLevel) {
_utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log("set firstLevel:" + newLevel);
this.levelController.firstLevel = newLevel;
}
/**
* Return start level (level of first fragment that will be played back)
* if not overrided by user, first level appearing in manifest will be used as start level
* if -1 : automatic start level selection, playback will start from level matching download bandwidth
* (determined from download of first segment)
* @type {number}
*/
}, {
key: "startLevel",
get: function get() {
return this.levelController.startLevel;
}
/**
* set start level (level of first fragment that will be played back)
* if not overrided by user, first level appearing in manifest will be used as start level
* if -1 : automatic start level selection, playback will start from level matching download bandwidth
* (determined from download of first segment)
* @type {number} newLevel
*/
,
set: function set(newLevel) {
_utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log("set startLevel:" + newLevel); // if not in automatic start level detection, ensure startLevel is greater than minAutoLevel
if (newLevel !== -1) {
newLevel = Math.max(newLevel, this.minAutoLevel);
}
this.levelController.startLevel = newLevel;
}
/**
* Get the current setting for capLevelToPlayerSize
*
* @type {boolean}
*/
}, {
key: "capLevelToPlayerSize",
get: function get() {
return this.config.capLevelToPlayerSize;
}
/**
* set dynamically set capLevelToPlayerSize against (`CapLevelController`)
*
* @type {boolean}
*/
,
set: function set(shouldStartCapping) {
var newCapLevelToPlayerSize = !!shouldStartCapping;
if (newCapLevelToPlayerSize !== this.config.capLevelToPlayerSize) {
if (newCapLevelToPlayerSize) {
this.capLevelController.startCapping(); // If capping occurs, nextLevelSwitch will happen based on size.
} else {
this.capLevelController.stopCapping();
this.autoLevelCapping = -1;
this.streamController.nextLevelSwitch(); // Now we're uncapped, get the next level asap.
}
this.config.capLevelToPlayerSize = newCapLevelToPlayerSize;
}
}
/**
* Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)
* @type {number}
*/
}, {
key: "autoLevelCapping",
get: function get() {
return this._autoLevelCapping;
}
/**
* get bandwidth estimate
* @type {number}
*/
,
set:
/**
* Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)
* @type {number}
*/
function set(newLevel) {
if (this._autoLevelCapping !== newLevel) {
_utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log("set autoLevelCapping:" + newLevel);
this._autoLevelCapping = newLevel;
}
}
/**
* True when automatic level selection enabled
* @type {boolean}
*/
}, {
key: "bandwidthEstimate",
get: function get() {
var bwEstimator = this.abrController.bwEstimator;
if (!bwEstimator) {
return NaN;
}
return bwEstimator.getEstimate();
}
}, {
key: "autoLevelEnabled",
get: function get() {
return this.levelController.manualLevel === -1;
}
/**
* Level set manually (if any)
* @type {number}
*/
}, {
key: "manualLevel",
get: function get() {
return this.levelController.manualLevel;
}
/**
* min level selectable in auto mode according to config.minAutoBitrate
* @type {number}
*/
}, {
key: "minAutoLevel",
get: function get() {
var levels = this.levels,
minAutoBitrate = this.config.minAutoBitrate;
if (!levels) return 0;
var len = levels.length;
for (var i = 0; i < len; i++) {
if (levels[i].maxBitrate > minAutoBitrate) {
return i;
}
}
return 0;
}
/**
* max level selectable in auto mode according to autoLevelCapping
* @type {number}
*/
}, {
key: "maxAutoLevel",
get: function get() {
var levels = this.levels,
autoLevelCapping = this.autoLevelCapping;
var maxAutoLevel;
if (autoLevelCapping === -1 && levels && levels.length) {
maxAutoLevel = levels.length - 1;
} else {
maxAutoLevel = autoLevelCapping;
}
return maxAutoLevel;
}
/**
* next automatically selected quality level
* @type {number}
*/
}, {
key: "nextAutoLevel",
get: function get() {
// ensure next auto level is between min and max auto level
return Math.min(Math.max(this.abrController.nextAutoLevel, this.minAutoLevel), this.maxAutoLevel);
}
/**
* this setter is used to force next auto level.
* this is useful to force a switch down in auto mode:
* in case of load error on level N, hls.js can set nextAutoLevel to N-1 for example)
* forced value is valid for one fragment. upon succesful frag loading at forced level,
* this value will be resetted to -1 by ABR controller.
* @type {number}
*/
,
set: function set(nextLevel) {
this.abrController.nextAutoLevel = Math.max(this.minAutoLevel, nextLevel);
}
/**
* @type {AudioTrack[]}
*/
}, {
key: "audioTracks",
get: function get() {
var audioTrackController = this.audioTrackController;
return audioTrackController ? audioTrackController.audioTracks : [];
}
/**
* index of the selected audio track (index in audio track lists)
* @type {number}
*/
}, {
key: "audioTrack",
get: function get() {
var audioTrackController = this.audioTrackController;
return audioTrackController ? audioTrackController.audioTrack : -1;
}
/**
* selects an audio track, based on its index in audio track lists
* @type {number}
*/
,
set: function set(audioTrackId) {
var audioTrackController = this.audioTrackController;
if (audioTrackController) {
audioTrackController.audioTrack = audioTrackId;
}
}
/**
* get alternate subtitle tracks list from playlist
* @type {MediaPlaylist[]}
*/
}, {
key: "subtitleTracks",
get: function get() {
var subtitleTrackController = this.subtitleTrackController;
return subtitleTrackController ? subtitleTrackController.subtitleTracks : [];
}
/**
* index of the selected subtitle track (index in subtitle track lists)
* @type {number}
*/
}, {
key: "subtitleTrack",
get: function get() {
var subtitleTrackController = this.subtitleTrackController;
return subtitleTrackController ? subtitleTrackController.subtitleTrack : -1;
},
set:
/**
* select an subtitle track, based on its index in subtitle track lists
* @type {number}
*/
function set(subtitleTrackId) {
var subtitleTrackController = this.subtitleTrackController;
if (subtitleTrackController) {
subtitleTrackController.subtitleTrack = subtitleTrackId;
}
}
/**
* @type {boolean}
*/
}, {
key: "media",
get: function get() {
return this._media;
}
}, {
key: "subtitleDisplay",
get: function get() {
var subtitleTrackController = this.subtitleTrackController;
return subtitleTrackController ? subtitleTrackController.subtitleDisplay : false;
}
/**
* Enable/disable subtitle display rendering
* @type {boolean}
*/
,
set: function set(value) {
var subtitleTrackController = this.subtitleTrackController;
if (subtitleTrackController) {
subtitleTrackController.subtitleDisplay = value;
}
}
/**
* get mode for Low-Latency HLS loading
* @type {boolean}
*/
}, {
key: "lowLatencyMode",
get: function get() {
return this.config.lowLatencyMode;
}
/**
* Enable/disable Low-Latency HLS part playlist and segment loading, and start live streams at playlist PART-HOLD-BACK rather than HOLD-BACK.
* @type {boolean}
*/
,
set: function set(mode) {
this.config.lowLatencyMode = mode;
}
/**
* position (in seconds) of live sync point (ie edge of live position minus safety delay defined by ```hls.config.liveSyncDuration```)
* @type {number}
*/
}, {
key: "liveSyncPosition",
get: function get() {
return this.latencyController.liveSyncPosition;
}
/**
* estimated position (in seconds) of live edge (ie edge of live playlist plus time sync playlist advanced)
* returns 0 before first playlist is loaded
* @type {number}
*/
}, {
key: "latency",
get: function get() {
return this.latencyController.latency;
}
/**
* maximum distance from the edge before the player seeks forward to ```hls.liveSyncPosition```
* configured using ```liveMaxLatencyDurationCount``` (multiple of target duration) or ```liveMaxLatencyDuration```
* returns 0 before first playlist is loaded
* @type {number}
*/
}, {
key: "maxLatency",
get: function get() {
return this.latencyController.maxLatency;
}
/**
* target distance from the edge as calculated by the latency controller
* @type {number}
*/
}, {
key: "targetLatency",
get: function get() {
return this.latencyController.targetLatency;
}
/**
* the rate at which the edge of the current live playlist is advancing or 1 if there is none
* @type {number}
*/
}, {
key: "drift",
get: function get() {
return this.latencyController.drift;
}
/**
* set to true when startLoad is called before MANIFEST_PARSED event
* @type {boolean}
*/
}, {
key: "forceStartLoad",
get: function get() {
return this.streamController.forceStartLoad;
}
}], [{
key: "version",
get: function get() {
return "1.1.2-0.canary.8068";
}
}, {
key: "Events",
get: function get() {
return _events__WEBPACK_IMPORTED_MODULE_12__["Events"];
}
}, {
key: "ErrorTypes",
get: function get() {
return _errors__WEBPACK_IMPORTED_MODULE_13__["ErrorTypes"];
}
}, {
key: "ErrorDetails",
get: function get() {
return _errors__WEBPACK_IMPORTED_MODULE_13__["ErrorDetails"];
}
}, {
key: "DefaultConfig",
get: function get() {
if (!Hls.defaultConfig) {
return _config__WEBPACK_IMPORTED_MODULE_10__["hlsDefaultConfig"];
}
return Hls.defaultConfig;
}
/**
* @type {HlsConfig}
*/
,
set: function set(defaultConfig) {
Hls.defaultConfig = defaultConfig;
}
}]);
return Hls;
}();
Hls.defaultConfig = void 0;
/***/ }),
/***/ "./src/is-supported.ts":
/*!*****************************!*\
!*** ./src/is-supported.ts ***!
\*****************************/
/*! exports provided: isSupported, changeTypeSupported */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isSupported", function() { return isSupported; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "changeTypeSupported", function() { return changeTypeSupported; });
/* harmony import */ var _utils_mediasource_helper__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utils/mediasource-helper */ "./src/utils/mediasource-helper.ts");
function getSourceBuffer() {
return self.SourceBuffer || self.WebKitSourceBuffer;
}
function isSupported() {
var mediaSource = Object(_utils_mediasource_helper__WEBPACK_IMPORTED_MODULE_0__["getMediaSource"])();
if (!mediaSource) {
return false;
}
var sourceBuffer = getSourceBuffer();
var isTypeSupported = mediaSource && typeof mediaSource.isTypeSupported === 'function' && mediaSource.isTypeSupported('video/mp4; codecs="avc1.42E01E,mp4a.40.2"'); // if SourceBuffer is exposed ensure its API is valid
// safari and old version of Chrome doe not expose SourceBuffer globally so checking SourceBuffer.prototype is impossible
var sourceBufferValidAPI = !sourceBuffer || sourceBuffer.prototype && typeof sourceBuffer.prototype.appendBuffer === 'function' && typeof sourceBuffer.prototype.remove === 'function';
return !!isTypeSupported && !!sourceBufferValidAPI;
}
function changeTypeSupported() {
var _sourceBuffer$prototy;
var sourceBuffer = getSourceBuffer();
return typeof (sourceBuffer === null || sourceBuffer === void 0 ? void 0 : (_sourceBuffer$prototy = sourceBuffer.prototype) === null || _sourceBuffer$prototy === void 0 ? void 0 : _sourceBuffer$prototy.changeType) === 'function';
}
/***/ }),
/***/ "./src/loader/fragment-loader.ts":
/*!***************************************!*\
!*** ./src/loader/fragment-loader.ts ***!
\***************************************/
/*! exports provided: default, LoadError */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return FragmentLoader; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LoadError", function() { return LoadError; });
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); }
function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
var MIN_CHUNK_SIZE = Math.pow(2, 17); // 128kb
var FragmentLoader = /*#__PURE__*/function () {
function FragmentLoader(config) {
this.config = void 0;
this.loader = null;
this.partLoadTimeout = -1;
this.config = config;
}
var _proto = FragmentLoader.prototype;
_proto.destroy = function destroy() {
if (this.loader) {
this.loader.destroy();
this.loader = null;
}
};
_proto.abort = function abort() {
if (this.loader) {
// Abort the loader for current fragment. Only one may load at any given time
this.loader.abort();
}
};
_proto.load = function load(frag, _onProgress) {
var _this = this;
var url = frag.url;
if (!url) {
return Promise.reject(new LoadError({
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].NETWORK_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].FRAG_LOAD_ERROR,
fatal: false,
frag: frag,
networkDetails: null
}, "Fragment does not have a " + (url ? 'part list' : 'url')));
}
this.abort();
var config = this.config;
var FragmentILoader = config.fLoader;
var DefaultILoader = config.loader;
return new Promise(function (resolve, reject) {
if (_this.loader) {
_this.loader.destroy();
}
var loader = _this.loader = frag.loader = FragmentILoader ? new FragmentILoader(config) : new DefaultILoader(config);
var loaderContext = createLoaderContext(frag);
var loaderConfig = {
timeout: config.fragLoadingTimeOut,
maxRetry: 0,
retryDelay: 0,
maxRetryDelay: config.fragLoadingMaxRetryTimeout,
highWaterMark: MIN_CHUNK_SIZE
}; // Assign frag stats to the loader's stats reference
frag.stats = loader.stats;
loader.load(loaderContext, loaderConfig, {
onSuccess: function onSuccess(response, stats, context, networkDetails) {
_this.resetLoader(frag, loader);
resolve({
frag: frag,
part: null,
payload: response.data,
networkDetails: networkDetails
});
},
onError: function onError(response, context, networkDetails) {
_this.resetLoader(frag, loader);
reject(new LoadError({
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].NETWORK_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].FRAG_LOAD_ERROR,
fatal: false,
frag: frag,
response: response,
networkDetails: networkDetails
}));
},
onAbort: function onAbort(stats, context, networkDetails) {
_this.resetLoader(frag, loader);
reject(new LoadError({
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].NETWORK_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].INTERNAL_ABORTED,
fatal: false,
frag: frag,
networkDetails: networkDetails
}));
},
onTimeout: function onTimeout(response, context, networkDetails) {
_this.resetLoader(frag, loader);
reject(new LoadError({
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].NETWORK_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].FRAG_LOAD_TIMEOUT,
fatal: false,
frag: frag,
networkDetails: networkDetails
}));
},
onProgress: function onProgress(stats, context, data, networkDetails) {
if (_onProgress) {
_onProgress({
frag: frag,
part: null,
payload: data,
networkDetails: networkDetails
});
}
}
});
});
};
_proto.loadPart = function loadPart(frag, part, onProgress) {
var _this2 = this;
this.abort();
var config = this.config;
var FragmentILoader = config.fLoader;
var DefaultILoader = config.loader;
return new Promise(function (resolve, reject) {
if (_this2.loader) {
_this2.loader.destroy();
}
var loader = _this2.loader = frag.loader = FragmentILoader ? new FragmentILoader(config) : new DefaultILoader(config);
var loaderContext = createLoaderContext(frag, part);
var loaderConfig = {
timeout: config.fragLoadingTimeOut,
maxRetry: 0,
retryDelay: 0,
maxRetryDelay: config.fragLoadingMaxRetryTimeout,
highWaterMark: MIN_CHUNK_SIZE
}; // Assign part stats to the loader's stats reference
part.stats = loader.stats;
loader.load(loaderContext, loaderConfig, {
onSuccess: function onSuccess(response, stats, context, networkDetails) {
_this2.resetLoader(frag, loader);
_this2.updateStatsFromPart(frag, part);
var partLoadedData = {
frag: frag,
part: part,
payload: response.data,
networkDetails: networkDetails
};
onProgress(partLoadedData);
resolve(partLoadedData);
},
onError: function onError(response, context, networkDetails) {
_this2.resetLoader(frag, loader);
reject(new LoadError({
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].NETWORK_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].FRAG_LOAD_ERROR,
fatal: false,
frag: frag,
part: part,
response: response,
networkDetails: networkDetails
}));
},
onAbort: function onAbort(stats, context, networkDetails) {
frag.stats.aborted = part.stats.aborted;
_this2.resetLoader(frag, loader);
reject(new LoadError({
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].NETWORK_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].INTERNAL_ABORTED,
fatal: false,
frag: frag,
part: part,
networkDetails: networkDetails
}));
},
onTimeout: function onTimeout(response, context, networkDetails) {
_this2.resetLoader(frag, loader);
reject(new LoadError({
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].NETWORK_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].FRAG_LOAD_TIMEOUT,
fatal: false,
frag: frag,
part: part,
networkDetails: networkDetails
}));
}
});
});
};
_proto.updateStatsFromPart = function updateStatsFromPart(frag, part) {
var fragStats = frag.stats;
var partStats = part.stats;
var partTotal = partStats.total;
fragStats.loaded += partStats.loaded;
if (partTotal) {
var estTotalParts = Math.round(frag.duration / part.duration);
var estLoadedParts = Math.min(Math.round(fragStats.loaded / partTotal), estTotalParts);
var estRemainingParts = estTotalParts - estLoadedParts;
var estRemainingBytes = estRemainingParts * Math.round(fragStats.loaded / estLoadedParts);
fragStats.total = fragStats.loaded + estRemainingBytes;
} else {
fragStats.total = Math.max(fragStats.loaded, fragStats.total);
}
var fragLoading = fragStats.loading;
var partLoading = partStats.loading;
if (fragLoading.start) {
// add to fragment loader latency
fragLoading.first += partLoading.first - partLoading.start;
} else {
fragLoading.start = partLoading.start;
fragLoading.first = partLoading.first;
}
fragLoading.end = partLoading.end;
};
_proto.resetLoader = function resetLoader(frag, loader) {
frag.loader = null;
if (this.loader === loader) {
self.clearTimeout(this.partLoadTimeout);
this.loader = null;
}
loader.destroy();
};
return FragmentLoader;
}();
function createLoaderContext(frag, part) {
if (part === void 0) {
part = null;
}
var segment = part || frag;
var loaderContext = {
frag: frag,
part: part,
responseType: 'arraybuffer',
url: segment.url,
headers: {},
rangeStart: 0,
rangeEnd: 0
};
var start = segment.byteRangeStartOffset;
var end = segment.byteRangeEndOffset;
if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(start) && Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(end)) {
loaderContext.rangeStart = start;
loaderContext.rangeEnd = end;
}
return loaderContext;
}
var LoadError = /*#__PURE__*/function (_Error) {
_inheritsLoose(LoadError, _Error);
function LoadError(data) {
var _this3;
for (var _len = arguments.length, params = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
params[_key - 1] = arguments[_key];
}
_this3 = _Error.call.apply(_Error, [this].concat(params)) || this;
_this3.data = void 0;
_this3.data = data;
return _this3;
}
return LoadError;
}( /*#__PURE__*/_wrapNativeSuper(Error));
/***/ }),
/***/ "./src/loader/fragment.ts":
/*!********************************!*\
!*** ./src/loader/fragment.ts ***!
\********************************/
/*! exports provided: ElementaryStreamTypes, BaseSegment, Fragment, Part */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ElementaryStreamTypes", function() { return ElementaryStreamTypes; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BaseSegment", function() { return BaseSegment; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Fragment", function() { return Fragment; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Part", function() { return Part; });
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! url-toolkit */ "./node_modules/url-toolkit/src/url-toolkit.js");
/* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(url_toolkit__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/* harmony import */ var _level_key__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./level-key */ "./src/loader/level-key.ts");
/* harmony import */ var _load_stats__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./load-stats */ "./src/loader/load-stats.ts");
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
var ElementaryStreamTypes;
(function (ElementaryStreamTypes) {
ElementaryStreamTypes["AUDIO"] = "audio";
ElementaryStreamTypes["VIDEO"] = "video";
ElementaryStreamTypes["AUDIOVIDEO"] = "audiovideo";
})(ElementaryStreamTypes || (ElementaryStreamTypes = {}));
var BaseSegment = /*#__PURE__*/function () {
// baseurl is the URL to the playlist
// relurl is the portion of the URL that comes from inside the playlist.
// Holds the types of data this fragment supports
function BaseSegment(baseurl) {
var _this$elementaryStrea;
this._byteRange = null;
this._url = null;
this.baseurl = void 0;
this.relurl = void 0;
this.elementaryStreams = (_this$elementaryStrea = {}, _this$elementaryStrea[ElementaryStreamTypes.AUDIO] = null, _this$elementaryStrea[ElementaryStreamTypes.VIDEO] = null, _this$elementaryStrea[ElementaryStreamTypes.AUDIOVIDEO] = null, _this$elementaryStrea);
this.baseurl = baseurl;
} // setByteRange converts a EXT-X-BYTERANGE attribute into a two element array
var _proto = BaseSegment.prototype;
_proto.setByteRange = function setByteRange(value, previous) {
var params = value.split('@', 2);
var byteRange = [];
if (params.length === 1) {
byteRange[0] = previous ? previous.byteRangeEndOffset : 0;
} else {
byteRange[0] = parseInt(params[1]);
}
byteRange[1] = parseInt(params[0]) + byteRange[0];
this._byteRange = byteRange;
};
_createClass(BaseSegment, [{
key: "byteRange",
get: function get() {
if (!this._byteRange) {
return [];
}
return this._byteRange;
}
}, {
key: "byteRangeStartOffset",
get: function get() {
return this.byteRange[0];
}
}, {
key: "byteRangeEndOffset",
get: function get() {
return this.byteRange[1];
}
}, {
key: "url",
get: function get() {
if (!this._url && this.baseurl && this.relurl) {
this._url = Object(url_toolkit__WEBPACK_IMPORTED_MODULE_1__["buildAbsoluteURL"])(this.baseurl, this.relurl, {
alwaysNormalize: true
});
}
return this._url || '';
},
set: function set(value) {
this._url = value;
}
}]);
return BaseSegment;
}();
var Fragment = /*#__PURE__*/function (_BaseSegment) {
_inheritsLoose(Fragment, _BaseSegment);
// EXTINF has to be present for a m38 to be considered valid
// sn notates the sequence number for a segment, and if set to a string can be 'initSegment'
// levelkey is the EXT-X-KEY that applies to this segment for decryption
// core difference from the private field _decryptdata is the lack of the initialized IV
// _decryptdata will set the IV for this segment based on the segment number in the fragment
// A string representing the fragment type
// A reference to the loader. Set while the fragment is loading, and removed afterwards. Used to abort fragment loading
// The level/track index to which the fragment belongs
// The continuity counter of the fragment
// The starting Presentation Time Stamp (PTS) of the fragment. Set after transmux complete.
// The ending Presentation Time Stamp (PTS) of the fragment. Set after transmux complete.
// The latest Presentation Time Stamp (PTS) appended to the buffer.
// The starting Decode Time Stamp (DTS) of the fragment. Set after transmux complete.
// The ending Decode Time Stamp (DTS) of the fragment. Set after transmux complete.
// The start time of the fragment, as listed in the manifest. Updated after transmux complete.
// Set by `updateFragPTSDTS` in level-helper
// The maximum starting Presentation Time Stamp (audio/video PTS) of the fragment. Set after transmux complete.
// The minimum ending Presentation Time Stamp (audio/video PTS) of the fragment. Set after transmux complete.
// Load/parse timing information
// A flag indicating whether the segment was downloaded in order to test bitrate, and was not buffered
// #EXTINF segment title
// The Media Initialization Section for this segment
function Fragment(type, baseurl) {
var _this;
_this = _BaseSegment.call(this, baseurl) || this;
_this._decryptdata = null;
_this.rawProgramDateTime = null;
_this.programDateTime = null;
_this.tagList = [];
_this.duration = 0;
_this.sn = 0;
_this.levelkey = void 0;
_this.type = void 0;
_this.loader = null;
_this.level = -1;
_this.cc = 0;
_this.startPTS = void 0;
_this.endPTS = void 0;
_this.appendedPTS = void 0;
_this.startDTS = void 0;
_this.endDTS = void 0;
_this.start = 0;
_this.deltaPTS = void 0;
_this.maxStartPTS = void 0;
_this.minEndPTS = void 0;
_this.stats = new _load_stats__WEBPACK_IMPORTED_MODULE_4__["LoadStats"]();
_this.urlId = 0;
_this.data = void 0;
_this.bitrateTest = false;
_this.title = null;
_this.initSegment = null;
_this.type = type;
return _this;
}
var _proto2 = Fragment.prototype;
/**
* Utility method for parseLevelPlaylist to create an initialization vector for a given segment
* @param {number} segmentNumber - segment number to generate IV with
* @returns {Uint8Array}
*/
_proto2.createInitializationVector = function createInitializationVector(segmentNumber) {
var uint8View = new Uint8Array(16);
for (var i = 12; i < 16; i++) {
uint8View[i] = segmentNumber >> 8 * (15 - i) & 0xff;
}
return uint8View;
}
/**
* Utility method for parseLevelPlaylist to get a fragment's decryption data from the currently parsed encryption key data
* @param levelkey - a playlist's encryption info
* @param segmentNumber - the fragment's segment number
* @returns {LevelKey} - an object to be applied as a fragment's decryptdata
*/
;
_proto2.setDecryptDataFromLevelKey = function setDecryptDataFromLevelKey(levelkey, segmentNumber) {
var decryptdata = levelkey;
if ((levelkey === null || levelkey === void 0 ? void 0 : levelkey.method) === 'AES-128' && levelkey.uri && !levelkey.iv) {
decryptdata = _level_key__WEBPACK_IMPORTED_MODULE_3__["LevelKey"].fromURI(levelkey.uri);
decryptdata.method = levelkey.method;
decryptdata.iv = this.createInitializationVector(segmentNumber);
decryptdata.keyFormat = 'identity';
}
return decryptdata;
};
_proto2.setElementaryStreamInfo = function setElementaryStreamInfo(type, startPTS, endPTS, startDTS, endDTS, partial) {
if (partial === void 0) {
partial = false;
}
var elementaryStreams = this.elementaryStreams;
var info = elementaryStreams[type];
if (!info) {
elementaryStreams[type] = {
startPTS: startPTS,
endPTS: endPTS,
startDTS: startDTS,
endDTS: endDTS,
partial: partial
};
return;
}
info.startPTS = Math.min(info.startPTS, startPTS);
info.endPTS = Math.max(info.endPTS, endPTS);
info.startDTS = Math.min(info.startDTS, startDTS);
info.endDTS = Math.max(info.endDTS, endDTS);
};
_proto2.clearElementaryStreamInfo = function clearElementaryStreamInfo() {
var elementaryStreams = this.elementaryStreams;
elementaryStreams[ElementaryStreamTypes.AUDIO] = null;
elementaryStreams[ElementaryStreamTypes.VIDEO] = null;
elementaryStreams[ElementaryStreamTypes.AUDIOVIDEO] = null;
};
_createClass(Fragment, [{
key: "decryptdata",
get: function get() {
if (!this.levelkey && !this._decryptdata) {
return null;
}
if (!this._decryptdata && this.levelkey) {
var sn = this.sn;
if (typeof sn !== 'number') {
// We are fetching decryption data for a initialization segment
// If the segment was encrypted with AES-128
// It must have an IV defined. We cannot substitute the Segment Number in.
if (this.levelkey && this.levelkey.method === 'AES-128' && !this.levelkey.iv) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn("missing IV for initialization segment with method=\"" + this.levelkey.method + "\" - compliance issue");
}
/*
Be converted to a Number.
'initSegment' will become NaN.
NaN, which when converted through ToInt32() -> +0.
---
Explicitly set sn to resulting value from implicit conversions 'initSegment' values for IV generation.
*/
sn = 0;
}
this._decryptdata = this.setDecryptDataFromLevelKey(this.levelkey, sn);
}
return this._decryptdata;
}
}, {
key: "end",
get: function get() {
return this.start + this.duration;
}
}, {
key: "endProgramDateTime",
get: function get() {
if (this.programDateTime === null) {
return null;
}
if (!Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(this.programDateTime)) {
return null;
}
var duration = !Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(this.duration) ? 0 : this.duration;
return this.programDateTime + duration * 1000;
}
}, {
key: "encrypted",
get: function get() {
var _this$decryptdata;
// At the m3u8-parser level we need to add support for manifest signalled keyformats
// when we want the fragment to start reporting that it is encrypted.
// Currently, keyFormat will only be set for identity keys
if ((_this$decryptdata = this.decryptdata) !== null && _this$decryptdata !== void 0 && _this$decryptdata.keyFormat && this.decryptdata.uri) {
return true;
}
return false;
}
}]);
return Fragment;
}(BaseSegment);
var Part = /*#__PURE__*/function (_BaseSegment2) {
_inheritsLoose(Part, _BaseSegment2);
function Part(partAttrs, frag, baseurl, index, previous) {
var _this2;
_this2 = _BaseSegment2.call(this, baseurl) || this;
_this2.fragOffset = 0;
_this2.duration = 0;
_this2.gap = false;
_this2.independent = false;
_this2.relurl = void 0;
_this2.fragment = void 0;
_this2.index = void 0;
_this2.stats = new _load_stats__WEBPACK_IMPORTED_MODULE_4__["LoadStats"]();
_this2.duration = partAttrs.decimalFloatingPoint('DURATION');
_this2.gap = partAttrs.bool('GAP');
_this2.independent = partAttrs.bool('INDEPENDENT');
_this2.relurl = partAttrs.enumeratedString('URI');
_this2.fragment = frag;
_this2.index = index;
var byteRange = partAttrs.enumeratedString('BYTERANGE');
if (byteRange) {
_this2.setByteRange(byteRange, previous);
}
if (previous) {
_this2.fragOffset = previous.fragOffset + previous.duration;
}
return _this2;
}
_createClass(Part, [{
key: "start",
get: function get() {
return this.fragment.start + this.fragOffset;
}
}, {
key: "end",
get: function get() {
return this.start + this.duration;
}
}, {
key: "loaded",
get: function get() {
var elementaryStreams = this.elementaryStreams;
return !!(elementaryStreams.audio || elementaryStreams.video || elementaryStreams.audiovideo);
}
}]);
return Part;
}(BaseSegment);
/***/ }),
/***/ "./src/loader/key-loader.ts":
/*!**********************************!*\
!*** ./src/loader/key-loader.ts ***!
\**********************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return KeyLoader; });
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/*
* Decrypt key Loader
*/
var KeyLoader = /*#__PURE__*/function () {
function KeyLoader(hls) {
this.hls = void 0;
this.loaders = {};
this.decryptkey = null;
this.decrypturl = null;
this.hls = hls;
this._registerListeners();
}
var _proto = KeyLoader.prototype;
_proto._registerListeners = function _registerListeners() {
this.hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].KEY_LOADING, this.onKeyLoading, this);
};
_proto._unregisterListeners = function _unregisterListeners() {
this.hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].KEY_LOADING, this.onKeyLoading);
};
_proto.destroy = function destroy() {
this._unregisterListeners();
for (var loaderName in this.loaders) {
var loader = this.loaders[loaderName];
if (loader) {
loader.destroy();
}
}
this.loaders = {};
};
_proto.onKeyLoading = function onKeyLoading(event, data) {
var frag = data.frag;
var type = frag.type;
var loader = this.loaders[type];
if (!frag.decryptdata) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn('Missing decryption data on fragment in onKeyLoading');
return;
} // Load the key if the uri is different from previous one, or if the decrypt key has not yet been retrieved
var uri = frag.decryptdata.uri;
if (uri !== this.decrypturl || this.decryptkey === null) {
var config = this.hls.config;
if (loader) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn("abort previous key loader for type:" + type);
loader.abort();
}
if (!uri) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn('key uri is falsy');
return;
}
var Loader = config.loader;
var fragLoader = frag.loader = this.loaders[type] = new Loader(config);
this.decrypturl = uri;
this.decryptkey = null;
var loaderContext = {
url: uri,
frag: frag,
responseType: 'arraybuffer'
}; // maxRetry is 0 so that instead of retrying the same key on the same variant multiple times,
// key-loader will trigger an error and rely on stream-controller to handle retry logic.
// this will also align retry logic with fragment-loader
var loaderConfig = {
timeout: config.fragLoadingTimeOut,
maxRetry: 0,
retryDelay: config.fragLoadingRetryDelay,
maxRetryDelay: config.fragLoadingMaxRetryTimeout,
highWaterMark: 0
};
var loaderCallbacks = {
onSuccess: this.loadsuccess.bind(this),
onError: this.loaderror.bind(this),
onTimeout: this.loadtimeout.bind(this)
};
fragLoader.load(loaderContext, loaderConfig, loaderCallbacks);
} else if (this.decryptkey) {
// Return the key if it's already been loaded
frag.decryptdata.key = this.decryptkey;
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].KEY_LOADED, {
frag: frag
});
}
};
_proto.loadsuccess = function loadsuccess(response, stats, context) {
var frag = context.frag;
if (!frag.decryptdata) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error('after key load, decryptdata unset');
return;
}
this.decryptkey = frag.decryptdata.key = new Uint8Array(response.data); // detach fragment loader on load success
frag.loader = null;
delete this.loaders[frag.type];
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].KEY_LOADED, {
frag: frag
});
};
_proto.loaderror = function loaderror(response, context) {
var frag = context.frag;
var loader = frag.loader;
if (loader) {
loader.abort();
}
delete this.loaders[frag.type];
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].NETWORK_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].KEY_LOAD_ERROR,
fatal: false,
frag: frag,
response: response
});
};
_proto.loadtimeout = function loadtimeout(stats, context) {
var frag = context.frag;
var loader = frag.loader;
if (loader) {
loader.abort();
}
delete this.loaders[frag.type];
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].NETWORK_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].KEY_LOAD_TIMEOUT,
fatal: false,
frag: frag
});
};
return KeyLoader;
}();
/***/ }),
/***/ "./src/loader/level-details.ts":
/*!*************************************!*\
!*** ./src/loader/level-details.ts ***!
\*************************************/
/*! exports provided: LevelDetails */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LevelDetails", function() { return LevelDetails; });
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
var DEFAULT_TARGET_DURATION = 10;
var LevelDetails = /*#__PURE__*/function () {
// Manifest reload synchronization
function LevelDetails(baseUrl) {
this.PTSKnown = false;
this.alignedSliding = false;
this.averagetargetduration = void 0;
this.endCC = 0;
this.endSN = 0;
this.fragments = void 0;
this.fragmentHint = void 0;
this.partList = null;
this.live = true;
this.ageHeader = 0;
this.advancedDateTime = void 0;
this.updated = true;
this.advanced = true;
this.availabilityDelay = void 0;
this.misses = 0;
this.needSidxRanges = false;
this.startCC = 0;
this.startSN = 0;
this.startTimeOffset = null;
this.targetduration = 0;
this.totalduration = 0;
this.type = null;
this.url = void 0;
this.m3u8 = '';
this.version = null;
this.canBlockReload = false;
this.canSkipUntil = 0;
this.canSkipDateRanges = false;
this.skippedSegments = 0;
this.recentlyRemovedDateranges = void 0;
this.partHoldBack = 0;
this.holdBack = 0;
this.partTarget = 0;
this.preloadHint = void 0;
this.renditionReports = void 0;
this.tuneInGoal = 0;
this.deltaUpdateFailed = void 0;
this.driftStartTime = 0;
this.driftEndTime = 0;
this.driftStart = 0;
this.driftEnd = 0;
this.fragments = [];
this.url = baseUrl;
}
var _proto = LevelDetails.prototype;
_proto.reloaded = function reloaded(previous) {
if (!previous) {
this.advanced = true;
this.updated = true;
return;
}
var partSnDiff = this.lastPartSn - previous.lastPartSn;
var partIndexDiff = this.lastPartIndex - previous.lastPartIndex;
this.updated = this.endSN !== previous.endSN || !!partIndexDiff || !!partSnDiff;
this.advanced = this.endSN > previous.endSN || partSnDiff > 0 || partSnDiff === 0 && partIndexDiff > 0;
if (this.updated || this.advanced) {
this.misses = Math.floor(previous.misses * 0.6);
} else {
this.misses = previous.misses + 1;
}
this.availabilityDelay = previous.availabilityDelay;
};
_createClass(LevelDetails, [{
key: "hasProgramDateTime",
get: function get() {
if (this.fragments.length) {
return Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(this.fragments[this.fragments.length - 1].programDateTime);
}
return false;
}
}, {
key: "levelTargetDuration",
get: function get() {
return this.averagetargetduration || this.targetduration || DEFAULT_TARGET_DURATION;
}
}, {
key: "drift",
get: function get() {
var runTime = this.driftEndTime - this.driftStartTime;
if (runTime > 0) {
var runDuration = this.driftEnd - this.driftStart;
return runDuration * 1000 / runTime;
}
return 1;
}
}, {
key: "edge",
get: function get() {
return this.partEnd || this.fragmentEnd;
}
}, {
key: "partEnd",
get: function get() {
var _this$partList;
if ((_this$partList = this.partList) !== null && _this$partList !== void 0 && _this$partList.length) {
return this.partList[this.partList.length - 1].end;
}
return this.fragmentEnd;
}
}, {
key: "fragmentEnd",
get: function get() {
var _this$fragments;
if ((_this$fragments = this.fragments) !== null && _this$fragments !== void 0 && _this$fragments.length) {
return this.fragments[this.fragments.length - 1].end;
}
return 0;
}
}, {
key: "age",
get: function get() {
if (this.advancedDateTime) {
return Math.max(Date.now() - this.advancedDateTime, 0) / 1000;
}
return 0;
}
}, {
key: "lastPartIndex",
get: function get() {
var _this$partList2;
if ((_this$partList2 = this.partList) !== null && _this$partList2 !== void 0 && _this$partList2.length) {
return this.partList[this.partList.length - 1].index;
}
return -1;
}
}, {
key: "lastPartSn",
get: function get() {
var _this$partList3;
if ((_this$partList3 = this.partList) !== null && _this$partList3 !== void 0 && _this$partList3.length) {
return this.partList[this.partList.length - 1].fragment.sn;
}
return this.endSN;
}
}]);
return LevelDetails;
}();
/***/ }),
/***/ "./src/loader/level-key.ts":
/*!*********************************!*\
!*** ./src/loader/level-key.ts ***!
\*********************************/
/*! exports provided: LevelKey */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LevelKey", function() { return LevelKey; });
/* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! url-toolkit */ "./node_modules/url-toolkit/src/url-toolkit.js");
/* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(url_toolkit__WEBPACK_IMPORTED_MODULE_0__);
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
var LevelKey = /*#__PURE__*/function () {
LevelKey.fromURL = function fromURL(baseUrl, relativeUrl) {
return new LevelKey(baseUrl, relativeUrl);
};
LevelKey.fromURI = function fromURI(uri) {
return new LevelKey(uri);
};
function LevelKey(absoluteOrBaseURI, relativeURL) {
this._uri = null;
this.method = null;
this.keyFormat = null;
this.keyFormatVersions = null;
this.keyID = null;
this.key = null;
this.iv = null;
if (relativeURL) {
this._uri = Object(url_toolkit__WEBPACK_IMPORTED_MODULE_0__["buildAbsoluteURL"])(absoluteOrBaseURI, relativeURL, {
alwaysNormalize: true
});
} else {
this._uri = absoluteOrBaseURI;
}
}
_createClass(LevelKey, [{
key: "uri",
get: function get() {
return this._uri;
}
}]);
return LevelKey;
}();
/***/ }),
/***/ "./src/loader/load-stats.ts":
/*!**********************************!*\
!*** ./src/loader/load-stats.ts ***!
\**********************************/
/*! exports provided: LoadStats */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LoadStats", function() { return LoadStats; });
var LoadStats = function LoadStats() {
this.aborted = false;
this.loaded = 0;
this.retry = 0;
this.total = 0;
this.chunkCount = 0;
this.bwEstimate = 0;
this.loading = {
start: 0,
first: 0,
end: 0
};
this.parsing = {
start: 0,
end: 0
};
this.buffering = {
start: 0,
first: 0,
end: 0
};
};
/***/ }),
/***/ "./src/loader/m3u8-parser.ts":
/*!***********************************!*\
!*** ./src/loader/m3u8-parser.ts ***!
\***********************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return M3U8Parser; });
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! url-toolkit */ "./node_modules/url-toolkit/src/url-toolkit.js");
/* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(url_toolkit__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _fragment__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./fragment */ "./src/loader/fragment.ts");
/* harmony import */ var _level_details__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./level-details */ "./src/loader/level-details.ts");
/* harmony import */ var _level_key__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./level-key */ "./src/loader/level-key.ts");
/* harmony import */ var _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/attr-list */ "./src/utils/attr-list.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/* harmony import */ var _utils_codecs__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../utils/codecs */ "./src/utils/codecs.ts");
// https://regex101.com is your friend
var MASTER_PLAYLIST_REGEX = /#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-SESSION-DATA:([^\r\n]*)[\r\n]+/g;
var MASTER_PLAYLIST_MEDIA_REGEX = /#EXT-X-MEDIA:(.*)/g;
var LEVEL_PLAYLIST_REGEX_FAST = new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source, // duration (#EXTINF:<duration>,<title>), group 1 => duration, group 2 => title
/(?!#) *(\S[\S ]*)/.source, // segment URI, group 3 => the URI (note newline is not eaten)
/#EXT-X-BYTERANGE:*(.+)/.source, // next segment's byterange, group 4 => range spec (x@y)
/#EXT-X-PROGRAM-DATE-TIME:(.+)/.source, // next segment's program date/time group 5 => the datetime spec
/#.*/.source // All other non-segment oriented tags will match with all groups empty
].join('|'), 'g');
var LEVEL_PLAYLIST_REGEX_SLOW = new RegExp([/#(EXTM3U)/.source, /#EXT-X-(PLAYLIST-TYPE):(.+)/.source, /#EXT-X-(MEDIA-SEQUENCE): *(\d+)/.source, /#EXT-X-(SKIP):(.+)/.source, /#EXT-X-(TARGETDURATION): *(\d+)/.source, /#EXT-X-(KEY):(.+)/.source, /#EXT-X-(START):(.+)/.source, /#EXT-X-(ENDLIST)/.source, /#EXT-X-(DISCONTINUITY-SEQ)UENCE: *(\d+)/.source, /#EXT-X-(DIS)CONTINUITY/.source, /#EXT-X-(VERSION):(\d+)/.source, /#EXT-X-(MAP):(.+)/.source, /#EXT-X-(SERVER-CONTROL):(.+)/.source, /#EXT-X-(PART-INF):(.+)/.source, /#EXT-X-(GAP)/.source, /#EXT-X-(BITRATE):\s*(\d+)/.source, /#EXT-X-(PART):(.+)/.source, /#EXT-X-(PRELOAD-HINT):(.+)/.source, /#EXT-X-(RENDITION-REPORT):(.+)/.source, /(#)([^:]*):(.*)/.source, /(#)(.*)(?:.*)\r?\n?/.source].join('|'));
var MP4_REGEX_SUFFIX = /\.(mp4|m4s|m4v|m4a)$/i;
function isMP4Url(url) {
var _URLToolkit$parseURL$, _URLToolkit$parseURL;
return MP4_REGEX_SUFFIX.test((_URLToolkit$parseURL$ = (_URLToolkit$parseURL = url_toolkit__WEBPACK_IMPORTED_MODULE_1__["parseURL"](url)) === null || _URLToolkit$parseURL === void 0 ? void 0 : _URLToolkit$parseURL.path) != null ? _URLToolkit$parseURL$ : '');
}
var M3U8Parser = /*#__PURE__*/function () {
function M3U8Parser() {}
M3U8Parser.findGroup = function findGroup(groups, mediaGroupId) {
for (var i = 0; i < groups.length; i++) {
var group = groups[i];
if (group.id === mediaGroupId) {
return group;
}
}
};
M3U8Parser.convertAVC1ToAVCOTI = function convertAVC1ToAVCOTI(codec) {
// Convert avc1 codec string from RFC-4281 to RFC-6381 for MediaSource.isTypeSupported
var avcdata = codec.split('.');
if (avcdata.length > 2) {
var result = avcdata.shift() + '.';
result += parseInt(avcdata.shift()).toString(16);
result += ('000' + parseInt(avcdata.shift()).toString(16)).substr(-4);
return result;
}
return codec;
};
M3U8Parser.resolve = function resolve(url, baseUrl) {
return url_toolkit__WEBPACK_IMPORTED_MODULE_1__["buildAbsoluteURL"](baseUrl, url, {
alwaysNormalize: true
});
};
M3U8Parser.parseMasterPlaylist = function parseMasterPlaylist(string, baseurl) {
var levels = [];
var sessionData = {};
var hasSessionData = false;
MASTER_PLAYLIST_REGEX.lastIndex = 0;
var result;
while ((result = MASTER_PLAYLIST_REGEX.exec(string)) != null) {
if (result[1]) {
// '#EXT-X-STREAM-INF' is found, parse level tag in group 1
var attrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](result[1]);
var level = {
attrs: attrs,
bitrate: attrs.decimalInteger('AVERAGE-BANDWIDTH') || attrs.decimalInteger('BANDWIDTH'),
name: attrs.NAME,
url: M3U8Parser.resolve(result[2], baseurl)
};
var resolution = attrs.decimalResolution('RESOLUTION');
if (resolution) {
level.width = resolution.width;
level.height = resolution.height;
}
setCodecs((attrs.CODECS || '').split(/[ ,]+/).filter(function (c) {
return c;
}), level);
if (level.videoCodec && level.videoCodec.indexOf('avc1') !== -1) {
level.videoCodec = M3U8Parser.convertAVC1ToAVCOTI(level.videoCodec);
}
levels.push(level);
} else if (result[3]) {
// '#EXT-X-SESSION-DATA' is found, parse session data in group 3
var sessionAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](result[3]);
if (sessionAttrs['DATA-ID']) {
hasSessionData = true;
sessionData[sessionAttrs['DATA-ID']] = sessionAttrs;
}
}
}
return {
levels: levels,
sessionData: hasSessionData ? sessionData : null
};
};
M3U8Parser.parseMasterPlaylistMedia = function parseMasterPlaylistMedia(string, baseurl, type, groups) {
if (groups === void 0) {
groups = [];
}
var result;
var medias = [];
var id = 0;
MASTER_PLAYLIST_MEDIA_REGEX.lastIndex = 0;
while ((result = MASTER_PLAYLIST_MEDIA_REGEX.exec(string)) !== null) {
var attrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](result[1]);
if (attrs.TYPE === type) {
var media = {
attrs: attrs,
bitrate: 0,
id: id++,
groupId: attrs['GROUP-ID'],
instreamId: attrs['INSTREAM-ID'],
name: attrs.NAME || attrs.LANGUAGE || '',
type: type,
default: attrs.bool('DEFAULT'),
autoselect: attrs.bool('AUTOSELECT'),
forced: attrs.bool('FORCED'),
lang: attrs.LANGUAGE,
url: attrs.URI ? M3U8Parser.resolve(attrs.URI, baseurl) : ''
};
if (groups.length) {
// If there are audio or text groups signalled in the manifest, let's look for a matching codec string for this track
// If we don't find the track signalled, lets use the first audio groups codec we have
// Acting as a best guess
var groupCodec = M3U8Parser.findGroup(groups, media.groupId) || groups[0];
assignCodec(media, groupCodec, 'audioCodec');
assignCodec(media, groupCodec, 'textCodec');
}
medias.push(media);
}
}
return medias;
};
M3U8Parser.parseLevelPlaylist = function parseLevelPlaylist(string, baseurl, id, type, levelUrlId) {
var level = new _level_details__WEBPACK_IMPORTED_MODULE_3__["LevelDetails"](baseurl);
var fragments = level.fragments; // The most recent init segment seen (applies to all subsequent segments)
var currentInitSegment = null;
var currentSN = 0;
var currentPart = 0;
var totalduration = 0;
var discontinuityCounter = 0;
var prevFrag = null;
var frag = new _fragment__WEBPACK_IMPORTED_MODULE_2__["Fragment"](type, baseurl);
var result;
var i;
var levelkey;
var firstPdtIndex = -1;
var createNextFrag = false;
LEVEL_PLAYLIST_REGEX_FAST.lastIndex = 0;
level.m3u8 = string;
while ((result = LEVEL_PLAYLIST_REGEX_FAST.exec(string)) !== null) {
if (createNextFrag) {
createNextFrag = false;
frag = new _fragment__WEBPACK_IMPORTED_MODULE_2__["Fragment"](type, baseurl); // setup the next fragment for part loading
frag.start = totalduration;
frag.sn = currentSN;
frag.cc = discontinuityCounter;
frag.level = id;
if (currentInitSegment) {
frag.initSegment = currentInitSegment;
frag.rawProgramDateTime = currentInitSegment.rawProgramDateTime;
}
}
var duration = result[1];
if (duration) {
// INF
frag.duration = parseFloat(duration); // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
var title = (' ' + result[2]).slice(1);
frag.title = title || null;
frag.tagList.push(title ? ['INF', duration, title] : ['INF', duration]);
} else if (result[3]) {
// url
if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(frag.duration)) {
frag.start = totalduration;
if (levelkey) {
frag.levelkey = levelkey;
}
frag.sn = currentSN;
frag.level = id;
frag.cc = discontinuityCounter;
frag.urlId = levelUrlId;
fragments.push(frag); // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
frag.relurl = (' ' + result[3]).slice(1);
assignProgramDateTime(frag, prevFrag);
prevFrag = frag;
totalduration += frag.duration;
currentSN++;
currentPart = 0;
createNextFrag = true;
}
} else if (result[4]) {
// X-BYTERANGE
var data = (' ' + result[4]).slice(1);
if (prevFrag) {
frag.setByteRange(data, prevFrag);
} else {
frag.setByteRange(data);
}
} else if (result[5]) {
// PROGRAM-DATE-TIME
// avoid sliced strings https://github.com/video-dev/hls.js/issues/939
frag.rawProgramDateTime = (' ' + result[5]).slice(1);
frag.tagList.push(['PROGRAM-DATE-TIME', frag.rawProgramDateTime]);
if (firstPdtIndex === -1) {
firstPdtIndex = fragments.length;
}
} else {
result = result[0].match(LEVEL_PLAYLIST_REGEX_SLOW);
if (!result) {
_utils_logger__WEBPACK_IMPORTED_MODULE_6__["logger"].warn('No matches on slow regex match for level playlist!');
continue;
}
for (i = 1; i < result.length; i++) {
if (typeof result[i] !== 'undefined') {
break;
}
} // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
var tag = (' ' + result[i]).slice(1);
var value1 = (' ' + result[i + 1]).slice(1);
var value2 = result[i + 2] ? (' ' + result[i + 2]).slice(1) : '';
switch (tag) {
case 'PLAYLIST-TYPE':
level.type = value1.toUpperCase();
break;
case 'MEDIA-SEQUENCE':
currentSN = level.startSN = parseInt(value1);
break;
case 'SKIP':
{
var skipAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](value1);
var skippedSegments = skipAttrs.decimalInteger('SKIPPED-SEGMENTS');
if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(skippedSegments)) {
level.skippedSegments = skippedSegments; // This will result in fragments[] containing undefined values, which we will fill in with `mergeDetails`
for (var _i = skippedSegments; _i--;) {
fragments.unshift(null);
}
currentSN += skippedSegments;
}
var recentlyRemovedDateranges = skipAttrs.enumeratedString('RECENTLY-REMOVED-DATERANGES');
if (recentlyRemovedDateranges) {
level.recentlyRemovedDateranges = recentlyRemovedDateranges.split('\t');
}
break;
}
case 'TARGETDURATION':
level.targetduration = parseFloat(value1);
break;
case 'VERSION':
level.version = parseInt(value1);
break;
case 'EXTM3U':
break;
case 'ENDLIST':
level.live = false;
break;
case '#':
if (value1 || value2) {
frag.tagList.push(value2 ? [value1, value2] : [value1]);
}
break;
case 'DIS':
discontinuityCounter++;
/* falls through */
case 'GAP':
frag.tagList.push([tag]);
break;
case 'BITRATE':
frag.tagList.push([tag, value1]);
break;
case 'DISCONTINUITY-SEQ':
discontinuityCounter = parseInt(value1);
break;
case 'KEY':
{
var _keyAttrs$enumeratedS;
// https://tools.ietf.org/html/rfc8216#section-4.3.2.4
var keyAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](value1);
var decryptmethod = keyAttrs.enumeratedString('METHOD');
var decrypturi = keyAttrs.URI;
var decryptiv = keyAttrs.hexadecimalInteger('IV');
var decryptkeyformatversions = keyAttrs.enumeratedString('KEYFORMATVERSIONS');
var decryptkeyid = keyAttrs.enumeratedString('KEYID'); // From RFC: This attribute is OPTIONAL; its absence indicates an implicit value of "identity".
var decryptkeyformat = (_keyAttrs$enumeratedS = keyAttrs.enumeratedString('KEYFORMAT')) != null ? _keyAttrs$enumeratedS : 'identity';
var unsupportedKnownKeyformatsInManifest = ['com.apple.streamingkeydelivery', 'com.microsoft.playready', 'urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed', // widevine (v2)
'com.widevine' // earlier widevine (v1)
];
if (unsupportedKnownKeyformatsInManifest.indexOf(decryptkeyformat) > -1) {
_utils_logger__WEBPACK_IMPORTED_MODULE_6__["logger"].warn("Keyformat " + decryptkeyformat + " is not supported from the manifest");
continue;
} else if (decryptkeyformat !== 'identity') {
// We are supposed to skip keys we don't understand.
// As we currently only officially support identity keys
// from the manifest we shouldn't save any other key.
continue;
} // TODO: multiple keys can be defined on a fragment, and we need to support this
// for clients that support both playready and widevine
if (decryptmethod) {
// TODO: need to determine if the level key is actually a relative URL
// if it isn't, then we should instead construct the LevelKey using fromURI.
levelkey = _level_key__WEBPACK_IMPORTED_MODULE_4__["LevelKey"].fromURL(baseurl, decrypturi);
if (decrypturi && ['AES-128', 'SAMPLE-AES', 'SAMPLE-AES-CENC'].indexOf(decryptmethod) >= 0) {
levelkey.method = decryptmethod;
levelkey.keyFormat = decryptkeyformat;
if (decryptkeyid) {
levelkey.keyID = decryptkeyid;
}
if (decryptkeyformatversions) {
levelkey.keyFormatVersions = decryptkeyformatversions;
} // Initialization Vector (IV)
levelkey.iv = decryptiv;
}
}
break;
}
case 'START':
{
var startAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](value1);
var startTimeOffset = startAttrs.decimalFloatingPoint('TIME-OFFSET'); // TIME-OFFSET can be 0
if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(startTimeOffset)) {
level.startTimeOffset = startTimeOffset;
}
break;
}
case 'MAP':
{
var mapAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](value1);
frag.relurl = mapAttrs.URI;
if (mapAttrs.BYTERANGE) {
frag.setByteRange(mapAttrs.BYTERANGE);
}
frag.level = id;
frag.sn = 'initSegment';
if (levelkey) {
frag.levelkey = levelkey;
}
frag.initSegment = null;
currentInitSegment = frag;
createNextFrag = true;
break;
}
case 'SERVER-CONTROL':
{
var serverControlAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](value1);
level.canBlockReload = serverControlAttrs.bool('CAN-BLOCK-RELOAD');
level.canSkipUntil = serverControlAttrs.optionalFloat('CAN-SKIP-UNTIL', 0);
level.canSkipDateRanges = level.canSkipUntil > 0 && serverControlAttrs.bool('CAN-SKIP-DATERANGES');
level.partHoldBack = serverControlAttrs.optionalFloat('PART-HOLD-BACK', 0);
level.holdBack = serverControlAttrs.optionalFloat('HOLD-BACK', 0);
break;
}
case 'PART-INF':
{
var partInfAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](value1);
level.partTarget = partInfAttrs.decimalFloatingPoint('PART-TARGET');
break;
}
case 'PART':
{
var partList = level.partList;
if (!partList) {
partList = level.partList = [];
}
var previousFragmentPart = currentPart > 0 ? partList[partList.length - 1] : undefined;
var index = currentPart++;
var part = new _fragment__WEBPACK_IMPORTED_MODULE_2__["Part"](new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](value1), frag, baseurl, index, previousFragmentPart);
partList.push(part);
frag.duration += part.duration;
break;
}
case 'PRELOAD-HINT':
{
var preloadHintAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](value1);
level.preloadHint = preloadHintAttrs;
break;
}
case 'RENDITION-REPORT':
{
var renditionReportAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](value1);
level.renditionReports = level.renditionReports || [];
level.renditionReports.push(renditionReportAttrs);
break;
}
default:
_utils_logger__WEBPACK_IMPORTED_MODULE_6__["logger"].warn("line parsed but not handled: " + result);
break;
}
}
}
if (prevFrag && !prevFrag.relurl) {
fragments.pop();
totalduration -= prevFrag.duration;
if (level.partList) {
level.fragmentHint = prevFrag;
}
} else if (level.partList) {
assignProgramDateTime(frag, prevFrag);
frag.cc = discontinuityCounter;
level.fragmentHint = frag;
}
var fragmentLength = fragments.length;
var firstFragment = fragments[0];
var lastFragment = fragments[fragmentLength - 1];
totalduration += level.skippedSegments * level.targetduration;
if (totalduration > 0 && fragmentLength && lastFragment) {
level.averagetargetduration = totalduration / fragmentLength;
var lastSn = lastFragment.sn;
level.endSN = lastSn !== 'initSegment' ? lastSn : 0;
if (firstFragment) {
level.startCC = firstFragment.cc;
if (!firstFragment.initSegment) {
// this is a bit lurky but HLS really has no other way to tell us
// if the fragments are TS or MP4, except if we download them :/
// but this is to be able to handle SIDX.
if (level.fragments.every(function (frag) {
return frag.relurl && isMP4Url(frag.relurl);
})) {
_utils_logger__WEBPACK_IMPORTED_MODULE_6__["logger"].warn('MP4 fragments found but no init segment (probably no MAP, incomplete M3U8), trying to fetch SIDX');
frag = new _fragment__WEBPACK_IMPORTED_MODULE_2__["Fragment"](type, baseurl);
frag.relurl = lastFragment.relurl;
frag.level = id;
frag.sn = 'initSegment';
firstFragment.initSegment = frag;
level.needSidxRanges = true;
}
}
}
} else {
level.endSN = 0;
level.startCC = 0;
}
if (level.fragmentHint) {
totalduration += level.fragmentHint.duration;
}
level.totalduration = totalduration;
level.endCC = discontinuityCounter;
/**
* Backfill any missing PDT values
* "If the first EXT-X-PROGRAM-DATE-TIME tag in a Playlist appears after
* one or more Media Segment URIs, the client SHOULD extrapolate
* backward from that tag (using EXTINF durations and/or media
* timestamps) to associate dates with those segments."
* We have already extrapolated forward, but all fragments up to the first instance of PDT do not have their PDTs
* computed.
*/
if (firstPdtIndex > 0) {
backfillProgramDateTimes(fragments, firstPdtIndex);
}
return level;
};
return M3U8Parser;
}();
function setCodecs(codecs, level) {
['video', 'audio', 'text'].forEach(function (type) {
var filtered = codecs.filter(function (codec) {
return Object(_utils_codecs__WEBPACK_IMPORTED_MODULE_7__["isCodecType"])(codec, type);
});
if (filtered.length) {
var preferred = filtered.filter(function (codec) {
return codec.lastIndexOf('avc1', 0) === 0 || codec.lastIndexOf('mp4a', 0) === 0;
});
level[type + "Codec"] = preferred.length > 0 ? preferred[0] : filtered[0]; // remove from list
codecs = codecs.filter(function (codec) {
return filtered.indexOf(codec) === -1;
});
}
});
level.unknownCodecs = codecs;
}
function assignCodec(media, groupItem, codecProperty) {
var codecValue = groupItem[codecProperty];
if (codecValue) {
media[codecProperty] = codecValue;
}
}
function backfillProgramDateTimes(fragments, firstPdtIndex) {
var fragPrev = fragments[firstPdtIndex];
for (var i = firstPdtIndex; i--;) {
var frag = fragments[i]; // Exit on delta-playlist skipped segments
if (!frag) {
return;
}
frag.programDateTime = fragPrev.programDateTime - frag.duration * 1000;
fragPrev = frag;
}
}
function assignProgramDateTime(frag, prevFrag) {
if (frag.rawProgramDateTime) {
frag.programDateTime = Date.parse(frag.rawProgramDateTime);
} else if (prevFrag !== null && prevFrag !== void 0 && prevFrag.programDateTime) {
frag.programDateTime = prevFrag.endProgramDateTime;
}
if (!Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(frag.programDateTime)) {
frag.programDateTime = null;
frag.rawProgramDateTime = null;
}
}
/***/ }),
/***/ "./src/loader/playlist-loader.ts":
/*!***************************************!*\
!*** ./src/loader/playlist-loader.ts ***!
\***************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/mp4-tools */ "./src/utils/mp4-tools.ts");
/* harmony import */ var _m3u8_parser__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./m3u8-parser */ "./src/loader/m3u8-parser.ts");
/* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts");
/* harmony import */ var _utils_attr_list__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../utils/attr-list */ "./src/utils/attr-list.ts");
/**
* PlaylistLoader - delegate for media manifest/playlist loading tasks. Takes care of parsing media to internal data-models.
*
* Once loaded, dispatches events with parsed data-models of manifest/levels/audio/subtitle tracks.
*
* Uses loader(s) set in config to do actual internal loading of resource tasks.
*
* @module
*
*/
function mapContextToLevelType(context) {
var type = context.type;
switch (type) {
case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].AUDIO_TRACK:
return _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].AUDIO;
case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].SUBTITLE_TRACK:
return _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].SUBTITLE;
default:
return _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN;
}
}
function getResponseUrl(response, context) {
var url = response.url; // responseURL not supported on some browsers (it is used to detect URL redirection)
// data-uri mode also not supported (but no need to detect redirection)
if (url === undefined || url.indexOf('data:') === 0) {
// fallback to initial URL
url = context.url;
}
return url;
}
var PlaylistLoader = /*#__PURE__*/function () {
function PlaylistLoader(hls) {
this.hls = void 0;
this.loaders = Object.create(null);
this.hls = hls;
this.registerListeners();
}
var _proto = PlaylistLoader.prototype;
_proto.registerListeners = function registerListeners() {
var hls = this.hls;
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADING, this.onManifestLoading, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_LOADING, this.onLevelLoading, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].AUDIO_TRACK_LOADING, this.onAudioTrackLoading, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_TRACK_LOADING, this.onSubtitleTrackLoading, this);
};
_proto.unregisterListeners = function unregisterListeners() {
var hls = this.hls;
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADING, this.onManifestLoading, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_LOADING, this.onLevelLoading, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].AUDIO_TRACK_LOADING, this.onAudioTrackLoading, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_TRACK_LOADING, this.onSubtitleTrackLoading, this);
}
/**
* Returns defaults or configured loader-type overloads (pLoader and loader config params)
*/
;
_proto.createInternalLoader = function createInternalLoader(context) {
var config = this.hls.config;
var PLoader = config.pLoader;
var Loader = config.loader;
var InternalLoader = PLoader || Loader;
var loader = new InternalLoader(config);
context.loader = loader;
this.loaders[context.type] = loader;
return loader;
};
_proto.getInternalLoader = function getInternalLoader(context) {
return this.loaders[context.type];
};
_proto.resetInternalLoader = function resetInternalLoader(contextType) {
if (this.loaders[contextType]) {
delete this.loaders[contextType];
}
}
/**
* Call `destroy` on all internal loader instances mapped (one per context type)
*/
;
_proto.destroyInternalLoaders = function destroyInternalLoaders() {
for (var contextType in this.loaders) {
var loader = this.loaders[contextType];
if (loader) {
loader.destroy();
}
this.resetInternalLoader(contextType);
}
};
_proto.destroy = function destroy() {
this.unregisterListeners();
this.destroyInternalLoaders();
};
_proto.onManifestLoading = function onManifestLoading(event, data) {
var url = data.url;
this.load({
id: null,
groupId: null,
level: 0,
responseType: 'text',
type: _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].MANIFEST,
url: url,
deliveryDirectives: null
});
};
_proto.onLevelLoading = function onLevelLoading(event, data) {
var id = data.id,
level = data.level,
url = data.url,
deliveryDirectives = data.deliveryDirectives;
this.load({
id: id,
groupId: null,
level: level,
responseType: 'text',
type: _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].LEVEL,
url: url,
deliveryDirectives: deliveryDirectives
});
};
_proto.onAudioTrackLoading = function onAudioTrackLoading(event, data) {
var id = data.id,
groupId = data.groupId,
url = data.url,
deliveryDirectives = data.deliveryDirectives;
this.load({
id: id,
groupId: groupId,
level: null,
responseType: 'text',
type: _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].AUDIO_TRACK,
url: url,
deliveryDirectives: deliveryDirectives
});
};
_proto.onSubtitleTrackLoading = function onSubtitleTrackLoading(event, data) {
var id = data.id,
groupId = data.groupId,
url = data.url,
deliveryDirectives = data.deliveryDirectives;
this.load({
id: id,
groupId: groupId,
level: null,
responseType: 'text',
type: _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].SUBTITLE_TRACK,
url: url,
deliveryDirectives: deliveryDirectives
});
};
_proto.load = function load(context) {
var _context$deliveryDire;
var config = this.hls.config; // logger.debug(`[playlist-loader]: Loading playlist of type ${context.type}, level: ${context.level}, id: ${context.id}`);
// Check if a loader for this context already exists
var loader = this.getInternalLoader(context);
if (loader) {
var loaderContext = loader.context;
if (loaderContext && loaderContext.url === context.url) {
// same URL can't overlap
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].trace('[playlist-loader]: playlist request ongoing');
return;
}
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].log("[playlist-loader]: aborting previous loader for type: " + context.type);
loader.abort();
}
var maxRetry;
var timeout;
var retryDelay;
var maxRetryDelay; // apply different configs for retries depending on
// context (manifest, level, audio/subs playlist)
switch (context.type) {
case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].MANIFEST:
maxRetry = config.manifestLoadingMaxRetry;
timeout = config.manifestLoadingTimeOut;
retryDelay = config.manifestLoadingRetryDelay;
maxRetryDelay = config.manifestLoadingMaxRetryTimeout;
break;
case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].LEVEL:
case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].AUDIO_TRACK:
case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].SUBTITLE_TRACK:
// Manage retries in Level/Track Controller
maxRetry = 0;
timeout = config.levelLoadingTimeOut;
break;
default:
maxRetry = config.levelLoadingMaxRetry;
timeout = config.levelLoadingTimeOut;
retryDelay = config.levelLoadingRetryDelay;
maxRetryDelay = config.levelLoadingMaxRetryTimeout;
break;
}
loader = this.createInternalLoader(context); // Override level/track timeout for LL-HLS requests
// (the default of 10000ms is counter productive to blocking playlist reload requests)
if ((_context$deliveryDire = context.deliveryDirectives) !== null && _context$deliveryDire !== void 0 && _context$deliveryDire.part) {
var levelDetails;
if (context.type === _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].LEVEL && context.level !== null) {
levelDetails = this.hls.levels[context.level].details;
} else if (context.type === _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].AUDIO_TRACK && context.id !== null) {
levelDetails = this.hls.audioTracks[context.id].details;
} else if (context.type === _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].SUBTITLE_TRACK && context.id !== null) {
levelDetails = this.hls.subtitleTracks[context.id].details;
}
if (levelDetails) {
var partTarget = levelDetails.partTarget;
var targetDuration = levelDetails.targetduration;
if (partTarget && targetDuration) {
timeout = Math.min(Math.max(partTarget * 3, targetDuration * 0.8) * 1000, timeout);
}
}
}
var loaderConfig = {
timeout: timeout,
maxRetry: maxRetry,
retryDelay: retryDelay,
maxRetryDelay: maxRetryDelay,
highWaterMark: 0
};
var loaderCallbacks = {
onSuccess: this.loadsuccess.bind(this),
onError: this.loaderror.bind(this),
onTimeout: this.loadtimeout.bind(this)
}; // logger.debug(`[playlist-loader]: Calling internal loader delegate for URL: ${context.url}`);
loader.load(context, loaderConfig, loaderCallbacks);
};
_proto.loadsuccess = function loadsuccess(response, stats, context, networkDetails) {
if (networkDetails === void 0) {
networkDetails = null;
}
if (context.isSidxRequest) {
this.handleSidxRequest(response, context);
this.handlePlaylistLoaded(response, stats, context, networkDetails);
return;
}
this.resetInternalLoader(context.type);
var string = response.data; // Validate if it is an M3U8 at all
if (string.indexOf('#EXTM3U') !== 0) {
this.handleManifestParsingError(response, context, 'no EXTM3U delimiter', networkDetails);
return;
}
stats.parsing.start = performance.now(); // Check if chunk-list or master. handle empty chunk list case (first EXTINF not signaled, but TARGETDURATION present)
if (string.indexOf('#EXTINF:') > 0 || string.indexOf('#EXT-X-TARGETDURATION:') > 0) {
this.handleTrackOrLevelPlaylist(response, stats, context, networkDetails);
} else {
this.handleMasterPlaylist(response, stats, context, networkDetails);
}
};
_proto.loaderror = function loaderror(response, context, networkDetails) {
if (networkDetails === void 0) {
networkDetails = null;
}
this.handleNetworkError(context, networkDetails, false, response);
};
_proto.loadtimeout = function loadtimeout(stats, context, networkDetails) {
if (networkDetails === void 0) {
networkDetails = null;
}
this.handleNetworkError(context, networkDetails, true);
};
_proto.handleMasterPlaylist = function handleMasterPlaylist(response, stats, context, networkDetails) {
var hls = this.hls;
var string = response.data;
var url = getResponseUrl(response, context);
var _M3U8Parser$parseMast = _m3u8_parser__WEBPACK_IMPORTED_MODULE_5__["default"].parseMasterPlaylist(string, url),
levels = _M3U8Parser$parseMast.levels,
sessionData = _M3U8Parser$parseMast.sessionData;
if (!levels.length) {
this.handleManifestParsingError(response, context, 'no level found in manifest', networkDetails);
return;
} // multi level playlist, parse level info
var audioGroups = levels.map(function (level) {
return {
id: level.attrs.AUDIO,
audioCodec: level.audioCodec
};
});
var subtitleGroups = levels.map(function (level) {
return {
id: level.attrs.SUBTITLES,
textCodec: level.textCodec
};
});
var audioTracks = _m3u8_parser__WEBPACK_IMPORTED_MODULE_5__["default"].parseMasterPlaylistMedia(string, url, 'AUDIO', audioGroups);
var subtitles = _m3u8_parser__WEBPACK_IMPORTED_MODULE_5__["default"].parseMasterPlaylistMedia(string, url, 'SUBTITLES', subtitleGroups);
var captions = _m3u8_parser__WEBPACK_IMPORTED_MODULE_5__["default"].parseMasterPlaylistMedia(string, url, 'CLOSED-CAPTIONS');
if (audioTracks.length) {
// check if we have found an audio track embedded in main playlist (audio track without URI attribute)
var embeddedAudioFound = audioTracks.some(function (audioTrack) {
return !audioTrack.url;
}); // if no embedded audio track defined, but audio codec signaled in quality level,
// we need to signal this main audio track this could happen with playlists with
// alt audio rendition in which quality levels (main)
// contains both audio+video. but with mixed audio track not signaled
if (!embeddedAudioFound && levels[0].audioCodec && !levels[0].attrs.AUDIO) {
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].log('[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one');
audioTracks.unshift({
type: 'main',
name: 'main',
default: false,
autoselect: false,
forced: false,
id: -1,
attrs: new _utils_attr_list__WEBPACK_IMPORTED_MODULE_7__["AttrList"]({}),
bitrate: 0,
url: ''
});
}
}
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADED, {
levels: levels,
audioTracks: audioTracks,
subtitles: subtitles,
captions: captions,
url: url,
stats: stats,
networkDetails: networkDetails,
sessionData: sessionData
});
};
_proto.handleTrackOrLevelPlaylist = function handleTrackOrLevelPlaylist(response, stats, context, networkDetails) {
var hls = this.hls;
var id = context.id,
level = context.level,
type = context.type;
var url = getResponseUrl(response, context);
var levelUrlId = Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(id) ? id : 0;
var levelId = Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(level) ? level : levelUrlId;
var levelType = mapContextToLevelType(context);
var levelDetails = _m3u8_parser__WEBPACK_IMPORTED_MODULE_5__["default"].parseLevelPlaylist(response.data, url, levelId, levelType, levelUrlId);
if (!levelDetails.fragments.length) {
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorTypes"].NETWORK_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].LEVEL_EMPTY_ERROR,
fatal: false,
url: url,
reason: 'no fragments found in level',
level: typeof context.level === 'number' ? context.level : undefined
});
return;
} // We have done our first request (Manifest-type) and receive
// not a master playlist but a chunk-list (track/level)
// We fire the manifest-loaded event anyway with the parsed level-details
// by creating a single-level structure for it.
if (type === _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].MANIFEST) {
var singleLevel = {
attrs: new _utils_attr_list__WEBPACK_IMPORTED_MODULE_7__["AttrList"]({}),
bitrate: 0,
details: levelDetails,
name: '',
url: url
};
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADED, {
levels: [singleLevel],
audioTracks: [],
url: url,
stats: stats,
networkDetails: networkDetails,
sessionData: null
});
} // save parsing time
stats.parsing.end = performance.now(); // in case we need SIDX ranges
// return early after calling load for
// the SIDX box.
if (levelDetails.needSidxRanges) {
var _levelDetails$fragmen;
var sidxUrl = (_levelDetails$fragmen = levelDetails.fragments[0].initSegment) === null || _levelDetails$fragmen === void 0 ? void 0 : _levelDetails$fragmen.url;
this.load({
url: sidxUrl,
isSidxRequest: true,
type: type,
level: level,
levelDetails: levelDetails,
id: id,
groupId: null,
rangeStart: 0,
rangeEnd: 2048,
responseType: 'arraybuffer',
deliveryDirectives: null
});
return;
} // extend the context with the new levelDetails property
context.levelDetails = levelDetails;
this.handlePlaylistLoaded(response, stats, context, networkDetails);
};
_proto.handleSidxRequest = function handleSidxRequest(response, context) {
var sidxInfo = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_4__["parseSegmentIndex"])(new Uint8Array(response.data)); // if provided fragment does not contain sidx, early return
if (!sidxInfo) {
return;
}
var sidxReferences = sidxInfo.references;
var levelDetails = context.levelDetails;
sidxReferences.forEach(function (segmentRef, index) {
var segRefInfo = segmentRef.info;
var frag = levelDetails.fragments[index];
if (frag.byteRange.length === 0) {
frag.setByteRange(String(1 + segRefInfo.end - segRefInfo.start) + '@' + String(segRefInfo.start));
}
if (frag.initSegment) {
frag.initSegment.setByteRange(String(sidxInfo.moovEndOffset) + '@0');
}
});
};
_proto.handleManifestParsingError = function handleManifestParsingError(response, context, reason, networkDetails) {
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorTypes"].NETWORK_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].MANIFEST_PARSING_ERROR,
fatal: context.type === _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].MANIFEST,
url: response.url,
reason: reason,
response: response,
context: context,
networkDetails: networkDetails
});
};
_proto.handleNetworkError = function handleNetworkError(context, networkDetails, timeout, response) {
if (timeout === void 0) {
timeout = false;
}
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn("[playlist-loader]: A network " + (timeout ? 'timeout' : 'error') + " occurred while loading " + context.type + " level: " + context.level + " id: " + context.id + " group-id: \"" + context.groupId + "\"");
var details = _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].UNKNOWN;
var fatal = false;
var loader = this.getInternalLoader(context);
switch (context.type) {
case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].MANIFEST:
details = timeout ? _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].MANIFEST_LOAD_TIMEOUT : _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].MANIFEST_LOAD_ERROR;
fatal = true;
break;
case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].LEVEL:
details = timeout ? _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].LEVEL_LOAD_TIMEOUT : _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].LEVEL_LOAD_ERROR;
fatal = false;
break;
case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].AUDIO_TRACK:
details = timeout ? _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].AUDIO_TRACK_LOAD_TIMEOUT : _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].AUDIO_TRACK_LOAD_ERROR;
fatal = false;
break;
case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].SUBTITLE_TRACK:
details = timeout ? _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].SUBTITLE_TRACK_LOAD_TIMEOUT : _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].SUBTITLE_LOAD_ERROR;
fatal = false;
break;
}
if (loader) {
this.resetInternalLoader(context.type);
}
var errorData = {
type: _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorTypes"].NETWORK_ERROR,
details: details,
fatal: fatal,
url: context.url,
loader: loader,
context: context,
networkDetails: networkDetails
};
if (response) {
errorData.response = response;
}
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, errorData);
};
_proto.handlePlaylistLoaded = function handlePlaylistLoaded(response, stats, context, networkDetails) {
var type = context.type,
level = context.level,
id = context.id,
groupId = context.groupId,
loader = context.loader,
levelDetails = context.levelDetails,
deliveryDirectives = context.deliveryDirectives;
if (!(levelDetails !== null && levelDetails !== void 0 && levelDetails.targetduration)) {
this.handleManifestParsingError(response, context, 'invalid target duration', networkDetails);
return;
}
if (!loader) {
return;
}
if (levelDetails.live) {
if (loader.getCacheAge) {
levelDetails.ageHeader = loader.getCacheAge() || 0;
}
if (!loader.getCacheAge || isNaN(levelDetails.ageHeader)) {
levelDetails.ageHeader = 0;
}
}
switch (type) {
case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].MANIFEST:
case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].LEVEL:
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_LOADED, {
details: levelDetails,
level: level || 0,
id: id || 0,
stats: stats,
networkDetails: networkDetails,
deliveryDirectives: deliveryDirectives
});
break;
case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].AUDIO_TRACK:
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].AUDIO_TRACK_LOADED, {
details: levelDetails,
id: id || 0,
groupId: groupId || '',
stats: stats,
networkDetails: networkDetails,
deliveryDirectives: deliveryDirectives
});
break;
case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].SUBTITLE_TRACK:
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_TRACK_LOADED, {
details: levelDetails,
id: id || 0,
groupId: groupId || '',
stats: stats,
networkDetails: networkDetails,
deliveryDirectives: deliveryDirectives
});
break;
}
};
return PlaylistLoader;
}();
/* harmony default export */ __webpack_exports__["default"] = (PlaylistLoader);
/***/ }),
/***/ "./src/polyfills/number.ts":
/*!*********************************!*\
!*** ./src/polyfills/number.ts ***!
\*********************************/
/*! exports provided: isFiniteNumber, MAX_SAFE_INTEGER */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isFiniteNumber", function() { return isFiniteNumber; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MAX_SAFE_INTEGER", function() { return MAX_SAFE_INTEGER; });
var isFiniteNumber = Number.isFinite || function (value) {
return typeof value === 'number' && isFinite(value);
};
var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991;
/***/ }),
/***/ "./src/remux/aac-helper.ts":
/*!*********************************!*\
!*** ./src/remux/aac-helper.ts ***!
\*********************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/**
* AAC helper
*/
var AAC = /*#__PURE__*/function () {
function AAC() {}
AAC.getSilentFrame = function getSilentFrame(codec, channelCount) {
switch (codec) {
case 'mp4a.40.2':
if (channelCount === 1) {
return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x23, 0x80]);
} else if (channelCount === 2) {
return new Uint8Array([0x21, 0x00, 0x49, 0x90, 0x02, 0x19, 0x00, 0x23, 0x80]);
} else if (channelCount === 3) {
return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x8e]);
} else if (channelCount === 4) {
return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x80, 0x2c, 0x80, 0x08, 0x02, 0x38]);
} else if (channelCount === 5) {
return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x38]);
} else if (channelCount === 6) {
return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x00, 0xb2, 0x00, 0x20, 0x08, 0xe0]);
}
break;
// handle HE-AAC below (mp4a.40.5 / mp4a.40.29)
default:
if (channelCount === 1) {
// ffmpeg -y -f lavfi -i "aevalsrc=0:d=0.05" -c:a libfdk_aac -profile:a aac_he -b:a 4k output.aac && hexdump -v -e '16/1 "0x%x," "\n"' -v output.aac
return new Uint8Array([0x1, 0x40, 0x22, 0x80, 0xa3, 0x4e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0, 0x0, 0x1c, 0x6, 0xf1, 0xc1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5e]);
} else if (channelCount === 2) {
// ffmpeg -y -f lavfi -i "aevalsrc=0|0:d=0.05" -c:a libfdk_aac -profile:a aac_he_v2 -b:a 4k output.aac && hexdump -v -e '16/1 "0x%x," "\n"' -v output.aac
return new Uint8Array([0x1, 0x40, 0x22, 0x80, 0xa3, 0x5e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0, 0x0, 0x0, 0x95, 0x0, 0x6, 0xf1, 0xa1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5e]);
} else if (channelCount === 3) {
// ffmpeg -y -f lavfi -i "aevalsrc=0|0|0:d=0.05" -c:a libfdk_aac -profile:a aac_he_v2 -b:a 4k output.aac && hexdump -v -e '16/1 "0x%x," "\n"' -v output.aac
return new Uint8Array([0x1, 0x40, 0x22, 0x80, 0xa3, 0x5e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0, 0x0, 0x0, 0x95, 0x0, 0x6, 0xf1, 0xa1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5e]);
}
break;
}
return undefined;
};
return AAC;
}();
/* harmony default export */ __webpack_exports__["default"] = (AAC);
/***/ }),
/***/ "./src/remux/mp4-generator.ts":
/*!************************************!*\
!*** ./src/remux/mp4-generator.ts ***!
\************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/**
* Generate MP4 Box
*/
var UINT32_MAX = Math.pow(2, 32) - 1;
var MP4 = /*#__PURE__*/function () {
function MP4() {}
MP4.init = function init() {
MP4.types = {
avc1: [],
// codingname
avcC: [],
btrt: [],
dinf: [],
dref: [],
esds: [],
ftyp: [],
hdlr: [],
mdat: [],
mdhd: [],
mdia: [],
mfhd: [],
minf: [],
moof: [],
moov: [],
mp4a: [],
'.mp3': [],
mvex: [],
mvhd: [],
pasp: [],
sdtp: [],
stbl: [],
stco: [],
stsc: [],
stsd: [],
stsz: [],
stts: [],
tfdt: [],
tfhd: [],
traf: [],
trak: [],
trun: [],
trex: [],
tkhd: [],
vmhd: [],
smhd: []
};
var i;
for (i in MP4.types) {
if (MP4.types.hasOwnProperty(i)) {
MP4.types[i] = [i.charCodeAt(0), i.charCodeAt(1), i.charCodeAt(2), i.charCodeAt(3)];
}
}
var videoHdlr = new Uint8Array([0x00, // version 0
0x00, 0x00, 0x00, // flags
0x00, 0x00, 0x00, 0x00, // pre_defined
0x76, 0x69, 0x64, 0x65, // handler_type: 'vide'
0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x00, 0x00, 0x00, // reserved
0x56, 0x69, 0x64, 0x65, 0x6f, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'VideoHandler'
]);
var audioHdlr = new Uint8Array([0x00, // version 0
0x00, 0x00, 0x00, // flags
0x00, 0x00, 0x00, 0x00, // pre_defined
0x73, 0x6f, 0x75, 0x6e, // handler_type: 'soun'
0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x00, 0x00, 0x00, // reserved
0x53, 0x6f, 0x75, 0x6e, 0x64, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'SoundHandler'
]);
MP4.HDLR_TYPES = {
video: videoHdlr,
audio: audioHdlr
};
var dref = new Uint8Array([0x00, // version 0
0x00, 0x00, 0x00, // flags
0x00, 0x00, 0x00, 0x01, // entry_count
0x00, 0x00, 0x00, 0x0c, // entry_size
0x75, 0x72, 0x6c, 0x20, // 'url' type
0x00, // version 0
0x00, 0x00, 0x01 // entry_flags
]);
var stco = new Uint8Array([0x00, // version
0x00, 0x00, 0x00, // flags
0x00, 0x00, 0x00, 0x00 // entry_count
]);
MP4.STTS = MP4.STSC = MP4.STCO = stco;
MP4.STSZ = new Uint8Array([0x00, // version
0x00, 0x00, 0x00, // flags
0x00, 0x00, 0x00, 0x00, // sample_size
0x00, 0x00, 0x00, 0x00 // sample_count
]);
MP4.VMHD = new Uint8Array([0x00, // version
0x00, 0x00, 0x01, // flags
0x00, 0x00, // graphicsmode
0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // opcolor
]);
MP4.SMHD = new Uint8Array([0x00, // version
0x00, 0x00, 0x00, // flags
0x00, 0x00, // balance
0x00, 0x00 // reserved
]);
MP4.STSD = new Uint8Array([0x00, // version 0
0x00, 0x00, 0x00, // flags
0x00, 0x00, 0x00, 0x01]); // entry_count
var majorBrand = new Uint8Array([105, 115, 111, 109]); // isom
var avc1Brand = new Uint8Array([97, 118, 99, 49]); // avc1
var minorVersion = new Uint8Array([0, 0, 0, 1]);
MP4.FTYP = MP4.box(MP4.types.ftyp, majorBrand, minorVersion, majorBrand, avc1Brand);
MP4.DINF = MP4.box(MP4.types.dinf, MP4.box(MP4.types.dref, dref));
};
MP4.box = function box(type) {
var size = 8;
for (var _len = arguments.length, payload = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
payload[_key - 1] = arguments[_key];
}
var i = payload.length;
var len = i; // calculate the total size we need to allocate
while (i--) {
size += payload[i].byteLength;
}
var result = new Uint8Array(size);
result[0] = size >> 24 & 0xff;
result[1] = size >> 16 & 0xff;
result[2] = size >> 8 & 0xff;
result[3] = size & 0xff;
result.set(type, 4); // copy the payload into the result
for (i = 0, size = 8; i < len; i++) {
// copy payload[i] array @ offset size
result.set(payload[i], size);
size += payload[i].byteLength;
}
return result;
};
MP4.hdlr = function hdlr(type) {
return MP4.box(MP4.types.hdlr, MP4.HDLR_TYPES[type]);
};
MP4.mdat = function mdat(data) {
return MP4.box(MP4.types.mdat, data);
};
MP4.mdhd = function mdhd(timescale, duration) {
duration *= timescale;
var upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
var lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
return MP4.box(MP4.types.mdhd, new Uint8Array([0x01, // version 1
0x00, 0x00, 0x00, // flags
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, // creation_time
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, // modification_time
timescale >> 24 & 0xff, timescale >> 16 & 0xff, timescale >> 8 & 0xff, timescale & 0xff, // timescale
upperWordDuration >> 24, upperWordDuration >> 16 & 0xff, upperWordDuration >> 8 & 0xff, upperWordDuration & 0xff, lowerWordDuration >> 24, lowerWordDuration >> 16 & 0xff, lowerWordDuration >> 8 & 0xff, lowerWordDuration & 0xff, 0x55, 0xc4, // 'und' language (undetermined)
0x00, 0x00]));
};
MP4.mdia = function mdia(track) {
return MP4.box(MP4.types.mdia, MP4.mdhd(track.timescale, track.duration), MP4.hdlr(track.type), MP4.minf(track));
};
MP4.mfhd = function mfhd(sequenceNumber) {
return MP4.box(MP4.types.mfhd, new Uint8Array([0x00, 0x00, 0x00, 0x00, // flags
sequenceNumber >> 24, sequenceNumber >> 16 & 0xff, sequenceNumber >> 8 & 0xff, sequenceNumber & 0xff // sequence_number
]));
};
MP4.minf = function minf(track) {
if (track.type === 'audio') {
return MP4.box(MP4.types.minf, MP4.box(MP4.types.smhd, MP4.SMHD), MP4.DINF, MP4.stbl(track));
} else {
return MP4.box(MP4.types.minf, MP4.box(MP4.types.vmhd, MP4.VMHD), MP4.DINF, MP4.stbl(track));
}
};
MP4.moof = function moof(sn, baseMediaDecodeTime, track) {
return MP4.box(MP4.types.moof, MP4.mfhd(sn), MP4.traf(track, baseMediaDecodeTime));
}
/**
* @param tracks... (optional) {array} the tracks associated with this movie
*/
;
MP4.moov = function moov(tracks) {
var i = tracks.length;
var boxes = [];
while (i--) {
boxes[i] = MP4.trak(tracks[i]);
}
return MP4.box.apply(null, [MP4.types.moov, MP4.mvhd(tracks[0].timescale, tracks[0].duration)].concat(boxes).concat(MP4.mvex(tracks)));
};
MP4.mvex = function mvex(tracks) {
var i = tracks.length;
var boxes = [];
while (i--) {
boxes[i] = MP4.trex(tracks[i]);
}
return MP4.box.apply(null, [MP4.types.mvex].concat(boxes));
};
MP4.mvhd = function mvhd(timescale, duration) {
duration *= timescale;
var upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
var lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
var bytes = new Uint8Array([0x01, // version 1
0x00, 0x00, 0x00, // flags
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, // creation_time
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, // modification_time
timescale >> 24 & 0xff, timescale >> 16 & 0xff, timescale >> 8 & 0xff, timescale & 0xff, // timescale
upperWordDuration >> 24, upperWordDuration >> 16 & 0xff, upperWordDuration >> 8 & 0xff, upperWordDuration & 0xff, lowerWordDuration >> 24, lowerWordDuration >> 16 & 0xff, lowerWordDuration >> 8 & 0xff, lowerWordDuration & 0xff, 0x00, 0x01, 0x00, 0x00, // 1.0 rate
0x01, 0x00, // 1.0 volume
0x00, 0x00, // reserved
0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, // transformation: unity matrix
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pre_defined
0xff, 0xff, 0xff, 0xff // next_track_ID
]);
return MP4.box(MP4.types.mvhd, bytes);
};
MP4.sdtp = function sdtp(track) {
var samples = track.samples || [];
var bytes = new Uint8Array(4 + samples.length);
var i;
var flags; // leave the full box header (4 bytes) all zero
// write the sample table
for (i = 0; i < samples.length; i++) {
flags = samples[i].flags;
bytes[i + 4] = flags.dependsOn << 4 | flags.isDependedOn << 2 | flags.hasRedundancy;
}
return MP4.box(MP4.types.sdtp, bytes);
};
MP4.stbl = function stbl(track) {
return MP4.box(MP4.types.stbl, MP4.stsd(track), MP4.box(MP4.types.stts, MP4.STTS), MP4.box(MP4.types.stsc, MP4.STSC), MP4.box(MP4.types.stsz, MP4.STSZ), MP4.box(MP4.types.stco, MP4.STCO));
};
MP4.avc1 = function avc1(track) {
var sps = [];
var pps = [];
var i;
var data;
var len; // assemble the SPSs
for (i = 0; i < track.sps.length; i++) {
data = track.sps[i];
len = data.byteLength;
sps.push(len >>> 8 & 0xff);
sps.push(len & 0xff); // SPS
sps = sps.concat(Array.prototype.slice.call(data));
} // assemble the PPSs
for (i = 0; i < track.pps.length; i++) {
data = track.pps[i];
len = data.byteLength;
pps.push(len >>> 8 & 0xff);
pps.push(len & 0xff);
pps = pps.concat(Array.prototype.slice.call(data));
}
var avcc = MP4.box(MP4.types.avcC, new Uint8Array([0x01, // version
sps[3], // profile
sps[4], // profile compat
sps[5], // level
0xfc | 3, // lengthSizeMinusOne, hard-coded to 4 bytes
0xe0 | track.sps.length // 3bit reserved (111) + numOfSequenceParameterSets
].concat(sps).concat([track.pps.length // numOfPictureParameterSets
]).concat(pps))); // "PPS"
var width = track.width;
var height = track.height;
var hSpacing = track.pixelRatio[0];
var vSpacing = track.pixelRatio[1];
return MP4.box(MP4.types.avc1, new Uint8Array([0x00, 0x00, 0x00, // reserved
0x00, 0x00, 0x00, // reserved
0x00, 0x01, // data_reference_index
0x00, 0x00, // pre_defined
0x00, 0x00, // reserved
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pre_defined
width >> 8 & 0xff, width & 0xff, // width
height >> 8 & 0xff, height & 0xff, // height
0x00, 0x48, 0x00, 0x00, // horizresolution
0x00, 0x48, 0x00, 0x00, // vertresolution
0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x01, // frame_count
0x12, 0x64, 0x61, 0x69, 0x6c, // dailymotion/hls.js
0x79, 0x6d, 0x6f, 0x74, 0x69, 0x6f, 0x6e, 0x2f, 0x68, 0x6c, 0x73, 0x2e, 0x6a, 0x73, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // compressorname
0x00, 0x18, // depth = 24
0x11, 0x11]), // pre_defined = -1
avcc, MP4.box(MP4.types.btrt, new Uint8Array([0x00, 0x1c, 0x9c, 0x80, // bufferSizeDB
0x00, 0x2d, 0xc6, 0xc0, // maxBitrate
0x00, 0x2d, 0xc6, 0xc0])), // avgBitrate
MP4.box(MP4.types.pasp, new Uint8Array([hSpacing >> 24, // hSpacing
hSpacing >> 16 & 0xff, hSpacing >> 8 & 0xff, hSpacing & 0xff, vSpacing >> 24, // vSpacing
vSpacing >> 16 & 0xff, vSpacing >> 8 & 0xff, vSpacing & 0xff])));
};
MP4.esds = function esds(track) {
var configlen = track.config.length;
return new Uint8Array([0x00, // version 0
0x00, 0x00, 0x00, // flags
0x03, // descriptor_type
0x17 + configlen, // length
0x00, 0x01, // es_id
0x00, // stream_priority
0x04, // descriptor_type
0x0f + configlen, // length
0x40, // codec : mpeg4_audio
0x15, // stream_type
0x00, 0x00, 0x00, // buffer_size
0x00, 0x00, 0x00, 0x00, // maxBitrate
0x00, 0x00, 0x00, 0x00, // avgBitrate
0x05 // descriptor_type
].concat([configlen]).concat(track.config).concat([0x06, 0x01, 0x02])); // GASpecificConfig)); // length + audio config descriptor
};
MP4.mp4a = function mp4a(track) {
var samplerate = track.samplerate;
return MP4.box(MP4.types.mp4a, new Uint8Array([0x00, 0x00, 0x00, // reserved
0x00, 0x00, 0x00, // reserved
0x00, 0x01, // data_reference_index
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
0x00, track.channelCount, // channelcount
0x00, 0x10, // sampleSize:16bits
0x00, 0x00, 0x00, 0x00, // reserved2
samplerate >> 8 & 0xff, samplerate & 0xff, //
0x00, 0x00]), MP4.box(MP4.types.esds, MP4.esds(track)));
};
MP4.mp3 = function mp3(track) {
var samplerate = track.samplerate;
return MP4.box(MP4.types['.mp3'], new Uint8Array([0x00, 0x00, 0x00, // reserved
0x00, 0x00, 0x00, // reserved
0x00, 0x01, // data_reference_index
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
0x00, track.channelCount, // channelcount
0x00, 0x10, // sampleSize:16bits
0x00, 0x00, 0x00, 0x00, // reserved2
samplerate >> 8 & 0xff, samplerate & 0xff, //
0x00, 0x00]));
};
MP4.stsd = function stsd(track) {
if (track.type === 'audio') {
if (!track.isAAC && track.codec === 'mp3') {
return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp3(track));
}
return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp4a(track));
} else {
return MP4.box(MP4.types.stsd, MP4.STSD, MP4.avc1(track));
}
};
MP4.tkhd = function tkhd(track) {
var id = track.id;
var duration = track.duration * track.timescale;
var width = track.width;
var height = track.height;
var upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
var lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
return MP4.box(MP4.types.tkhd, new Uint8Array([0x01, // version 1
0x00, 0x00, 0x07, // flags
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, // creation_time
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, // modification_time
id >> 24 & 0xff, id >> 16 & 0xff, id >> 8 & 0xff, id & 0xff, // track_ID
0x00, 0x00, 0x00, 0x00, // reserved
upperWordDuration >> 24, upperWordDuration >> 16 & 0xff, upperWordDuration >> 8 & 0xff, upperWordDuration & 0xff, lowerWordDuration >> 24, lowerWordDuration >> 16 & 0xff, lowerWordDuration >> 8 & 0xff, lowerWordDuration & 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x00, // layer
0x00, 0x00, // alternate_group
0x00, 0x00, // non-audio track volume
0x00, 0x00, // reserved
0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, // transformation: unity matrix
width >> 8 & 0xff, width & 0xff, 0x00, 0x00, // width
height >> 8 & 0xff, height & 0xff, 0x00, 0x00 // height
]));
};
MP4.traf = function traf(track, baseMediaDecodeTime) {
var sampleDependencyTable = MP4.sdtp(track);
var id = track.id;
var upperWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1));
var lowerWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1));
return MP4.box(MP4.types.traf, MP4.box(MP4.types.tfhd, new Uint8Array([0x00, // version 0
0x00, 0x00, 0x00, // flags
id >> 24, id >> 16 & 0xff, id >> 8 & 0xff, id & 0xff // track_ID
])), MP4.box(MP4.types.tfdt, new Uint8Array([0x01, // version 1
0x00, 0x00, 0x00, // flags
upperWordBaseMediaDecodeTime >> 24, upperWordBaseMediaDecodeTime >> 16 & 0xff, upperWordBaseMediaDecodeTime >> 8 & 0xff, upperWordBaseMediaDecodeTime & 0xff, lowerWordBaseMediaDecodeTime >> 24, lowerWordBaseMediaDecodeTime >> 16 & 0xff, lowerWordBaseMediaDecodeTime >> 8 & 0xff, lowerWordBaseMediaDecodeTime & 0xff])), MP4.trun(track, sampleDependencyTable.length + 16 + // tfhd
20 + // tfdt
8 + // traf header
16 + // mfhd
8 + // moof header
8), // mdat header
sampleDependencyTable);
}
/**
* Generate a track box.
* @param track {object} a track definition
* @return {Uint8Array} the track box
*/
;
MP4.trak = function trak(track) {
track.duration = track.duration || 0xffffffff;
return MP4.box(MP4.types.trak, MP4.tkhd(track), MP4.mdia(track));
};
MP4.trex = function trex(track) {
var id = track.id;
return MP4.box(MP4.types.trex, new Uint8Array([0x00, // version 0
0x00, 0x00, 0x00, // flags
id >> 24, id >> 16 & 0xff, id >> 8 & 0xff, id & 0xff, // track_ID
0x00, 0x00, 0x00, 0x01, // default_sample_description_index
0x00, 0x00, 0x00, 0x00, // default_sample_duration
0x00, 0x00, 0x00, 0x00, // default_sample_size
0x00, 0x01, 0x00, 0x01 // default_sample_flags
]));
};
MP4.trun = function trun(track, offset) {
var samples = track.samples || [];
var len = samples.length;
var arraylen = 12 + 16 * len;
var array = new Uint8Array(arraylen);
var i;
var sample;
var duration;
var size;
var flags;
var cts;
offset += 8 + arraylen;
array.set([0x00, // version 0
0x00, 0x0f, 0x01, // flags
len >>> 24 & 0xff, len >>> 16 & 0xff, len >>> 8 & 0xff, len & 0xff, // sample_count
offset >>> 24 & 0xff, offset >>> 16 & 0xff, offset >>> 8 & 0xff, offset & 0xff // data_offset
], 0);
for (i = 0; i < len; i++) {
sample = samples[i];
duration = sample.duration;
size = sample.size;
flags = sample.flags;
cts = sample.cts;
array.set([duration >>> 24 & 0xff, duration >>> 16 & 0xff, duration >>> 8 & 0xff, duration & 0xff, // sample_duration
size >>> 24 & 0xff, size >>> 16 & 0xff, size >>> 8 & 0xff, size & 0xff, // sample_size
flags.isLeading << 2 | flags.dependsOn, flags.isDependedOn << 6 | flags.hasRedundancy << 4 | flags.paddingValue << 1 | flags.isNonSync, flags.degradPrio & 0xf0 << 8, flags.degradPrio & 0x0f, // sample_flags
cts >>> 24 & 0xff, cts >>> 16 & 0xff, cts >>> 8 & 0xff, cts & 0xff // sample_composition_time_offset
], 12 + 16 * i);
}
return MP4.box(MP4.types.trun, array);
};
MP4.initSegment = function initSegment(tracks) {
if (!MP4.types) {
MP4.init();
}
var movie = MP4.moov(tracks);
var result = new Uint8Array(MP4.FTYP.byteLength + movie.byteLength);
result.set(MP4.FTYP);
result.set(movie, MP4.FTYP.byteLength);
return result;
};
return MP4;
}();
MP4.types = void 0;
MP4.HDLR_TYPES = void 0;
MP4.STTS = void 0;
MP4.STSC = void 0;
MP4.STCO = void 0;
MP4.STSZ = void 0;
MP4.VMHD = void 0;
MP4.SMHD = void 0;
MP4.STSD = void 0;
MP4.FTYP = void 0;
MP4.DINF = void 0;
/* harmony default export */ __webpack_exports__["default"] = (MP4);
/***/ }),
/***/ "./src/remux/mp4-remuxer.ts":
/*!**********************************!*\
!*** ./src/remux/mp4-remuxer.ts ***!
\**********************************/
/*! exports provided: default, normalizePts */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return MP4Remuxer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "normalizePts", function() { return normalizePts; });
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var _aac_helper__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./aac-helper */ "./src/remux/aac-helper.ts");
/* harmony import */ var _mp4_generator__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./mp4-generator */ "./src/remux/mp4-generator.ts");
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts");
/* harmony import */ var _utils_timescale_conversion__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../utils/timescale-conversion */ "./src/utils/timescale-conversion.ts");
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
var MAX_SILENT_FRAME_DURATION = 10 * 1000; // 10 seconds
var AAC_SAMPLES_PER_FRAME = 1024;
var MPEG_AUDIO_SAMPLE_PER_FRAME = 1152;
var chromeVersion = null;
var safariWebkitVersion = null;
var requiresPositiveDts = false;
var MP4Remuxer = /*#__PURE__*/function () {
function MP4Remuxer(observer, config, typeSupported, vendor) {
if (vendor === void 0) {
vendor = '';
}
this.observer = void 0;
this.config = void 0;
this.typeSupported = void 0;
this.ISGenerated = false;
this._initPTS = void 0;
this._initDTS = void 0;
this.nextAvcDts = null;
this.nextAudioPts = null;
this.isAudioContiguous = false;
this.isVideoContiguous = false;
this.observer = observer;
this.config = config;
this.typeSupported = typeSupported;
this.ISGenerated = false;
if (chromeVersion === null) {
var userAgent = navigator.userAgent || '';
var result = userAgent.match(/Chrome\/(\d+)/i);
chromeVersion = result ? parseInt(result[1]) : 0;
}
if (safariWebkitVersion === null) {
var _result = navigator.userAgent.match(/Safari\/(\d+)/i);
safariWebkitVersion = _result ? parseInt(_result[1]) : 0;
}
requiresPositiveDts = !!chromeVersion && chromeVersion < 75 || !!safariWebkitVersion && safariWebkitVersion < 600;
}
var _proto = MP4Remuxer.prototype;
_proto.destroy = function destroy() {};
_proto.resetTimeStamp = function resetTimeStamp(defaultTimeStamp) {
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].log('[mp4-remuxer]: initPTS & initDTS reset');
this._initPTS = this._initDTS = defaultTimeStamp;
};
_proto.resetNextTimestamp = function resetNextTimestamp() {
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].log('[mp4-remuxer]: reset next timestamp');
this.isVideoContiguous = false;
this.isAudioContiguous = false;
};
_proto.resetInitSegment = function resetInitSegment() {
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].log('[mp4-remuxer]: ISGenerated flag reset');
this.ISGenerated = false;
};
_proto.getVideoStartPts = function getVideoStartPts(videoSamples) {
var rolloverDetected = false;
var startPTS = videoSamples.reduce(function (minPTS, sample) {
var delta = sample.pts - minPTS;
if (delta < -4294967296) {
// 2^32, see PTSNormalize for reasoning, but we're hitting a rollover here, and we don't want that to impact the timeOffset calculation
rolloverDetected = true;
return normalizePts(minPTS, sample.pts);
} else if (delta > 0) {
return minPTS;
} else {
return sample.pts;
}
}, videoSamples[0].pts);
if (rolloverDetected) {
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].debug('PTS rollover detected');
}
return startPTS;
};
_proto.remux = function remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, flush, playlistType) {
var video;
var audio;
var initSegment;
var text;
var id3;
var independent;
var audioTimeOffset = timeOffset;
var videoTimeOffset = timeOffset; // If we're remuxing audio and video progressively, wait until we've received enough samples for each track before proceeding.
// This is done to synchronize the audio and video streams. We know if the current segment will have samples if the "pid"
// parameter is greater than -1. The pid is set when the PMT is parsed, which contains the tracks list.
// However, if the initSegment has already been generated, or we've reached the end of a segment (flush),
// then we can remux one track without waiting for the other.
var hasAudio = audioTrack.pid > -1;
var hasVideo = videoTrack.pid > -1;
var length = videoTrack.samples.length;
var enoughAudioSamples = audioTrack.samples.length > 0;
var enoughVideoSamples = length > 1;
var canRemuxAvc = (!hasAudio || enoughAudioSamples) && (!hasVideo || enoughVideoSamples) || this.ISGenerated || flush;
if (canRemuxAvc) {
if (!this.ISGenerated) {
initSegment = this.generateIS(audioTrack, videoTrack, timeOffset);
}
var isVideoContiguous = this.isVideoContiguous;
var firstKeyFrameIndex = -1;
if (enoughVideoSamples) {
firstKeyFrameIndex = findKeyframeIndex(videoTrack.samples);
if (!isVideoContiguous && this.config.forceKeyFrameOnDiscontinuity) {
independent = true;
if (firstKeyFrameIndex > 0) {
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn("[mp4-remuxer]: Dropped " + firstKeyFrameIndex + " out of " + length + " video samples due to a missing keyframe");
var startPTS = this.getVideoStartPts(videoTrack.samples);
videoTrack.samples = videoTrack.samples.slice(firstKeyFrameIndex);
videoTrack.dropped += firstKeyFrameIndex;
videoTimeOffset += (videoTrack.samples[0].pts - startPTS) / (videoTrack.timescale || 90000);
} else if (firstKeyFrameIndex === -1) {
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn("[mp4-remuxer]: No keyframe found out of " + length + " video samples");
independent = false;
}
}
}
if (this.ISGenerated) {
if (enoughAudioSamples && enoughVideoSamples) {
// timeOffset is expected to be the offset of the first timestamp of this fragment (first DTS)
// if first audio DTS is not aligned with first video DTS then we need to take that into account
// when providing timeOffset to remuxAudio / remuxVideo. if we don't do that, there might be a permanent / small
// drift between audio and video streams
var _startPTS = this.getVideoStartPts(videoTrack.samples);
var tsDelta = normalizePts(audioTrack.samples[0].pts, _startPTS) - _startPTS;
var audiovideoTimestampDelta = tsDelta / videoTrack.inputTimeScale;
audioTimeOffset += Math.max(0, audiovideoTimestampDelta);
videoTimeOffset += Math.max(0, -audiovideoTimestampDelta);
} // Purposefully remuxing audio before video, so that remuxVideo can use nextAudioPts, which is calculated in remuxAudio.
if (enoughAudioSamples) {
// if initSegment was generated without audio samples, regenerate it again
if (!audioTrack.samplerate) {
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn('[mp4-remuxer]: regenerate InitSegment as audio detected');
initSegment = this.generateIS(audioTrack, videoTrack, timeOffset);
}
audio = this.remuxAudio(audioTrack, audioTimeOffset, this.isAudioContiguous, accurateTimeOffset, hasVideo || enoughVideoSamples || playlistType === _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].AUDIO ? videoTimeOffset : undefined);
if (enoughVideoSamples) {
var audioTrackLength = audio ? audio.endPTS - audio.startPTS : 0; // if initSegment was generated without video samples, regenerate it again
if (!videoTrack.inputTimeScale) {
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn('[mp4-remuxer]: regenerate InitSegment as video detected');
initSegment = this.generateIS(audioTrack, videoTrack, timeOffset);
}
video = this.remuxVideo(videoTrack, videoTimeOffset, isVideoContiguous, audioTrackLength);
}
} else if (enoughVideoSamples) {
video = this.remuxVideo(videoTrack, videoTimeOffset, isVideoContiguous, 0);
}
if (video) {
video.firstKeyFrame = firstKeyFrameIndex;
video.independent = firstKeyFrameIndex !== -1;
}
}
} // Allow ID3 and text to remux, even if more audio/video samples are required
if (this.ISGenerated) {
if (id3Track.samples.length) {
id3 = this.remuxID3(id3Track, timeOffset);
}
if (textTrack.samples.length) {
text = this.remuxText(textTrack, timeOffset);
}
}
return {
audio: audio,
video: video,
initSegment: initSegment,
independent: independent,
text: text,
id3: id3
};
};
_proto.generateIS = function generateIS(audioTrack, videoTrack, timeOffset) {
var audioSamples = audioTrack.samples;
var videoSamples = videoTrack.samples;
var typeSupported = this.typeSupported;
var tracks = {};
var computePTSDTS = !Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(this._initPTS);
var container = 'audio/mp4';
var initPTS;
var initDTS;
var timescale;
if (computePTSDTS) {
initPTS = initDTS = Infinity;
}
if (audioTrack.config && audioSamples.length) {
// let's use audio sampling rate as MP4 time scale.
// rationale is that there is a integer nb of audio frames per audio sample (1024 for AAC)
// using audio sampling rate here helps having an integer MP4 frame duration
// this avoids potential rounding issue and AV sync issue
audioTrack.timescale = audioTrack.samplerate;
if (!audioTrack.isAAC) {
if (typeSupported.mpeg) {
// Chrome and Safari
container = 'audio/mpeg';
audioTrack.codec = '';
} else if (typeSupported.mp3) {
// Firefox
audioTrack.codec = 'mp3';
}
}
tracks.audio = {
id: 'audio',
container: container,
codec: audioTrack.codec,
initSegment: !audioTrack.isAAC && typeSupported.mpeg ? new Uint8Array(0) : _mp4_generator__WEBPACK_IMPORTED_MODULE_2__["default"].initSegment([audioTrack]),
metadata: {
channelCount: audioTrack.channelCount
}
};
if (computePTSDTS) {
timescale = audioTrack.inputTimeScale; // remember first PTS of this demuxing context. for audio, PTS = DTS
initPTS = initDTS = audioSamples[0].pts - Math.round(timescale * timeOffset);
}
}
if (videoTrack.sps && videoTrack.pps && videoSamples.length) {
// let's use input time scale as MP4 video timescale
// we use input time scale straight away to avoid rounding issues on frame duration / cts computation
videoTrack.timescale = videoTrack.inputTimeScale;
tracks.video = {
id: 'main',
container: 'video/mp4',
codec: videoTrack.codec,
initSegment: _mp4_generator__WEBPACK_IMPORTED_MODULE_2__["default"].initSegment([videoTrack]),
metadata: {
width: videoTrack.width,
height: videoTrack.height
}
};
if (computePTSDTS) {
timescale = videoTrack.inputTimeScale;
var startPTS = this.getVideoStartPts(videoSamples);
var startOffset = Math.round(timescale * timeOffset);
initDTS = Math.min(initDTS, normalizePts(videoSamples[0].dts, startPTS) - startOffset);
initPTS = Math.min(initPTS, startPTS - startOffset);
}
}
if (Object.keys(tracks).length) {
this.ISGenerated = true;
if (computePTSDTS) {
this._initPTS = initPTS;
this._initDTS = initDTS;
}
return {
tracks: tracks,
initPTS: initPTS,
timescale: timescale
};
}
};
_proto.remuxVideo = function remuxVideo(track, timeOffset, contiguous, audioTrackLength) {
var timeScale = track.inputTimeScale;
var inputSamples = track.samples;
var outputSamples = [];
var nbSamples = inputSamples.length;
var initPTS = this._initPTS;
var nextAvcDts = this.nextAvcDts;
var offset = 8;
var mp4SampleDuration;
var firstDTS;
var lastDTS;
var minPTS = Number.POSITIVE_INFINITY;
var maxPTS = Number.NEGATIVE_INFINITY;
var ptsDtsShift = 0;
var sortSamples = false; // if parsed fragment is contiguous with last one, let's use last DTS value as reference
if (!contiguous || nextAvcDts === null) {
var pts = timeOffset * timeScale;
var cts = inputSamples[0].pts - normalizePts(inputSamples[0].dts, inputSamples[0].pts); // if not contiguous, let's use target timeOffset
nextAvcDts = pts - cts;
} // PTS is coded on 33bits, and can loop from -2^32 to 2^32
// PTSNormalize will make PTS/DTS value monotonic, we use last known DTS value as reference value
for (var i = 0; i < nbSamples; i++) {
var sample = inputSamples[i];
sample.pts = normalizePts(sample.pts - initPTS, nextAvcDts);
sample.dts = normalizePts(sample.dts - initPTS, nextAvcDts);
if (sample.dts > sample.pts) {
var PTS_DTS_SHIFT_TOLERANCE_90KHZ = 90000 * 0.2;
ptsDtsShift = Math.max(Math.min(ptsDtsShift, sample.pts - sample.dts), -1 * PTS_DTS_SHIFT_TOLERANCE_90KHZ);
}
if (sample.dts < inputSamples[i > 0 ? i - 1 : i].dts) {
sortSamples = true;
}
} // sort video samples by DTS then PTS then demux id order
if (sortSamples) {
inputSamples.sort(function (a, b) {
var deltadts = a.dts - b.dts;
var deltapts = a.pts - b.pts;
return deltadts || deltapts;
});
} // Get first/last DTS
firstDTS = inputSamples[0].dts;
lastDTS = inputSamples[inputSamples.length - 1].dts; // on Safari let's signal the same sample duration for all samples
// sample duration (as expected by trun MP4 boxes), should be the delta between sample DTS
// set this constant duration as being the avg delta between consecutive DTS.
var averageSampleDuration = Math.round((lastDTS - firstDTS) / (nbSamples - 1)); // handle broken streams with PTS < DTS, tolerance up 0.2 seconds
if (ptsDtsShift < 0) {
if (ptsDtsShift < averageSampleDuration * -2) {
// Fix for "CNN special report, with CC" in test-streams (including Safari browser)
// With large PTS < DTS errors such as this, we want to correct CTS while maintaining increasing DTS values
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn("PTS < DTS detected in video samples, offsetting DTS from PTS by " + Object(_utils_timescale_conversion__WEBPACK_IMPORTED_MODULE_7__["toMsFromMpegTsClock"])(-averageSampleDuration, true) + " ms");
var lastDts = ptsDtsShift;
for (var _i = 0; _i < nbSamples; _i++) {
inputSamples[_i].dts = lastDts = Math.max(lastDts, inputSamples[_i].pts - averageSampleDuration);
inputSamples[_i].pts = Math.max(lastDts, inputSamples[_i].pts);
}
} else {
// Fix for "Custom IV with bad PTS DTS" in test-streams
// With smaller PTS < DTS errors we can simply move all DTS back. This increases CTS without causing buffer gaps or decode errors in Safari
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn("PTS < DTS detected in video samples, shifting DTS by " + Object(_utils_timescale_conversion__WEBPACK_IMPORTED_MODULE_7__["toMsFromMpegTsClock"])(ptsDtsShift, true) + " ms to overcome this issue");
for (var _i2 = 0; _i2 < nbSamples; _i2++) {
inputSamples[_i2].dts = inputSamples[_i2].dts + ptsDtsShift;
}
}
firstDTS = inputSamples[0].dts;
} // if fragment are contiguous, detect hole/overlapping between fragments
if (contiguous) {
// check timestamp continuity across consecutive fragments (this is to remove inter-fragment gap/hole)
var delta = firstDTS - nextAvcDts;
var foundHole = delta > averageSampleDuration;
var foundOverlap = delta < -1;
if (foundHole || foundOverlap) {
if (foundHole) {
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn("AVC: " + Object(_utils_timescale_conversion__WEBPACK_IMPORTED_MODULE_7__["toMsFromMpegTsClock"])(delta, true) + " ms (" + delta + "dts) hole between fragments detected, filling it");
} else {
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn("AVC: " + Object(_utils_timescale_conversion__WEBPACK_IMPORTED_MODULE_7__["toMsFromMpegTsClock"])(-delta, true) + " ms (" + delta + "dts) overlapping between fragments detected");
}
firstDTS = nextAvcDts;
var firstPTS = inputSamples[0].pts - delta;
inputSamples[0].dts = firstDTS;
inputSamples[0].pts = firstPTS;
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].log("Video: First PTS/DTS adjusted: " + Object(_utils_timescale_conversion__WEBPACK_IMPORTED_MODULE_7__["toMsFromMpegTsClock"])(firstPTS, true) + "/" + Object(_utils_timescale_conversion__WEBPACK_IMPORTED_MODULE_7__["toMsFromMpegTsClock"])(firstDTS, true) + ", delta: " + Object(_utils_timescale_conversion__WEBPACK_IMPORTED_MODULE_7__["toMsFromMpegTsClock"])(delta, true) + " ms");
}
}
if (requiresPositiveDts) {
firstDTS = Math.max(0, firstDTS);
}
var nbNalu = 0;
var naluLen = 0;
for (var _i3 = 0; _i3 < nbSamples; _i3++) {
// compute total/avc sample length and nb of NAL units
var _sample = inputSamples[_i3];
var units = _sample.units;
var nbUnits = units.length;
var sampleLen = 0;
for (var j = 0; j < nbUnits; j++) {
sampleLen += units[j].data.length;
}
naluLen += sampleLen;
nbNalu += nbUnits;
_sample.length = sampleLen; // normalize PTS/DTS
// ensure sample monotonic DTS
_sample.dts = Math.max(_sample.dts, firstDTS); // ensure that computed value is greater or equal than sample DTS
_sample.pts = Math.max(_sample.pts, _sample.dts, 0);
minPTS = Math.min(_sample.pts, minPTS);
maxPTS = Math.max(_sample.pts, maxPTS);
}
lastDTS = inputSamples[nbSamples - 1].dts;
/* concatenate the video data and construct the mdat in place
(need 8 more bytes to fill length and mpdat type) */
var mdatSize = naluLen + 4 * nbNalu + 8;
var mdat;
try {
mdat = new Uint8Array(mdatSize);
} catch (err) {
this.observer.emit(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].ERROR, _events__WEBPACK_IMPORTED_MODULE_3__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_4__["ErrorTypes"].MUX_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_4__["ErrorDetails"].REMUX_ALLOC_ERROR,
fatal: false,
bytes: mdatSize,
reason: "fail allocating video mdat " + mdatSize
});
return;
}
var view = new DataView(mdat.buffer);
view.setUint32(0, mdatSize);
mdat.set(_mp4_generator__WEBPACK_IMPORTED_MODULE_2__["default"].types.mdat, 4);
for (var _i4 = 0; _i4 < nbSamples; _i4++) {
var avcSample = inputSamples[_i4];
var avcSampleUnits = avcSample.units;
var mp4SampleLength = 0; // convert NALU bitstream to MP4 format (prepend NALU with size field)
for (var _j = 0, _nbUnits = avcSampleUnits.length; _j < _nbUnits; _j++) {
var unit = avcSampleUnits[_j];
var unitData = unit.data;
var unitDataLen = unit.data.byteLength;
view.setUint32(offset, unitDataLen);
offset += 4;
mdat.set(unitData, offset);
offset += unitDataLen;
mp4SampleLength += 4 + unitDataLen;
} // expected sample duration is the Decoding Timestamp diff of consecutive samples
if (_i4 < nbSamples - 1) {
mp4SampleDuration = inputSamples[_i4 + 1].dts - avcSample.dts;
} else {
var config = this.config;
var lastFrameDuration = avcSample.dts - inputSamples[_i4 > 0 ? _i4 - 1 : _i4].dts;
if (config.stretchShortVideoTrack && this.nextAudioPts !== null) {
// In some cases, a segment's audio track duration may exceed the video track duration.
// Since we've already remuxed audio, and we know how long the audio track is, we look to
// see if the delta to the next segment is longer than maxBufferHole.
// If so, playback would potentially get stuck, so we artificially inflate
// the duration of the last frame to minimize any potential gap between segments.
var gapTolerance = Math.floor(config.maxBufferHole * timeScale);
var deltaToFrameEnd = (audioTrackLength ? minPTS + audioTrackLength * timeScale : this.nextAudioPts) - avcSample.pts;
if (deltaToFrameEnd > gapTolerance) {
// We subtract lastFrameDuration from deltaToFrameEnd to try to prevent any video
// frame overlap. maxBufferHole should be >> lastFrameDuration anyway.
mp4SampleDuration = deltaToFrameEnd - lastFrameDuration;
if (mp4SampleDuration < 0) {
mp4SampleDuration = lastFrameDuration;
}
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].log("[mp4-remuxer]: It is approximately " + deltaToFrameEnd / 90 + " ms to the next segment; using duration " + mp4SampleDuration / 90 + " ms for the last video frame.");
} else {
mp4SampleDuration = lastFrameDuration;
}
} else {
mp4SampleDuration = lastFrameDuration;
}
}
var compositionTimeOffset = Math.round(avcSample.pts - avcSample.dts);
outputSamples.push(new Mp4Sample(avcSample.key, mp4SampleDuration, mp4SampleLength, compositionTimeOffset));
}
if (outputSamples.length && chromeVersion && chromeVersion < 70) {
// Chrome workaround, mark first sample as being a Random Access Point (keyframe) to avoid sourcebuffer append issue
// https://code.google.com/p/chromium/issues/detail?id=229412
var flags = outputSamples[0].flags;
flags.dependsOn = 2;
flags.isNonSync = 0;
}
console.assert(mp4SampleDuration !== undefined, 'mp4SampleDuration must be computed'); // next AVC sample DTS should be equal to last sample DTS + last sample duration (in PES timescale)
this.nextAvcDts = nextAvcDts = lastDTS + mp4SampleDuration;
this.isVideoContiguous = true;
var moof = _mp4_generator__WEBPACK_IMPORTED_MODULE_2__["default"].moof(track.sequenceNumber++, firstDTS, _extends({}, track, {
samples: outputSamples
}));
var type = 'video';
var data = {
data1: moof,
data2: mdat,
startPTS: minPTS / timeScale,
endPTS: (maxPTS + mp4SampleDuration) / timeScale,
startDTS: firstDTS / timeScale,
endDTS: nextAvcDts / timeScale,
type: type,
hasAudio: false,
hasVideo: true,
nb: outputSamples.length,
dropped: track.dropped
};
track.samples = [];
track.dropped = 0;
console.assert(mdat.length, 'MDAT length must not be zero');
return data;
};
_proto.remuxAudio = function remuxAudio(track, timeOffset, contiguous, accurateTimeOffset, videoTimeOffset) {
var inputTimeScale = track.inputTimeScale;
var mp4timeScale = track.samplerate ? track.samplerate : inputTimeScale;
var scaleFactor = inputTimeScale / mp4timeScale;
var mp4SampleDuration = track.isAAC ? AAC_SAMPLES_PER_FRAME : MPEG_AUDIO_SAMPLE_PER_FRAME;
var inputSampleDuration = mp4SampleDuration * scaleFactor;
var initPTS = this._initPTS;
var rawMPEG = !track.isAAC && this.typeSupported.mpeg;
var outputSamples = [];
var inputSamples = track.samples;
var offset = rawMPEG ? 0 : 8;
var nextAudioPts = this.nextAudioPts || -1; // window.audioSamples ? window.audioSamples.push(inputSamples.map(s => s.pts)) : (window.audioSamples = [inputSamples.map(s => s.pts)]);
// for audio samples, also consider consecutive fragments as being contiguous (even if a level switch occurs),
// for sake of clarity:
// consecutive fragments are frags with
// - less than 100ms gaps between new time offset (if accurate) and next expected PTS OR
// - less than 20 audio frames distance
// contiguous fragments are consecutive fragments from same quality level (same level, new SN = old SN + 1)
// this helps ensuring audio continuity
// and this also avoids audio glitches/cut when switching quality, or reporting wrong duration on first audio frame
var timeOffsetMpegTS = timeOffset * inputTimeScale;
this.isAudioContiguous = contiguous = contiguous || inputSamples.length && nextAudioPts > 0 && (accurateTimeOffset && Math.abs(timeOffsetMpegTS - nextAudioPts) < 9000 || Math.abs(normalizePts(inputSamples[0].pts - initPTS, timeOffsetMpegTS) - nextAudioPts) < 20 * inputSampleDuration); // compute normalized PTS
inputSamples.forEach(function (sample) {
sample.pts = normalizePts(sample.pts - initPTS, timeOffsetMpegTS);
});
if (!contiguous || nextAudioPts < 0) {
// filter out sample with negative PTS that are not playable anyway
// if we don't remove these negative samples, they will shift all audio samples forward.
// leading to audio overlap between current / next fragment
inputSamples = inputSamples.filter(function (sample) {
return sample.pts >= 0;
}); // in case all samples have negative PTS, and have been filtered out, return now
if (!inputSamples.length) {
return;
}
if (videoTimeOffset === 0) {
// Set the start to 0 to match video so that start gaps larger than inputSampleDuration are filled with silence
nextAudioPts = 0;
} else if (accurateTimeOffset) {
// When not seeking, not live, and LevelDetails.PTSKnown, use fragment start as predicted next audio PTS
nextAudioPts = Math.max(0, timeOffsetMpegTS);
} else {
// if frags are not contiguous and if we cant trust time offset, let's use first sample PTS as next audio PTS
nextAudioPts = inputSamples[0].pts;
}
} // If the audio track is missing samples, the frames seem to get "left-shifted" within the
// resulting mp4 segment, causing sync issues and leaving gaps at the end of the audio segment.
// In an effort to prevent this from happening, we inject frames here where there are gaps.
// When possible, we inject a silent frame; when that's not possible, we duplicate the last
// frame.
if (track.isAAC) {
var alignedWithVideo = videoTimeOffset !== undefined;
var maxAudioFramesDrift = this.config.maxAudioFramesDrift;
for (var i = 0, nextPts = nextAudioPts; i < inputSamples.length; i++) {
// First, let's see how far off this frame is from where we expect it to be
var sample = inputSamples[i];
var pts = sample.pts;
var delta = pts - nextPts;
var duration = Math.abs(1000 * delta / inputTimeScale); // When remuxing with video, if we're overlapping by more than a duration, drop this sample to stay in sync
if (delta <= -maxAudioFramesDrift * inputSampleDuration && alignedWithVideo) {
if (i === 0) {
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn("Audio frame @ " + (pts / inputTimeScale).toFixed(3) + "s overlaps nextAudioPts by " + Math.round(1000 * delta / inputTimeScale) + " ms.");
this.nextAudioPts = nextAudioPts = nextPts = pts;
}
} // eslint-disable-line brace-style
// Insert missing frames if:
// 1: We're more than maxAudioFramesDrift frame away
// 2: Not more than MAX_SILENT_FRAME_DURATION away
// 3: currentTime (aka nextPtsNorm) is not 0
// 4: remuxing with video (videoTimeOffset !== undefined)
else if (delta >= maxAudioFramesDrift * inputSampleDuration && duration < MAX_SILENT_FRAME_DURATION && alignedWithVideo) {
var missing = Math.round(delta / inputSampleDuration); // Adjust nextPts so that silent samples are aligned with media pts. This will prevent media samples from
// later being shifted if nextPts is based on timeOffset and delta is not a multiple of inputSampleDuration.
nextPts = pts - missing * inputSampleDuration;
if (nextPts < 0) {
missing--;
nextPts += inputSampleDuration;
}
if (i === 0) {
this.nextAudioPts = nextAudioPts = nextPts;
}
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn("[mp4-remuxer]: Injecting " + missing + " audio frame @ " + (nextPts / inputTimeScale).toFixed(3) + "s due to " + Math.round(1000 * delta / inputTimeScale) + " ms gap.");
for (var j = 0; j < missing; j++) {
var newStamp = Math.max(nextPts, 0);
var fillFrame = _aac_helper__WEBPACK_IMPORTED_MODULE_1__["default"].getSilentFrame(track.manifestCodec || track.codec, track.channelCount);
if (!fillFrame) {
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].log('[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead.');
fillFrame = sample.unit.subarray();
}
inputSamples.splice(i, 0, {
unit: fillFrame,
pts: newStamp
});
nextPts += inputSampleDuration;
i++;
}
}
sample.pts = nextPts;
nextPts += inputSampleDuration;
}
}
var firstPTS = null;
var lastPTS = null;
var mdat;
var mdatSize = 0;
var sampleLength = inputSamples.length;
while (sampleLength--) {
mdatSize += inputSamples[sampleLength].unit.byteLength;
}
for (var _j2 = 0, _nbSamples = inputSamples.length; _j2 < _nbSamples; _j2++) {
var audioSample = inputSamples[_j2];
var unit = audioSample.unit;
var _pts = audioSample.pts;
if (lastPTS !== null) {
// If we have more than one sample, set the duration of the sample to the "real" duration; the PTS diff with
// the previous sample
var prevSample = outputSamples[_j2 - 1];
prevSample.duration = Math.round((_pts - lastPTS) / scaleFactor);
} else {
if (contiguous && track.isAAC) {
// set PTS/DTS to expected PTS/DTS
_pts = nextAudioPts;
} // remember first PTS of our audioSamples
firstPTS = _pts;
if (mdatSize > 0) {
/* concatenate the audio data and construct the mdat in place
(need 8 more bytes to fill length and mdat type) */
mdatSize += offset;
try {
mdat = new Uint8Array(mdatSize);
} catch (err) {
this.observer.emit(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].ERROR, _events__WEBPACK_IMPORTED_MODULE_3__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_4__["ErrorTypes"].MUX_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_4__["ErrorDetails"].REMUX_ALLOC_ERROR,
fatal: false,
bytes: mdatSize,
reason: "fail allocating audio mdat " + mdatSize
});
return;
}
if (!rawMPEG) {
var view = new DataView(mdat.buffer);
view.setUint32(0, mdatSize);
mdat.set(_mp4_generator__WEBPACK_IMPORTED_MODULE_2__["default"].types.mdat, 4);
}
} else {
// no audio samples
return;
}
}
mdat.set(unit, offset);
var unitLen = unit.byteLength;
offset += unitLen; // Default the sample's duration to the computed mp4SampleDuration, which will either be 1024 for AAC or 1152 for MPEG
// In the case that we have 1 sample, this will be the duration. If we have more than one sample, the duration
// becomes the PTS diff with the previous sample
outputSamples.push(new Mp4Sample(true, mp4SampleDuration, unitLen, 0));
lastPTS = _pts;
} // We could end up with no audio samples if all input samples were overlapping with the previously remuxed ones
var nbSamples = outputSamples.length;
if (!nbSamples) {
return;
} // The next audio sample PTS should be equal to last sample PTS + duration
var lastSample = outputSamples[outputSamples.length - 1];
this.nextAudioPts = nextAudioPts = lastPTS + scaleFactor * lastSample.duration; // Set the track samples from inputSamples to outputSamples before remuxing
var moof = rawMPEG ? new Uint8Array(0) : _mp4_generator__WEBPACK_IMPORTED_MODULE_2__["default"].moof(track.sequenceNumber++, firstPTS / scaleFactor, _extends({}, track, {
samples: outputSamples
})); // Clear the track samples. This also clears the samples array in the demuxer, since the reference is shared
track.samples = [];
var start = firstPTS / inputTimeScale;
var end = nextAudioPts / inputTimeScale;
var type = 'audio';
var audioData = {
data1: moof,
data2: mdat,
startPTS: start,
endPTS: end,
startDTS: start,
endDTS: end,
type: type,
hasAudio: true,
hasVideo: false,
nb: nbSamples
};
this.isAudioContiguous = true;
console.assert(mdat.length, 'MDAT length must not be zero');
return audioData;
};
_proto.remuxEmptyAudio = function remuxEmptyAudio(track, timeOffset, contiguous, videoData) {
var inputTimeScale = track.inputTimeScale;
var mp4timeScale = track.samplerate ? track.samplerate : inputTimeScale;
var scaleFactor = inputTimeScale / mp4timeScale;
var nextAudioPts = this.nextAudioPts; // sync with video's timestamp
var startDTS = (nextAudioPts !== null ? nextAudioPts : videoData.startDTS * inputTimeScale) + this._initDTS;
var endDTS = videoData.endDTS * inputTimeScale + this._initDTS; // one sample's duration value
var frameDuration = scaleFactor * AAC_SAMPLES_PER_FRAME; // samples count of this segment's duration
var nbSamples = Math.ceil((endDTS - startDTS) / frameDuration); // silent frame
var silentFrame = _aac_helper__WEBPACK_IMPORTED_MODULE_1__["default"].getSilentFrame(track.manifestCodec || track.codec, track.channelCount);
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn('[mp4-remuxer]: remux empty Audio'); // Can't remux if we can't generate a silent frame...
if (!silentFrame) {
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].trace('[mp4-remuxer]: Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec');
return;
}
var samples = [];
for (var i = 0; i < nbSamples; i++) {
var stamp = startDTS + i * frameDuration;
samples.push({
unit: silentFrame,
pts: stamp,
dts: stamp
});
}
track.samples = samples;
return this.remuxAudio(track, timeOffset, contiguous, false);
};
_proto.remuxID3 = function remuxID3(track, timeOffset) {
var length = track.samples.length;
if (!length) {
return;
}
var inputTimeScale = track.inputTimeScale;
var initPTS = this._initPTS;
var initDTS = this._initDTS;
for (var index = 0; index < length; index++) {
var sample = track.samples[index]; // setting id3 pts, dts to relative time
// using this._initPTS and this._initDTS to calculate relative time
sample.pts = normalizePts(sample.pts - initPTS, timeOffset * inputTimeScale) / inputTimeScale;
sample.dts = normalizePts(sample.dts - initDTS, timeOffset * inputTimeScale) / inputTimeScale;
}
var samples = track.samples;
track.samples = [];
return {
samples: samples
};
};
_proto.remuxText = function remuxText(track, timeOffset) {
var length = track.samples.length;
if (!length) {
return;
}
var inputTimeScale = track.inputTimeScale;
var initPTS = this._initPTS;
for (var index = 0; index < length; index++) {
var sample = track.samples[index]; // setting text pts, dts to relative time
// using this._initPTS and this._initDTS to calculate relative time
sample.pts = normalizePts(sample.pts - initPTS, timeOffset * inputTimeScale) / inputTimeScale;
}
track.samples.sort(function (a, b) {
return a.pts - b.pts;
});
var samples = track.samples;
track.samples = [];
return {
samples: samples
};
};
return MP4Remuxer;
}();
function normalizePts(value, reference) {
var offset;
if (reference === null) {
return value;
}
if (reference < value) {
// - 2^33
offset = -8589934592;
} else {
// + 2^33
offset = 8589934592;
}
/* PTS is 33bit (from 0 to 2^33 -1)
if diff between value and reference is bigger than half of the amplitude (2^32) then it means that
PTS looping occured. fill the gap */
while (Math.abs(value - reference) > 4294967296) {
value += offset;
}
return value;
}
function findKeyframeIndex(samples) {
for (var i = 0; i < samples.length; i++) {
if (samples[i].key) {
return i;
}
}
return -1;
}
var Mp4Sample = function Mp4Sample(isKeyframe, duration, size, cts) {
this.size = void 0;
this.duration = void 0;
this.cts = void 0;
this.flags = void 0;
this.duration = duration;
this.size = size;
this.cts = cts;
this.flags = new Mp4SampleFlags(isKeyframe);
};
var Mp4SampleFlags = function Mp4SampleFlags(isKeyframe) {
this.isLeading = 0;
this.isDependedOn = 0;
this.hasRedundancy = 0;
this.degradPrio = 0;
this.dependsOn = 1;
this.isNonSync = 1;
this.dependsOn = isKeyframe ? 2 : 1;
this.isNonSync = isKeyframe ? 0 : 1;
};
/***/ }),
/***/ "./src/remux/passthrough-remuxer.ts":
/*!******************************************!*\
!*** ./src/remux/passthrough-remuxer.ts ***!
\******************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/mp4-tools */ "./src/utils/mp4-tools.ts");
/* harmony import */ var _loader_fragment__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../loader/fragment */ "./src/loader/fragment.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
var PassThroughRemuxer = /*#__PURE__*/function () {
function PassThroughRemuxer() {
this.emitInitSegment = false;
this.audioCodec = void 0;
this.videoCodec = void 0;
this.initData = void 0;
this.initPTS = void 0;
this.initTracks = void 0;
this.lastEndDTS = null;
}
var _proto = PassThroughRemuxer.prototype;
_proto.destroy = function destroy() {};
_proto.resetTimeStamp = function resetTimeStamp(defaultInitPTS) {
this.initPTS = defaultInitPTS;
this.lastEndDTS = null;
};
_proto.resetNextTimestamp = function resetNextTimestamp() {
this.lastEndDTS = null;
};
_proto.resetInitSegment = function resetInitSegment(initSegment, audioCodec, videoCodec) {
this.audioCodec = audioCodec;
this.videoCodec = videoCodec;
this.generateInitSegment(initSegment);
this.emitInitSegment = true;
};
_proto.generateInitSegment = function generateInitSegment(initSegment) {
var audioCodec = this.audioCodec,
videoCodec = this.videoCodec;
if (!initSegment || !initSegment.byteLength) {
this.initTracks = undefined;
this.initData = undefined;
return;
}
var initData = this.initData = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_1__["parseInitSegment"])(initSegment); // Get codec from initSegment or fallback to default
if (!audioCodec) {
audioCodec = getParsedTrackCodec(initData.audio, _loader_fragment__WEBPACK_IMPORTED_MODULE_2__["ElementaryStreamTypes"].AUDIO);
}
if (!videoCodec) {
videoCodec = getParsedTrackCodec(initData.video, _loader_fragment__WEBPACK_IMPORTED_MODULE_2__["ElementaryStreamTypes"].VIDEO);
}
var tracks = {};
if (initData.audio && initData.video) {
tracks.audiovideo = {
container: 'video/mp4',
codec: audioCodec + ',' + videoCodec,
initSegment: initSegment,
id: 'main'
};
} else if (initData.audio) {
tracks.audio = {
container: 'audio/mp4',
codec: audioCodec,
initSegment: initSegment,
id: 'audio'
};
} else if (initData.video) {
tracks.video = {
container: 'video/mp4',
codec: videoCodec,
initSegment: initSegment,
id: 'main'
};
} else {
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn('[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes.');
}
this.initTracks = tracks;
};
_proto.remux = function remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset) {
var initPTS = this.initPTS,
lastEndDTS = this.lastEndDTS;
var result = {
audio: undefined,
video: undefined,
text: textTrack,
id3: id3Track,
initSegment: undefined
}; // If we haven't yet set a lastEndDTS, or it was reset, set it to the provided timeOffset. We want to use the
// lastEndDTS over timeOffset whenever possible; during progressive playback, the media source will not update
// the media duration (which is what timeOffset is provided as) before we need to process the next chunk.
if (!Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(lastEndDTS)) {
lastEndDTS = this.lastEndDTS = timeOffset || 0;
} // The binary segment data is added to the videoTrack in the mp4demuxer. We don't check to see if the data is only
// audio or video (or both); adding it to video was an arbitrary choice.
var data = videoTrack.samples;
if (!data || !data.length) {
return result;
}
var initSegment = {
initPTS: undefined,
timescale: 1
};
var initData = this.initData;
if (!initData || !initData.length) {
this.generateInitSegment(data);
initData = this.initData;
}
if (!initData || !initData.length) {
// We can't remux if the initSegment could not be generated
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn('[passthrough-remuxer.ts]: Failed to generate initSegment.');
return result;
}
if (this.emitInitSegment) {
initSegment.tracks = this.initTracks;
this.emitInitSegment = false;
}
if (!Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(initPTS)) {
this.initPTS = initSegment.initPTS = initPTS = computeInitPTS(initData, data, lastEndDTS);
}
var duration = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_1__["getDuration"])(data, initData);
var startDTS = lastEndDTS;
var endDTS = duration + startDTS;
Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_1__["offsetStartDTS"])(initData, data, initPTS);
if (duration > 0) {
this.lastEndDTS = endDTS;
} else {
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn('Duration parsed from mp4 should be greater than zero');
this.resetNextTimestamp();
}
var hasAudio = !!initData.audio;
var hasVideo = !!initData.video;
var type = '';
if (hasAudio) {
type += 'audio';
}
if (hasVideo) {
type += 'video';
}
var track = {
data1: data,
startPTS: startDTS,
startDTS: startDTS,
endPTS: endDTS,
endDTS: endDTS,
type: type,
hasAudio: hasAudio,
hasVideo: hasVideo,
nb: 1,
dropped: 0
};
result.audio = track.type === 'audio' ? track : undefined;
result.video = track.type !== 'audio' ? track : undefined;
result.text = textTrack;
result.id3 = id3Track;
result.initSegment = initSegment;
return result;
};
return PassThroughRemuxer;
}();
var computeInitPTS = function computeInitPTS(initData, data, timeOffset) {
return Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_1__["getStartDTS"])(initData, data) - timeOffset;
};
function getParsedTrackCodec(track, type) {
var parsedCodec = track === null || track === void 0 ? void 0 : track.codec;
if (parsedCodec && parsedCodec.length > 4) {
return parsedCodec;
} // Since mp4-tools cannot parse full codec string (see 'TODO: Parse codec details'... in mp4-tools)
// Provide defaults based on codec type
// This allows for some playback of some fmp4 playlists without CODECS defined in manifest
if (parsedCodec === 'hvc1') {
return 'hvc1.1.c.L120.90';
}
if (parsedCodec === 'av01') {
return 'av01.0.04M.08';
}
if (parsedCodec === 'avc1' || type === _loader_fragment__WEBPACK_IMPORTED_MODULE_2__["ElementaryStreamTypes"].VIDEO) {
return 'avc1.42e01e';
}
return 'mp4a.40.5';
}
/* harmony default export */ __webpack_exports__["default"] = (PassThroughRemuxer);
/***/ }),
/***/ "./src/task-loop.ts":
/*!**************************!*\
!*** ./src/task-loop.ts ***!
\**************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return TaskLoop; });
/**
* Sub-class specialization of EventHandler base class.
*
* TaskLoop allows to schedule a task function being called (optionnaly repeatedly) on the main loop,
* scheduled asynchroneously, avoiding recursive calls in the same tick.
*
* The task itself is implemented in `doTick`. It can be requested and called for single execution
* using the `tick` method.
*
* It will be assured that the task execution method (`tick`) only gets called once per main loop "tick",
* no matter how often it gets requested for execution. Execution in further ticks will be scheduled accordingly.
*
* If further execution requests have already been scheduled on the next tick, it can be checked with `hasNextTick`,
* and cancelled with `clearNextTick`.
*
* The task can be scheduled as an interval repeatedly with a period as parameter (see `setInterval`, `clearInterval`).
*
* Sub-classes need to implement the `doTick` method which will effectively have the task execution routine.
*
* Further explanations:
*
* The baseclass has a `tick` method that will schedule the doTick call. It may be called synchroneously
* only for a stack-depth of one. On re-entrant calls, sub-sequent calls are scheduled for next main loop ticks.
*
* When the task execution (`tick` method) is called in re-entrant way this is detected and
* we are limiting the task execution per call stack to exactly one, but scheduling/post-poning further
* task processing on the next main loop iteration (also known as "next tick" in the Node/JS runtime lingo).
*/
var TaskLoop = /*#__PURE__*/function () {
function TaskLoop() {
this._boundTick = void 0;
this._tickTimer = null;
this._tickInterval = null;
this._tickCallCount = 0;
this._boundTick = this.tick.bind(this);
}
var _proto = TaskLoop.prototype;
_proto.destroy = function destroy() {
this.onHandlerDestroying();
this.onHandlerDestroyed();
};
_proto.onHandlerDestroying = function onHandlerDestroying() {
// clear all timers before unregistering from event bus
this.clearNextTick();
this.clearInterval();
};
_proto.onHandlerDestroyed = function onHandlerDestroyed() {}
/**
* @returns {boolean}
*/
;
_proto.hasInterval = function hasInterval() {
return !!this._tickInterval;
}
/**
* @returns {boolean}
*/
;
_proto.hasNextTick = function hasNextTick() {
return !!this._tickTimer;
}
/**
* @param {number} millis Interval time (ms)
* @returns {boolean} True when interval has been scheduled, false when already scheduled (no effect)
*/
;
_proto.setInterval = function setInterval(millis) {
if (!this._tickInterval) {
this._tickInterval = self.setInterval(this._boundTick, millis);
return true;
}
return false;
}
/**
* @returns {boolean} True when interval was cleared, false when none was set (no effect)
*/
;
_proto.clearInterval = function clearInterval() {
if (this._tickInterval) {
self.clearInterval(this._tickInterval);
this._tickInterval = null;
return true;
}
return false;
}
/**
* @returns {boolean} True when timeout was cleared, false when none was set (no effect)
*/
;
_proto.clearNextTick = function clearNextTick() {
if (this._tickTimer) {
self.clearTimeout(this._tickTimer);
this._tickTimer = null;
return true;
}
return false;
}
/**
* Will call the subclass doTick implementation in this main loop tick
* or in the next one (via setTimeout(,0)) in case it has already been called
* in this tick (in case this is a re-entrant call).
*/
;
_proto.tick = function tick() {
this._tickCallCount++;
if (this._tickCallCount === 1) {
this.doTick(); // re-entrant call to tick from previous doTick call stack
// -> schedule a call on the next main loop iteration to process this task processing request
if (this._tickCallCount > 1) {
// make sure only one timer exists at any time at max
this.tickImmediate();
}
this._tickCallCount = 0;
}
};
_proto.tickImmediate = function tickImmediate() {
this.clearNextTick();
this._tickTimer = self.setTimeout(this._boundTick, 0);
}
/**
* For subclass to implement task logic
* @abstract
*/
;
_proto.doTick = function doTick() {};
return TaskLoop;
}();
/***/ }),
/***/ "./src/types/level.ts":
/*!****************************!*\
!*** ./src/types/level.ts ***!
\****************************/
/*! exports provided: HlsSkip, getSkipValue, HlsUrlParameters, Level */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HlsSkip", function() { return HlsSkip; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getSkipValue", function() { return getSkipValue; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HlsUrlParameters", function() { return HlsUrlParameters; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Level", function() { return Level; });
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
var HlsSkip;
(function (HlsSkip) {
HlsSkip["No"] = "";
HlsSkip["Yes"] = "YES";
HlsSkip["v2"] = "v2";
})(HlsSkip || (HlsSkip = {}));
function getSkipValue(details, msn) {
var canSkipUntil = details.canSkipUntil,
canSkipDateRanges = details.canSkipDateRanges,
endSN = details.endSN;
var snChangeGoal = msn !== undefined ? msn - endSN : 0;
if (canSkipUntil && snChangeGoal < canSkipUntil) {
if (canSkipDateRanges) {
return HlsSkip.v2;
}
return HlsSkip.Yes;
}
return HlsSkip.No;
}
var HlsUrlParameters = /*#__PURE__*/function () {
function HlsUrlParameters(msn, part, skip) {
this.msn = void 0;
this.part = void 0;
this.skip = void 0;
this.msn = msn;
this.part = part;
this.skip = skip;
}
var _proto = HlsUrlParameters.prototype;
_proto.addDirectives = function addDirectives(uri) {
var url = new self.URL(uri);
if (this.msn !== undefined) {
url.searchParams.set('_HLS_msn', this.msn.toString());
}
if (this.part !== undefined) {
url.searchParams.set('_HLS_part', this.part.toString());
}
if (this.skip) {
url.searchParams.set('_HLS_skip', this.skip);
}
return url.toString();
};
return HlsUrlParameters;
}();
var Level = /*#__PURE__*/function () {
function Level(data) {
this.attrs = void 0;
this.audioCodec = void 0;
this.bitrate = void 0;
this.codecSet = void 0;
this.height = void 0;
this.id = void 0;
this.name = void 0;
this.videoCodec = void 0;
this.width = void 0;
this.unknownCodecs = void 0;
this.audioGroupIds = void 0;
this.details = void 0;
this.fragmentError = 0;
this.loadError = 0;
this.loaded = void 0;
this.realBitrate = 0;
this.textGroupIds = void 0;
this.url = void 0;
this._urlId = 0;
this.url = [data.url];
this.attrs = data.attrs;
this.bitrate = data.bitrate;
if (data.details) {
this.details = data.details;
}
this.id = data.id || 0;
this.name = data.name;
this.width = data.width || 0;
this.height = data.height || 0;
this.audioCodec = data.audioCodec;
this.videoCodec = data.videoCodec;
this.unknownCodecs = data.unknownCodecs;
this.codecSet = [data.videoCodec, data.audioCodec].filter(function (c) {
return c;
}).join(',').replace(/\.[^.,]+/g, '');
}
_createClass(Level, [{
key: "maxBitrate",
get: function get() {
return Math.max(this.realBitrate, this.bitrate);
}
}, {
key: "uri",
get: function get() {
return this.url[this._urlId] || '';
}
}, {
key: "urlId",
get: function get() {
return this._urlId;
},
set: function set(value) {
var newValue = value % this.url.length;
if (this._urlId !== newValue) {
this.details = undefined;
this._urlId = newValue;
}
}
}]);
return Level;
}();
/***/ }),
/***/ "./src/types/loader.ts":
/*!*****************************!*\
!*** ./src/types/loader.ts ***!
\*****************************/
/*! exports provided: PlaylistContextType, PlaylistLevelType */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PlaylistContextType", function() { return PlaylistContextType; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PlaylistLevelType", function() { return PlaylistLevelType; });
var PlaylistContextType;
(function (PlaylistContextType) {
PlaylistContextType["MANIFEST"] = "manifest";
PlaylistContextType["LEVEL"] = "level";
PlaylistContextType["AUDIO_TRACK"] = "audioTrack";
PlaylistContextType["SUBTITLE_TRACK"] = "subtitleTrack";
})(PlaylistContextType || (PlaylistContextType = {}));
var PlaylistLevelType;
(function (PlaylistLevelType) {
PlaylistLevelType["MAIN"] = "main";
PlaylistLevelType["AUDIO"] = "audio";
PlaylistLevelType["SUBTITLE"] = "subtitle";
})(PlaylistLevelType || (PlaylistLevelType = {}));
/***/ }),
/***/ "./src/types/transmuxer.ts":
/*!*********************************!*\
!*** ./src/types/transmuxer.ts ***!
\*********************************/
/*! exports provided: ChunkMetadata */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ChunkMetadata", function() { return ChunkMetadata; });
var ChunkMetadata = function ChunkMetadata(level, sn, id, size, part, partial) {
if (size === void 0) {
size = 0;
}
if (part === void 0) {
part = -1;
}
if (partial === void 0) {
partial = false;
}
this.level = void 0;
this.sn = void 0;
this.part = void 0;
this.id = void 0;
this.size = void 0;
this.partial = void 0;
this.transmuxing = getNewPerformanceTiming();
this.buffering = {
audio: getNewPerformanceTiming(),
video: getNewPerformanceTiming(),
audiovideo: getNewPerformanceTiming()
};
this.level = level;
this.sn = sn;
this.id = id;
this.size = size;
this.part = part;
this.partial = partial;
};
function getNewPerformanceTiming() {
return {
start: 0,
executeStart: 0,
executeEnd: 0,
end: 0
};
}
/***/ }),
/***/ "./src/utils/attr-list.ts":
/*!********************************!*\
!*** ./src/utils/attr-list.ts ***!
\********************************/
/*! exports provided: AttrList */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AttrList", function() { return AttrList; });
var DECIMAL_RESOLUTION_REGEX = /^(\d+)x(\d+)$/; // eslint-disable-line no-useless-escape
var ATTR_LIST_REGEX = /\s*(.+?)\s*=((?:\".*?\")|.*?)(?:,|$)/g; // eslint-disable-line no-useless-escape
// adapted from https://github.com/kanongil/node-m3u8parse/blob/master/attrlist.js
var AttrList = /*#__PURE__*/function () {
function AttrList(attrs) {
if (typeof attrs === 'string') {
attrs = AttrList.parseAttrList(attrs);
}
for (var attr in attrs) {
if (attrs.hasOwnProperty(attr)) {
this[attr] = attrs[attr];
}
}
}
var _proto = AttrList.prototype;
_proto.decimalInteger = function decimalInteger(attrName) {
var intValue = parseInt(this[attrName], 10);
if (intValue > Number.MAX_SAFE_INTEGER) {
return Infinity;
}
return intValue;
};
_proto.hexadecimalInteger = function hexadecimalInteger(attrName) {
if (this[attrName]) {
var stringValue = (this[attrName] || '0x').slice(2);
stringValue = (stringValue.length & 1 ? '0' : '') + stringValue;
var value = new Uint8Array(stringValue.length / 2);
for (var i = 0; i < stringValue.length / 2; i++) {
value[i] = parseInt(stringValue.slice(i * 2, i * 2 + 2), 16);
}
return value;
} else {
return null;
}
};
_proto.hexadecimalIntegerAsNumber = function hexadecimalIntegerAsNumber(attrName) {
var intValue = parseInt(this[attrName], 16);
if (intValue > Number.MAX_SAFE_INTEGER) {
return Infinity;
}
return intValue;
};
_proto.decimalFloatingPoint = function decimalFloatingPoint(attrName) {
return parseFloat(this[attrName]);
};
_proto.optionalFloat = function optionalFloat(attrName, defaultValue) {
var value = this[attrName];
return value ? parseFloat(value) : defaultValue;
};
_proto.enumeratedString = function enumeratedString(attrName) {
return this[attrName];
};
_proto.bool = function bool(attrName) {
return this[attrName] === 'YES';
};
_proto.decimalResolution = function decimalResolution(attrName) {
var res = DECIMAL_RESOLUTION_REGEX.exec(this[attrName]);
if (res === null) {
return undefined;
}
return {
width: parseInt(res[1], 10),
height: parseInt(res[2], 10)
};
};
AttrList.parseAttrList = function parseAttrList(input) {
var match;
var attrs = {};
var quote = '"';
ATTR_LIST_REGEX.lastIndex = 0;
while ((match = ATTR_LIST_REGEX.exec(input)) !== null) {
var value = match[2];
if (value.indexOf(quote) === 0 && value.lastIndexOf(quote) === value.length - 1) {
value = value.slice(1, -1);
}
attrs[match[1]] = value;
}
return attrs;
};
return AttrList;
}();
/***/ }),
/***/ "./src/utils/binary-search.ts":
/*!************************************!*\
!*** ./src/utils/binary-search.ts ***!
\************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
var BinarySearch = {
/**
* Searches for an item in an array which matches a certain condition.
* This requires the condition to only match one item in the array,
* and for the array to be ordered.
*
* @param {Array<T>} list The array to search.
* @param {BinarySearchComparison<T>} comparisonFn
* Called and provided a candidate item as the first argument.
* Should return:
* > -1 if the item should be located at a lower index than the provided item.
* > 1 if the item should be located at a higher index than the provided item.
* > 0 if the item is the item you're looking for.
*
* @return {T | null} The object if it is found or null otherwise.
*/
search: function search(list, comparisonFn) {
var minIndex = 0;
var maxIndex = list.length - 1;
var currentIndex = null;
var currentElement = null;
while (minIndex <= maxIndex) {
currentIndex = (minIndex + maxIndex) / 2 | 0;
currentElement = list[currentIndex];
var comparisonResult = comparisonFn(currentElement);
if (comparisonResult > 0) {
minIndex = currentIndex + 1;
} else if (comparisonResult < 0) {
maxIndex = currentIndex - 1;
} else {
return currentElement;
}
}
return null;
}
};
/* harmony default export */ __webpack_exports__["default"] = (BinarySearch);
/***/ }),
/***/ "./src/utils/buffer-helper.ts":
/*!************************************!*\
!*** ./src/utils/buffer-helper.ts ***!
\************************************/
/*! exports provided: BufferHelper */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BufferHelper", function() { return BufferHelper; });
/* harmony import */ var _logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./logger */ "./src/utils/logger.ts");
/**
* @module BufferHelper
*
* Providing methods dealing with buffer length retrieval for example.
*
* In general, a helper around HTML5 MediaElement TimeRanges gathered from `buffered` property.
*
* Also @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/buffered
*/
var noopBuffered = {
length: 0,
start: function start() {
return 0;
},
end: function end() {
return 0;
}
};
var BufferHelper = /*#__PURE__*/function () {
function BufferHelper() {}
/**
* Return true if `media`'s buffered include `position`
* @param {Bufferable} media
* @param {number} position
* @returns {boolean}
*/
BufferHelper.isBuffered = function isBuffered(media, position) {
try {
if (media) {
var buffered = BufferHelper.getBuffered(media);
for (var i = 0; i < buffered.length; i++) {
if (position >= buffered.start(i) && position <= buffered.end(i)) {
return true;
}
}
}
} catch (error) {// this is to catch
// InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer':
// This SourceBuffer has been removed from the parent media source
}
return false;
};
BufferHelper.bufferInfo = function bufferInfo(media, pos, maxHoleDuration) {
try {
if (media) {
var vbuffered = BufferHelper.getBuffered(media);
var buffered = [];
var i;
for (i = 0; i < vbuffered.length; i++) {
buffered.push({
start: vbuffered.start(i),
end: vbuffered.end(i)
});
}
return this.bufferedInfo(buffered, pos, maxHoleDuration);
}
} catch (error) {// this is to catch
// InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer':
// This SourceBuffer has been removed from the parent media source
}
return {
len: 0,
start: pos,
end: pos,
nextStart: undefined
};
};
BufferHelper.bufferedInfo = function bufferedInfo(buffered, pos, maxHoleDuration) {
pos = Math.max(0, pos); // sort on buffer.start/smaller end (IE does not always return sorted buffered range)
buffered.sort(function (a, b) {
var diff = a.start - b.start;
if (diff) {
return diff;
} else {
return b.end - a.end;
}
});
var buffered2 = [];
if (maxHoleDuration) {
// there might be some small holes between buffer time range
// consider that holes smaller than maxHoleDuration are irrelevant and build another
// buffer time range representations that discards those holes
for (var i = 0; i < buffered.length; i++) {
var buf2len = buffered2.length;
if (buf2len) {
var buf2end = buffered2[buf2len - 1].end; // if small hole (value between 0 or maxHoleDuration ) or overlapping (negative)
if (buffered[i].start - buf2end < maxHoleDuration) {
// merge overlapping time ranges
// update lastRange.end only if smaller than item.end
// e.g. [ 1, 15] with [ 2,8] => [ 1,15] (no need to modify lastRange.end)
// whereas [ 1, 8] with [ 2,15] => [ 1,15] ( lastRange should switch from [1,8] to [1,15])
if (buffered[i].end > buf2end) {
buffered2[buf2len - 1].end = buffered[i].end;
}
} else {
// big hole
buffered2.push(buffered[i]);
}
} else {
// first value
buffered2.push(buffered[i]);
}
}
} else {
buffered2 = buffered;
}
var bufferLen = 0; // bufferStartNext can possibly be undefined based on the conditional logic below
var bufferStartNext; // bufferStart and bufferEnd are buffer boundaries around current video position
var bufferStart = pos;
var bufferEnd = pos;
for (var _i = 0; _i < buffered2.length; _i++) {
var start = buffered2[_i].start;
var end = buffered2[_i].end; // logger.log('buf start/end:' + buffered.start(i) + '/' + buffered.end(i));
if (pos + maxHoleDuration >= start && pos < end) {
// play position is inside this buffer TimeRange, retrieve end of buffer position and buffer length
bufferStart = start;
bufferEnd = end;
bufferLen = bufferEnd - pos;
} else if (pos + maxHoleDuration < start) {
bufferStartNext = start;
break;
}
}
return {
len: bufferLen,
start: bufferStart || 0,
end: bufferEnd || 0,
nextStart: bufferStartNext
};
}
/**
* Safe method to get buffered property.
* SourceBuffer.buffered may throw if SourceBuffer is removed from it's MediaSource
*/
;
BufferHelper.getBuffered = function getBuffered(media) {
try {
return media.buffered;
} catch (e) {
_logger__WEBPACK_IMPORTED_MODULE_0__["logger"].log('failed to get media.buffered', e);
return noopBuffered;
}
};
return BufferHelper;
}();
/***/ }),
/***/ "./src/utils/codecs.ts":
/*!*****************************!*\
!*** ./src/utils/codecs.ts ***!
\*****************************/
/*! exports provided: isCodecType, isCodecSupportedInMp4 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isCodecType", function() { return isCodecType; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isCodecSupportedInMp4", function() { return isCodecSupportedInMp4; });
// from http://mp4ra.org/codecs.html
var sampleEntryCodesISO = {
audio: {
a3ds: true,
'ac-3': true,
'ac-4': true,
alac: true,
alaw: true,
dra1: true,
'dts+': true,
'dts-': true,
dtsc: true,
dtse: true,
dtsh: true,
'ec-3': true,
enca: true,
g719: true,
g726: true,
m4ae: true,
mha1: true,
mha2: true,
mhm1: true,
mhm2: true,
mlpa: true,
mp4a: true,
'raw ': true,
Opus: true,
samr: true,
sawb: true,
sawp: true,
sevc: true,
sqcp: true,
ssmv: true,
twos: true,
ulaw: true
},
video: {
avc1: true,
avc2: true,
avc3: true,
avc4: true,
avcp: true,
av01: true,
drac: true,
dvav: true,
dvhe: true,
encv: true,
hev1: true,
hvc1: true,
mjp2: true,
mp4v: true,
mvc1: true,
mvc2: true,
mvc3: true,
mvc4: true,
resv: true,
rv60: true,
s263: true,
svc1: true,
svc2: true,
'vc-1': true,
vp08: true,
vp09: true
},
text: {
stpp: true,
wvtt: true
}
};
function isCodecType(codec, type) {
var typeCodes = sampleEntryCodesISO[type];
return !!typeCodes && typeCodes[codec.slice(0, 4)] === true;
}
function isCodecSupportedInMp4(codec, type) {
return MediaSource.isTypeSupported((type || 'video') + "/mp4;codecs=\"" + codec + "\"");
}
/***/ }),
/***/ "./src/utils/discontinuities.ts":
/*!**************************************!*\
!*** ./src/utils/discontinuities.ts ***!
\**************************************/
/*! exports provided: findFirstFragWithCC, shouldAlignOnDiscontinuities, findDiscontinuousReferenceFrag, adjustSlidingStart, alignStream, alignPDT, alignFragmentByPDTDelta, alignMediaPlaylistByPDT */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findFirstFragWithCC", function() { return findFirstFragWithCC; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "shouldAlignOnDiscontinuities", function() { return shouldAlignOnDiscontinuities; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findDiscontinuousReferenceFrag", function() { return findDiscontinuousReferenceFrag; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "adjustSlidingStart", function() { return adjustSlidingStart; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "alignStream", function() { return alignStream; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "alignPDT", function() { return alignPDT; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "alignFragmentByPDTDelta", function() { return alignFragmentByPDTDelta; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "alignMediaPlaylistByPDT", function() { return alignMediaPlaylistByPDT; });
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var _logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./logger */ "./src/utils/logger.ts");
/* harmony import */ var _controller_level_helper__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../controller/level-helper */ "./src/controller/level-helper.ts");
function findFirstFragWithCC(fragments, cc) {
var firstFrag = null;
for (var i = 0, len = fragments.length; i < len; i++) {
var currentFrag = fragments[i];
if (currentFrag && currentFrag.cc === cc) {
firstFrag = currentFrag;
break;
}
}
return firstFrag;
}
function shouldAlignOnDiscontinuities(lastFrag, lastLevel, details) {
if (lastLevel.details) {
if (details.endCC > details.startCC || lastFrag && lastFrag.cc < details.startCC) {
return true;
}
}
return false;
} // Find the first frag in the previous level which matches the CC of the first frag of the new level
function findDiscontinuousReferenceFrag(prevDetails, curDetails) {
var prevFrags = prevDetails.fragments;
var curFrags = curDetails.fragments;
if (!curFrags.length || !prevFrags.length) {
_logger__WEBPACK_IMPORTED_MODULE_1__["logger"].log('No fragments to align');
return;
}
var prevStartFrag = findFirstFragWithCC(prevFrags, curFrags[0].cc);
if (!prevStartFrag || prevStartFrag && !prevStartFrag.startPTS) {
_logger__WEBPACK_IMPORTED_MODULE_1__["logger"].log('No frag in previous level to align on');
return;
}
return prevStartFrag;
}
function adjustFragmentStart(frag, sliding) {
if (frag) {
var start = frag.start + sliding;
frag.start = frag.startPTS = start;
frag.endPTS = start + frag.duration;
}
}
function adjustSlidingStart(sliding, details) {
// Update segments
var fragments = details.fragments;
for (var i = 0, len = fragments.length; i < len; i++) {
adjustFragmentStart(fragments[i], sliding);
} // Update LL-HLS parts at the end of the playlist
if (details.fragmentHint) {
adjustFragmentStart(details.fragmentHint, sliding);
}
details.alignedSliding = true;
}
/**
* Using the parameters of the last level, this function computes PTS' of the new fragments so that they form a
* contiguous stream with the last fragments.
* The PTS of a fragment lets Hls.js know where it fits into a stream - by knowing every PTS, we know which fragment to
* download at any given time. PTS is normally computed when the fragment is demuxed, so taking this step saves us time
* and an extra download.
* @param lastFrag
* @param lastLevel
* @param details
*/
function alignStream(lastFrag, lastLevel, details) {
if (!lastLevel) {
return;
}
alignDiscontinuities(lastFrag, details, lastLevel);
if (!details.alignedSliding && lastLevel.details) {
// If the PTS wasn't figured out via discontinuity sequence that means there was no CC increase within the level.
// Aligning via Program Date Time should therefore be reliable, since PDT should be the same within the same
// discontinuity sequence.
alignPDT(details, lastLevel.details);
}
if (!details.alignedSliding && lastLevel.details && !details.skippedSegments) {
// Try to align on sn so that we pick a better start fragment.
// Do not perform this on playlists with delta updates as this is only to align levels on switch
// and adjustSliding only adjusts fragments after skippedSegments.
Object(_controller_level_helper__WEBPACK_IMPORTED_MODULE_2__["adjustSliding"])(lastLevel.details, details);
}
}
/**
* Computes the PTS if a new level's fragments using the PTS of a fragment in the last level which shares the same
* discontinuity sequence.
* @param lastFrag - The last Fragment which shares the same discontinuity sequence
* @param lastLevel - The details of the last loaded level
* @param details - The details of the new level
*/
function alignDiscontinuities(lastFrag, details, lastLevel) {
if (shouldAlignOnDiscontinuities(lastFrag, lastLevel, details)) {
var referenceFrag = findDiscontinuousReferenceFrag(lastLevel.details, details);
if (referenceFrag && Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(referenceFrag.start)) {
_logger__WEBPACK_IMPORTED_MODULE_1__["logger"].log("Adjusting PTS using last level due to CC increase within current level " + details.url);
adjustSlidingStart(referenceFrag.start, details);
}
}
}
/**
* Computes the PTS of a new level's fragments using the difference in Program Date Time from the last level.
* @param details - The details of the new level
* @param lastDetails - The details of the last loaded level
*/
function alignPDT(details, lastDetails) {
// This check protects the unsafe "!" usage below for null program date time access.
if (!lastDetails.fragments.length || !details.hasProgramDateTime || !lastDetails.hasProgramDateTime) {
return;
} // if last level sliding is 1000 and its first frag PROGRAM-DATE-TIME is 2017-08-20 1:10:00 AM
// and if new details first frag PROGRAM DATE-TIME is 2017-08-20 1:10:08 AM
// then we can deduce that playlist B sliding is 1000+8 = 1008s
var lastPDT = lastDetails.fragments[0].programDateTime; // hasProgramDateTime check above makes this safe.
var newPDT = details.fragments[0].programDateTime; // date diff is in ms. frag.start is in seconds
var sliding = (newPDT - lastPDT) / 1000 + lastDetails.fragments[0].start;
if (sliding && Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(sliding)) {
_logger__WEBPACK_IMPORTED_MODULE_1__["logger"].log("Adjusting PTS using programDateTime delta " + (newPDT - lastPDT) + "ms, sliding:" + sliding.toFixed(3) + " " + details.url + " ");
adjustSlidingStart(sliding, details);
}
}
function alignFragmentByPDTDelta(frag, delta) {
var programDateTime = frag.programDateTime;
if (!programDateTime) return;
var start = (programDateTime - delta) / 1000;
frag.start = frag.startPTS = start;
frag.endPTS = start + frag.duration;
}
/**
* Ensures appropriate time-alignment between renditions based on PDT. Unlike `alignPDT`, which adjusts
* the timeline based on the delta between PDTs of the 0th fragment of two playlists/`LevelDetails`,
* this function assumes the timelines represented in `refDetails` are accurate, including the PDTs,
* and uses the "wallclock"/PDT timeline as a cross-reference to `details`, adjusting the presentation
* times/timelines of `details` accordingly.
* Given the asynchronous nature of fetches and initial loads of live `main` and audio/subtitle tracks,
* the primary purpose of this function is to ensure the "local timelines" of audio/subtitle tracks
* are aligned to the main/video timeline, using PDT as the cross-reference/"anchor" that should
* be consistent across playlists, per the HLS spec.
* @param details - The details of the rendition you'd like to time-align (e.g. an audio rendition).
* @param refDetails - The details of the reference rendition with start and PDT times for alignment.
*/
function alignMediaPlaylistByPDT(details, refDetails) {
// This check protects the unsafe "!" usage below for null program date time access.
if (!refDetails.fragments.length || !details.hasProgramDateTime || !refDetails.hasProgramDateTime) {
return;
}
var refPDT = refDetails.fragments[0].programDateTime; // hasProgramDateTime check above makes this safe.
var refStart = refDetails.fragments[0].start; // Use the delta between the reference details' presentation timeline's start time and its PDT
// to align the other rendtion's timeline.
var delta = refPDT - refStart * 1000; // Per spec: "If any Media Playlist in a Master Playlist contains an EXT-X-PROGRAM-DATE-TIME tag, then all
// Media Playlists in that Master Playlist MUST contain EXT-X-PROGRAM-DATE-TIME tags with consistent mappings
// of date and time to media timestamps."
// So we should be able to use each rendition's PDT as a reference time and use the delta to compute our relevant
// start and end times.
// NOTE: This code assumes each level/details timelines have already been made "internally consistent"
details.fragments.forEach(function (frag) {
alignFragmentByPDTDelta(frag, delta);
});
if (details.fragmentHint) {
alignFragmentByPDTDelta(details.fragmentHint, delta);
}
details.alignedSliding = true;
}
/***/ }),
/***/ "./src/utils/ewma-bandwidth-estimator.ts":
/*!***********************************************!*\
!*** ./src/utils/ewma-bandwidth-estimator.ts ***!
\***********************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _utils_ewma__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/ewma */ "./src/utils/ewma.ts");
/*
* EWMA Bandwidth Estimator
* - heavily inspired from shaka-player
* Tracks bandwidth samples and estimates available bandwidth.
* Based on the minimum of two exponentially-weighted moving averages with
* different half-lives.
*/
var EwmaBandWidthEstimator = /*#__PURE__*/function () {
function EwmaBandWidthEstimator(slow, fast, defaultEstimate) {
this.defaultEstimate_ = void 0;
this.minWeight_ = void 0;
this.minDelayMs_ = void 0;
this.slow_ = void 0;
this.fast_ = void 0;
this.defaultEstimate_ = defaultEstimate;
this.minWeight_ = 0.001;
this.minDelayMs_ = 50;
this.slow_ = new _utils_ewma__WEBPACK_IMPORTED_MODULE_0__["default"](slow);
this.fast_ = new _utils_ewma__WEBPACK_IMPORTED_MODULE_0__["default"](fast);
}
var _proto = EwmaBandWidthEstimator.prototype;
_proto.update = function update(slow, fast) {
var slow_ = this.slow_,
fast_ = this.fast_;
if (this.slow_.halfLife !== slow) {
this.slow_ = new _utils_ewma__WEBPACK_IMPORTED_MODULE_0__["default"](slow, slow_.getEstimate(), slow_.getTotalWeight());
}
if (this.fast_.halfLife !== fast) {
this.fast_ = new _utils_ewma__WEBPACK_IMPORTED_MODULE_0__["default"](fast, fast_.getEstimate(), fast_.getTotalWeight());
}
};
_proto.sample = function sample(durationMs, numBytes) {
durationMs = Math.max(durationMs, this.minDelayMs_);
var numBits = 8 * numBytes; // weight is duration in seconds
var durationS = durationMs / 1000; // value is bandwidth in bits/s
var bandwidthInBps = numBits / durationS;
this.fast_.sample(durationS, bandwidthInBps);
this.slow_.sample(durationS, bandwidthInBps);
};
_proto.canEstimate = function canEstimate() {
var fast = this.fast_;
return fast && fast.getTotalWeight() >= this.minWeight_;
};
_proto.getEstimate = function getEstimate() {
if (this.canEstimate()) {
// console.log('slow estimate:'+ Math.round(this.slow_.getEstimate()));
// console.log('fast estimate:'+ Math.round(this.fast_.getEstimate()));
// Take the minimum of these two estimates. This should have the effect of
// adapting down quickly, but up more slowly.
return Math.min(this.fast_.getEstimate(), this.slow_.getEstimate());
} else {
return this.defaultEstimate_;
}
};
_proto.destroy = function destroy() {};
return EwmaBandWidthEstimator;
}();
/* harmony default export */ __webpack_exports__["default"] = (EwmaBandWidthEstimator);
/***/ }),
/***/ "./src/utils/ewma.ts":
/*!***************************!*\
!*** ./src/utils/ewma.ts ***!
\***************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/*
* compute an Exponential Weighted moving average
* - https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average
* - heavily inspired from shaka-player
*/
var EWMA = /*#__PURE__*/function () {
// About half of the estimated value will be from the last |halfLife| samples by weight.
function EWMA(halfLife, estimate, weight) {
if (estimate === void 0) {
estimate = 0;
}
if (weight === void 0) {
weight = 0;
}
this.halfLife = void 0;
this.alpha_ = void 0;
this.estimate_ = void 0;
this.totalWeight_ = void 0;
this.halfLife = halfLife; // Larger values of alpha expire historical data more slowly.
this.alpha_ = halfLife ? Math.exp(Math.log(0.5) / halfLife) : 0;
this.estimate_ = estimate;
this.totalWeight_ = weight;
}
var _proto = EWMA.prototype;
_proto.sample = function sample(weight, value) {
var adjAlpha = Math.pow(this.alpha_, weight);
this.estimate_ = value * (1 - adjAlpha) + adjAlpha * this.estimate_;
this.totalWeight_ += weight;
};
_proto.getTotalWeight = function getTotalWeight() {
return this.totalWeight_;
};
_proto.getEstimate = function getEstimate() {
if (this.alpha_) {
var zeroFactor = 1 - Math.pow(this.alpha_, this.totalWeight_);
if (zeroFactor) {
return this.estimate_ / zeroFactor;
}
}
return this.estimate_;
};
return EWMA;
}();
/* harmony default export */ __webpack_exports__["default"] = (EWMA);
/***/ }),
/***/ "./src/utils/fetch-loader.ts":
/*!***********************************!*\
!*** ./src/utils/fetch-loader.ts ***!
\***********************************/
/*! exports provided: fetchSupported, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "fetchSupported", function() { return fetchSupported; });
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var _loader_load_stats__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../loader/load-stats */ "./src/loader/load-stats.ts");
/* harmony import */ var _demux_chunk_cache__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../demux/chunk-cache */ "./src/demux/chunk-cache.ts");
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); }
function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function fetchSupported() {
if ( // @ts-ignore
self.fetch && self.AbortController && self.ReadableStream && self.Request) {
try {
new self.ReadableStream({}); // eslint-disable-line no-new
return true;
} catch (e) {
/* noop */
}
}
return false;
}
var FetchLoader = /*#__PURE__*/function () {
function FetchLoader(config
/* HlsConfig */
) {
this.fetchSetup = void 0;
this.requestTimeout = void 0;
this.request = void 0;
this.response = void 0;
this.controller = void 0;
this.context = void 0;
this.config = null;
this.callbacks = null;
this.stats = void 0;
this.loader = null;
this.fetchSetup = config.fetchSetup || getRequest;
this.controller = new self.AbortController();
this.stats = new _loader_load_stats__WEBPACK_IMPORTED_MODULE_1__["LoadStats"]();
}
var _proto = FetchLoader.prototype;
_proto.destroy = function destroy() {
this.loader = this.callbacks = null;
this.abortInternal();
};
_proto.abortInternal = function abortInternal() {
var response = this.response;
if (!response || !response.ok) {
this.stats.aborted = true;
this.controller.abort();
}
};
_proto.abort = function abort() {
var _this$callbacks;
this.abortInternal();
if ((_this$callbacks = this.callbacks) !== null && _this$callbacks !== void 0 && _this$callbacks.onAbort) {
this.callbacks.onAbort(this.stats, this.context, this.response);
}
};
_proto.load = function load(context, config, callbacks) {
var _this = this;
var stats = this.stats;
if (stats.loading.start) {
throw new Error('Loader can only be used once.');
}
stats.loading.start = self.performance.now();
var initParams = getRequestParameters(context, this.controller.signal);
var onProgress = callbacks.onProgress;
var isArrayBuffer = context.responseType === 'arraybuffer';
var LENGTH = isArrayBuffer ? 'byteLength' : 'length';
this.context = context;
this.config = config;
this.callbacks = callbacks;
this.request = this.fetchSetup(context, initParams);
self.clearTimeout(this.requestTimeout);
this.requestTimeout = self.setTimeout(function () {
_this.abortInternal();
callbacks.onTimeout(stats, context, _this.response);
}, config.timeout);
self.fetch(this.request).then(function (response) {
_this.response = _this.loader = response;
if (!response.ok) {
var status = response.status,
statusText = response.statusText;
throw new FetchError(statusText || 'fetch, bad network response', status, response);
}
stats.loading.first = Math.max(self.performance.now(), stats.loading.start);
stats.total = parseInt(response.headers.get('Content-Length') || '0');
if (onProgress && Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(config.highWaterMark)) {
return _this.loadProgressively(response, stats, context, config.highWaterMark, onProgress);
}
if (isArrayBuffer) {
return response.arrayBuffer();
}
return response.text();
}).then(function (responseData) {
var response = _this.response;
self.clearTimeout(_this.requestTimeout);
stats.loading.end = Math.max(self.performance.now(), stats.loading.first);
stats.loaded = stats.total = responseData[LENGTH];
var loaderResponse = {
url: response.url,
data: responseData
};
if (onProgress && !Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(config.highWaterMark)) {
onProgress(stats, context, responseData, response);
}
callbacks.onSuccess(loaderResponse, stats, context, response);
}).catch(function (error) {
self.clearTimeout(_this.requestTimeout);
if (stats.aborted) {
return;
} // CORS errors result in an undefined code. Set it to 0 here to align with XHR's behavior
var code = error.code || 0;
callbacks.onError({
code: code,
text: error.message
}, context, error.details);
});
};
_proto.getCacheAge = function getCacheAge() {
var result = null;
if (this.response) {
var ageHeader = this.response.headers.get('age');
result = ageHeader ? parseFloat(ageHeader) : null;
}
return result;
};
_proto.loadProgressively = function loadProgressively(response, stats, context, highWaterMark, onProgress) {
if (highWaterMark === void 0) {
highWaterMark = 0;
}
var chunkCache = new _demux_chunk_cache__WEBPACK_IMPORTED_MODULE_2__["default"]();
var reader = response.body.getReader();
var pump = function pump() {
return reader.read().then(function (data) {
if (data.done) {
if (chunkCache.dataLength) {
onProgress(stats, context, chunkCache.flush(), response);
}
return Promise.resolve(new ArrayBuffer(0));
}
var chunk = data.value;
var len = chunk.length;
stats.loaded += len;
if (len < highWaterMark || chunkCache.dataLength) {
// The current chunk is too small to to be emitted or the cache already has data
// Push it to the cache
chunkCache.push(chunk);
if (chunkCache.dataLength >= highWaterMark) {
// flush in order to join the typed arrays
onProgress(stats, context, chunkCache.flush(), response);
}
} else {
// If there's nothing cached already, and the chache is large enough
// just emit the progress event
onProgress(stats, context, chunk, response);
}
return pump();
}).catch(function () {
/* aborted */
return Promise.reject();
});
};
return pump();
};
return FetchLoader;
}();
function getRequestParameters(context, signal) {
var initParams = {
method: 'GET',
mode: 'cors',
credentials: 'same-origin',
signal: signal,
headers: new self.Headers(_extends({}, context.headers))
};
if (context.rangeEnd) {
initParams.headers.set('Range', 'bytes=' + context.rangeStart + '-' + String(context.rangeEnd - 1));
}
return initParams;
}
function getRequest(context, initParams) {
return new self.Request(context.url, initParams);
}
var FetchError = /*#__PURE__*/function (_Error) {
_inheritsLoose(FetchError, _Error);
function FetchError(message, code, details) {
var _this2;
_this2 = _Error.call(this, message) || this;
_this2.code = void 0;
_this2.details = void 0;
_this2.code = code;
_this2.details = details;
return _this2;
}
return FetchError;
}( /*#__PURE__*/_wrapNativeSuper(Error));
/* harmony default export */ __webpack_exports__["default"] = (FetchLoader);
/***/ }),
/***/ "./src/utils/logger.ts":
/*!*****************************!*\
!*** ./src/utils/logger.ts ***!
\*****************************/
/*! exports provided: enableLogs, logger */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "enableLogs", function() { return enableLogs; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "logger", function() { return logger; });
var noop = function noop() {};
var fakeLogger = {
trace: noop,
debug: noop,
log: noop,
warn: noop,
info: noop,
error: noop
};
var exportedLogger = fakeLogger; // let lastCallTime;
// function formatMsgWithTimeInfo(type, msg) {
// const now = Date.now();
// const diff = lastCallTime ? '+' + (now - lastCallTime) : '0';
// lastCallTime = now;
// msg = (new Date(now)).toISOString() + ' | [' + type + '] > ' + msg + ' ( ' + diff + ' ms )';
// return msg;
// }
function consolePrintFn(type) {
var func = self.console[type];
if (func) {
return func.bind(self.console, "[" + type + "] >");
}
return noop;
}
function exportLoggerFunctions(debugConfig) {
for (var _len = arguments.length, functions = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
functions[_key - 1] = arguments[_key];
}
functions.forEach(function (type) {
exportedLogger[type] = debugConfig[type] ? debugConfig[type].bind(debugConfig) : consolePrintFn(type);
});
}
function enableLogs(debugConfig) {
// check that console is available
if (self.console && debugConfig === true || typeof debugConfig === 'object') {
exportLoggerFunctions(debugConfig, // Remove out from list here to hard-disable a log-level
// 'trace',
'debug', 'log', 'info', 'warn', 'error'); // Some browsers don't allow to use bind on console object anyway
// fallback to default if needed
try {
exportedLogger.log();
} catch (e) {
exportedLogger = fakeLogger;
}
} else {
exportedLogger = fakeLogger;
}
}
var logger = exportedLogger;
/***/ }),
/***/ "./src/utils/mediakeys-helper.ts":
/*!***************************************!*\
!*** ./src/utils/mediakeys-helper.ts ***!
\***************************************/
/*! exports provided: KeySystems, requestMediaKeySystemAccess */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "KeySystems", function() { return KeySystems; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "requestMediaKeySystemAccess", function() { return requestMediaKeySystemAccess; });
/**
* @see https://developer.mozilla.org/en-US/docs/Web/API/Navigator/requestMediaKeySystemAccess
*/
var KeySystems;
(function (KeySystems) {
KeySystems["WIDEVINE"] = "com.widevine.alpha";
KeySystems["PLAYREADY"] = "com.microsoft.playready";
})(KeySystems || (KeySystems = {}));
var requestMediaKeySystemAccess = function () {
if (typeof self !== 'undefined' && self.navigator && self.navigator.requestMediaKeySystemAccess) {
return self.navigator.requestMediaKeySystemAccess.bind(self.navigator);
} else {
return null;
}
}();
/***/ }),
/***/ "./src/utils/mediasource-helper.ts":
/*!*****************************************!*\
!*** ./src/utils/mediasource-helper.ts ***!
\*****************************************/
/*! exports provided: getMediaSource */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getMediaSource", function() { return getMediaSource; });
/**
* MediaSource helper
*/
function getMediaSource() {
return self.MediaSource || self.WebKitMediaSource;
}
/***/ }),
/***/ "./src/utils/mp4-tools.ts":
/*!********************************!*\
!*** ./src/utils/mp4-tools.ts ***!
\********************************/
/*! exports provided: bin2str, readUint16, readUint32, writeUint32, findBox, parseSegmentIndex, parseInitSegment, getStartDTS, getDuration, computeRawDurationFromSamples, offsetStartDTS, segmentValidRange, appendUint8Array */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "bin2str", function() { return bin2str; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "readUint16", function() { return readUint16; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "readUint32", function() { return readUint32; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "writeUint32", function() { return writeUint32; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findBox", function() { return findBox; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseSegmentIndex", function() { return parseSegmentIndex; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseInitSegment", function() { return parseInitSegment; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getStartDTS", function() { return getStartDTS; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getDuration", function() { return getDuration; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "computeRawDurationFromSamples", function() { return computeRawDurationFromSamples; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "offsetStartDTS", function() { return offsetStartDTS; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "segmentValidRange", function() { return segmentValidRange; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "appendUint8Array", function() { return appendUint8Array; });
/* harmony import */ var _typed_array__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./typed-array */ "./src/utils/typed-array.ts");
/* harmony import */ var _loader_fragment__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../loader/fragment */ "./src/loader/fragment.ts");
var UINT32_MAX = Math.pow(2, 32) - 1;
var push = [].push;
function bin2str(data) {
return String.fromCharCode.apply(null, data);
}
function readUint16(buffer, offset) {
if ('data' in buffer) {
offset += buffer.start;
buffer = buffer.data;
}
var val = buffer[offset] << 8 | buffer[offset + 1];
return val < 0 ? 65536 + val : val;
}
function readUint32(buffer, offset) {
if ('data' in buffer) {
offset += buffer.start;
buffer = buffer.data;
}
var val = buffer[offset] << 24 | buffer[offset + 1] << 16 | buffer[offset + 2] << 8 | buffer[offset + 3];
return val < 0 ? 4294967296 + val : val;
}
function writeUint32(buffer, offset, value) {
if ('data' in buffer) {
offset += buffer.start;
buffer = buffer.data;
}
buffer[offset] = value >> 24;
buffer[offset + 1] = value >> 16 & 0xff;
buffer[offset + 2] = value >> 8 & 0xff;
buffer[offset + 3] = value & 0xff;
} // Find the data for a box specified by its path
function findBox(input, path) {
var results = [];
if (!path.length) {
// short-circuit the search for empty paths
return results;
}
var data;
var start;
var end;
if ('data' in input) {
data = input.data;
start = input.start;
end = input.end;
} else {
data = input;
start = 0;
end = data.byteLength;
}
for (var i = start; i < end;) {
var size = readUint32(data, i);
var type = bin2str(data.subarray(i + 4, i + 8));
var endbox = size > 1 ? i + size : end;
if (type === path[0]) {
if (path.length === 1) {
// this is the end of the path and we've found the box we were
// looking for
results.push({
data: data,
start: i + 8,
end: endbox
});
} else {
// recursively search for the next box along the path
var subresults = findBox({
data: data,
start: i + 8,
end: endbox
}, path.slice(1));
if (subresults.length) {
push.apply(results, subresults);
}
}
}
i = endbox;
} // we've finished searching all of data
return results;
}
function parseSegmentIndex(initSegment) {
var moovBox = findBox(initSegment, ['moov']);
var moov = moovBox[0];
var moovEndOffset = moov ? moov.end : null; // we need this in case we need to chop of garbage of the end of current data
var sidxBox = findBox(initSegment, ['sidx']);
if (!sidxBox || !sidxBox[0]) {
return null;
}
var references = [];
var sidx = sidxBox[0];
var version = sidx.data[0]; // set initial offset, we skip the reference ID (not needed)
var index = version === 0 ? 8 : 16;
var timescale = readUint32(sidx, index);
index += 4; // TODO: parse earliestPresentationTime and firstOffset
// usually zero in our case
var earliestPresentationTime = 0;
var firstOffset = 0;
if (version === 0) {
index += 8;
} else {
index += 16;
} // skip reserved
index += 2;
var startByte = sidx.end + firstOffset;
var referencesCount = readUint16(sidx, index);
index += 2;
for (var i = 0; i < referencesCount; i++) {
var referenceIndex = index;
var referenceInfo = readUint32(sidx, referenceIndex);
referenceIndex += 4;
var referenceSize = referenceInfo & 0x7fffffff;
var referenceType = (referenceInfo & 0x80000000) >>> 31;
if (referenceType === 1) {
// eslint-disable-next-line no-console
console.warn('SIDX has hierarchical references (not supported)');
return null;
}
var subsegmentDuration = readUint32(sidx, referenceIndex);
referenceIndex += 4;
references.push({
referenceSize: referenceSize,
subsegmentDuration: subsegmentDuration,
// unscaled
info: {
duration: subsegmentDuration / timescale,
start: startByte,
end: startByte + referenceSize - 1
}
});
startByte += referenceSize; // Skipping 1 bit for |startsWithSap|, 3 bits for |sapType|, and 28 bits
// for |sapDelta|.
referenceIndex += 4; // skip to next ref
index = referenceIndex;
}
return {
earliestPresentationTime: earliestPresentationTime,
timescale: timescale,
version: version,
referencesCount: referencesCount,
references: references,
moovEndOffset: moovEndOffset
};
}
/**
* Parses an MP4 initialization segment and extracts stream type and
* timescale values for any declared tracks. Timescale values indicate the
* number of clock ticks per second to assume for time-based values
* elsewhere in the MP4.
*
* To determine the start time of an MP4, you need two pieces of
* information: the timescale unit and the earliest base media decode
* time. Multiple timescales can be specified within an MP4 but the
* base media decode time is always expressed in the timescale from
* the media header box for the track:
* ```
* moov > trak > mdia > mdhd.timescale
* moov > trak > mdia > hdlr
* ```
* @param initSegment {Uint8Array} the bytes of the init segment
* @return {InitData} a hash of track type to timescale values or null if
* the init segment is malformed.
*/
function parseInitSegment(initSegment) {
var result = [];
var traks = findBox(initSegment, ['moov', 'trak']);
for (var i = 0; i < traks.length; i++) {
var trak = traks[i];
var tkhd = findBox(trak, ['tkhd'])[0];
if (tkhd) {
var version = tkhd.data[tkhd.start];
var _index = version === 0 ? 12 : 20;
var trackId = readUint32(tkhd, _index);
var mdhd = findBox(trak, ['mdia', 'mdhd'])[0];
if (mdhd) {
version = mdhd.data[mdhd.start];
_index = version === 0 ? 12 : 20;
var timescale = readUint32(mdhd, _index);
var hdlr = findBox(trak, ['mdia', 'hdlr'])[0];
if (hdlr) {
var hdlrType = bin2str(hdlr.data.subarray(hdlr.start + 8, hdlr.start + 12));
var type = {
soun: _loader_fragment__WEBPACK_IMPORTED_MODULE_1__["ElementaryStreamTypes"].AUDIO,
vide: _loader_fragment__WEBPACK_IMPORTED_MODULE_1__["ElementaryStreamTypes"].VIDEO
}[hdlrType];
if (type) {
// Parse codec details
var stsd = findBox(trak, ['mdia', 'minf', 'stbl', 'stsd'])[0];
var codec = void 0;
if (stsd) {
codec = bin2str(stsd.data.subarray(stsd.start + 12, stsd.start + 16)); // TODO: Parse codec details to be able to build MIME type.
// stsd.start += 8;
// const codecBox = findBox(stsd, [codec])[0];
// if (codecBox) {
// TODO: Codec parsing support for avc1, mp4a, hevc, av01...
// }
}
result[trackId] = {
timescale: timescale,
type: type
};
result[type] = {
timescale: timescale,
id: trackId,
codec: codec
};
}
}
}
}
}
var trex = findBox(initSegment, ['moov', 'mvex', 'trex']);
trex.forEach(function (trex) {
var trackId = readUint32(trex, 4);
var track = result[trackId];
if (track) {
track.default = {
duration: readUint32(trex, 12),
flags: readUint32(trex, 20)
};
}
});
return result;
}
/**
* Determine the base media decode start time, in seconds, for an MP4
* fragment. If multiple fragments are specified, the earliest time is
* returned.
*
* The base media decode time can be parsed from track fragment
* metadata:
* ```
* moof > traf > tfdt.baseMediaDecodeTime
* ```
* It requires the timescale value from the mdhd to interpret.
*
* @param initData {InitData} a hash of track type to timescale values
* @param fmp4 {Uint8Array} the bytes of the mp4 fragment
* @return {number} the earliest base media decode start time for the
* fragment, in seconds
*/
function getStartDTS(initData, fmp4) {
// we need info from two children of each track fragment box
return findBox(fmp4, ['moof', 'traf']).reduce(function (result, traf) {
var tfdt = findBox(traf, ['tfdt'])[0];
var version = tfdt.data[tfdt.start];
var start = findBox(traf, ['tfhd']).reduce(function (result, tfhd) {
// get the track id from the tfhd
var id = readUint32(tfhd, 4);
var track = initData[id];
if (track) {
var baseTime = readUint32(tfdt, 4);
if (version === 1) {
baseTime *= Math.pow(2, 32);
baseTime += readUint32(tfdt, 8);
} // assume a 90kHz clock if no timescale was specified
var scale = track.timescale || 90e3; // convert base time to seconds
var startTime = baseTime / scale;
if (isFinite(startTime) && (result === null || startTime < result)) {
return startTime;
}
}
return result;
}, null);
if (start !== null && isFinite(start) && (result === null || start < result)) {
return start;
}
return result;
}, null) || 0;
}
/*
For Reference:
aligned(8) class TrackFragmentHeaderBox
extends FullBox(‘tfhd’, 0, tf_flags){
unsigned int(32) track_ID;
// all the following are optional fields
unsigned int(64) base_data_offset;
unsigned int(32) sample_description_index;
unsigned int(32) default_sample_duration;
unsigned int(32) default_sample_size;
unsigned int(32) default_sample_flags
}
*/
function getDuration(data, initData) {
var rawDuration = 0;
var videoDuration = 0;
var audioDuration = 0;
var trafs = findBox(data, ['moof', 'traf']);
for (var i = 0; i < trafs.length; i++) {
var traf = trafs[i]; // There is only one tfhd & trun per traf
// This is true for CMAF style content, and we should perhaps check the ftyp
// and only look for a single trun then, but for ISOBMFF we should check
// for multiple track runs.
var tfhd = findBox(traf, ['tfhd'])[0]; // get the track id from the tfhd
var id = readUint32(tfhd, 4);
var track = initData[id];
if (!track) {
continue;
}
var trackDefault = track.default;
var tfhdFlags = readUint32(tfhd, 0) | (trackDefault === null || trackDefault === void 0 ? void 0 : trackDefault.flags);
var sampleDuration = trackDefault === null || trackDefault === void 0 ? void 0 : trackDefault.duration;
if (tfhdFlags & 0x000008) {
// 0x000008 indicates the presence of the default_sample_duration field
if (tfhdFlags & 0x000002) {
// 0x000002 indicates the presence of the sample_description_index field, which precedes default_sample_duration
// If present, the default_sample_duration exists at byte offset 12
sampleDuration = readUint32(tfhd, 12);
} else {
// Otherwise, the duration is at byte offset 8
sampleDuration = readUint32(tfhd, 8);
}
} // assume a 90kHz clock if no timescale was specified
var timescale = track.timescale || 90e3;
var truns = findBox(traf, ['trun']);
for (var j = 0; j < truns.length; j++) {
if (sampleDuration) {
var sampleCount = readUint32(truns[j], 4);
rawDuration = sampleDuration * sampleCount;
} else {
rawDuration = computeRawDurationFromSamples(truns[j]);
}
if (track.type === _loader_fragment__WEBPACK_IMPORTED_MODULE_1__["ElementaryStreamTypes"].VIDEO) {
videoDuration += rawDuration / timescale;
} else if (track.type === _loader_fragment__WEBPACK_IMPORTED_MODULE_1__["ElementaryStreamTypes"].AUDIO) {
audioDuration += rawDuration / timescale;
}
}
}
if (videoDuration === 0 && audioDuration === 0) {
// If duration samples are not available in the traf use sidx subsegment_duration
var sidx = parseSegmentIndex(data);
if (sidx !== null && sidx !== void 0 && sidx.references) {
return sidx.references.reduce(function (dur, ref) {
return dur + ref.info.duration || 0;
}, 0);
}
}
if (videoDuration) {
return videoDuration;
}
return audioDuration;
}
/*
For Reference:
aligned(8) class TrackRunBox
extends FullBox(‘trun’, version, tr_flags) {
unsigned int(32) sample_count;
// the following are optional fields
signed int(32) data_offset;
unsigned int(32) first_sample_flags;
// all fields in the following array are optional
{
unsigned int(32) sample_duration;
unsigned int(32) sample_size;
unsigned int(32) sample_flags
if (version == 0)
{ unsigned int(32)
else
{ signed int(32)
}[ sample_count ]
}
*/
function computeRawDurationFromSamples(trun) {
var flags = readUint32(trun, 0); // Flags are at offset 0, non-optional sample_count is at offset 4. Therefore we start 8 bytes in.
// Each field is an int32, which is 4 bytes
var offset = 8; // data-offset-present flag
if (flags & 0x000001) {
offset += 4;
} // first-sample-flags-present flag
if (flags & 0x000004) {
offset += 4;
}
var duration = 0;
var sampleCount = readUint32(trun, 4);
for (var i = 0; i < sampleCount; i++) {
// sample-duration-present flag
if (flags & 0x000100) {
var sampleDuration = readUint32(trun, offset);
duration += sampleDuration;
offset += 4;
} // sample-size-present flag
if (flags & 0x000200) {
offset += 4;
} // sample-flags-present flag
if (flags & 0x000400) {
offset += 4;
} // sample-composition-time-offsets-present flag
if (flags & 0x000800) {
offset += 4;
}
}
return duration;
}
function offsetStartDTS(initData, fmp4, timeOffset) {
findBox(fmp4, ['moof', 'traf']).forEach(function (traf) {
findBox(traf, ['tfhd']).forEach(function (tfhd) {
// get the track id from the tfhd
var id = readUint32(tfhd, 4);
var track = initData[id];
if (!track) {
return;
} // assume a 90kHz clock if no timescale was specified
var timescale = track.timescale || 90e3; // get the base media decode time from the tfdt
findBox(traf, ['tfdt']).forEach(function (tfdt) {
var version = tfdt.data[tfdt.start];
var baseMediaDecodeTime = readUint32(tfdt, 4);
if (version === 0) {
writeUint32(tfdt, 4, baseMediaDecodeTime - timeOffset * timescale);
} else {
baseMediaDecodeTime *= Math.pow(2, 32);
baseMediaDecodeTime += readUint32(tfdt, 8);
baseMediaDecodeTime -= timeOffset * timescale;
baseMediaDecodeTime = Math.max(baseMediaDecodeTime, 0);
var upper = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1));
var lower = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1));
writeUint32(tfdt, 4, upper);
writeUint32(tfdt, 8, lower);
}
});
});
});
} // TODO: Check if the last moof+mdat pair is part of the valid range
function segmentValidRange(data) {
var segmentedRange = {
valid: null,
remainder: null
};
var moofs = findBox(data, ['moof']);
if (!moofs) {
return segmentedRange;
} else if (moofs.length < 2) {
segmentedRange.remainder = data;
return segmentedRange;
}
var last = moofs[moofs.length - 1]; // Offset by 8 bytes; findBox offsets the start by as much
segmentedRange.valid = Object(_typed_array__WEBPACK_IMPORTED_MODULE_0__["sliceUint8"])(data, 0, last.start - 8);
segmentedRange.remainder = Object(_typed_array__WEBPACK_IMPORTED_MODULE_0__["sliceUint8"])(data, last.start - 8);
return segmentedRange;
}
function appendUint8Array(data1, data2) {
var temp = new Uint8Array(data1.length + data2.length);
temp.set(data1);
temp.set(data2, data1.length);
return temp;
}
/***/ }),
/***/ "./src/utils/texttrack-utils.ts":
/*!**************************************!*\
!*** ./src/utils/texttrack-utils.ts ***!
\**************************************/
/*! exports provided: sendAddTrackEvent, addCueToTrack, clearCurrentCues, removeCuesInRange, getCuesInRange */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sendAddTrackEvent", function() { return sendAddTrackEvent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "addCueToTrack", function() { return addCueToTrack; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "clearCurrentCues", function() { return clearCurrentCues; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "removeCuesInRange", function() { return removeCuesInRange; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getCuesInRange", function() { return getCuesInRange; });
/* harmony import */ var _logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./logger */ "./src/utils/logger.ts");
function sendAddTrackEvent(track, videoEl) {
var event;
try {
event = new Event('addtrack');
} catch (err) {
// for IE11
event = document.createEvent('Event');
event.initEvent('addtrack', false, false);
}
event.track = track;
videoEl.dispatchEvent(event);
}
function addCueToTrack(track, cue) {
// Sometimes there are cue overlaps on segmented vtts so the same
// cue can appear more than once in different vtt files.
// This avoid showing duplicated cues with same timecode and text.
var mode = track.mode;
if (mode === 'disabled') {
track.mode = 'hidden';
}
if (track.cues && !track.cues.getCueById(cue.id)) {
try {
track.addCue(cue);
if (!track.cues.getCueById(cue.id)) {
throw new Error("addCue is failed for: " + cue);
}
} catch (err) {
_logger__WEBPACK_IMPORTED_MODULE_0__["logger"].debug("[texttrack-utils]: " + err);
var textTrackCue = new self.TextTrackCue(cue.startTime, cue.endTime, cue.text);
textTrackCue.id = cue.id;
track.addCue(textTrackCue);
}
}
if (mode === 'disabled') {
track.mode = mode;
}
}
function clearCurrentCues(track) {
// When track.mode is disabled, track.cues will be null.
// To guarantee the removal of cues, we need to temporarily
// change the mode to hidden
var mode = track.mode;
if (mode === 'disabled') {
track.mode = 'hidden';
}
if (track.cues) {
for (var i = track.cues.length; i--;) {
track.removeCue(track.cues[i]);
}
}
if (mode === 'disabled') {
track.mode = mode;
}
}
function removeCuesInRange(track, start, end) {
var mode = track.mode;
if (mode === 'disabled') {
track.mode = 'hidden';
}
if (track.cues && track.cues.length > 0) {
var cues = getCuesInRange(track.cues, start, end);
for (var i = 0; i < cues.length; i++) {
track.removeCue(cues[i]);
}
}
if (mode === 'disabled') {
track.mode = mode;
}
} // Find first cue starting after given time.
// Modified version of binary search O(log(n)).
function getFirstCueIndexAfterTime(cues, time) {
// If first cue starts after time, start there
if (time < cues[0].startTime) {
return 0;
} // If the last cue ends before time there is no overlap
var len = cues.length - 1;
if (time > cues[len].endTime) {
return -1;
}
var left = 0;
var right = len;
while (left <= right) {
var mid = Math.floor((right + left) / 2);
if (time < cues[mid].startTime) {
right = mid - 1;
} else if (time > cues[mid].startTime && left < len) {
left = mid + 1;
} else {
// If it's not lower or higher, it must be equal.
return mid;
}
} // At this point, left and right have swapped.
// No direct match was found, left or right element must be the closest. Check which one has the smallest diff.
return cues[left].startTime - time < time - cues[right].startTime ? left : right;
}
function getCuesInRange(cues, start, end) {
var cuesFound = [];
var firstCueInRange = getFirstCueIndexAfterTime(cues, start);
if (firstCueInRange > -1) {
for (var i = firstCueInRange, len = cues.length; i < len; i++) {
var cue = cues[i];
if (cue.startTime >= start && cue.endTime <= end) {
cuesFound.push(cue);
} else if (cue.startTime > end) {
return cuesFound;
}
}
}
return cuesFound;
}
/***/ }),
/***/ "./src/utils/time-ranges.ts":
/*!**********************************!*\
!*** ./src/utils/time-ranges.ts ***!
\**********************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/**
* TimeRanges to string helper
*/
var TimeRanges = {
toString: function toString(r) {
var log = '';
var len = r.length;
for (var i = 0; i < len; i++) {
log += '[' + r.start(i).toFixed(3) + ',' + r.end(i).toFixed(3) + ']';
}
return log;
}
};
/* harmony default export */ __webpack_exports__["default"] = (TimeRanges);
/***/ }),
/***/ "./src/utils/timescale-conversion.ts":
/*!*******************************************!*\
!*** ./src/utils/timescale-conversion.ts ***!
\*******************************************/
/*! exports provided: toTimescaleFromBase, toTimescaleFromScale, toMsFromMpegTsClock, toMpegTsClockFromTimescale */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toTimescaleFromBase", function() { return toTimescaleFromBase; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toTimescaleFromScale", function() { return toTimescaleFromScale; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toMsFromMpegTsClock", function() { return toMsFromMpegTsClock; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toMpegTsClockFromTimescale", function() { return toMpegTsClockFromTimescale; });
var MPEG_TS_CLOCK_FREQ_HZ = 90000;
function toTimescaleFromBase(value, destScale, srcBase, round) {
if (srcBase === void 0) {
srcBase = 1;
}
if (round === void 0) {
round = false;
}
var result = value * destScale * srcBase; // equivalent to `(value * scale) / (1 / base)`
return round ? Math.round(result) : result;
}
function toTimescaleFromScale(value, destScale, srcScale, round) {
if (srcScale === void 0) {
srcScale = 1;
}
if (round === void 0) {
round = false;
}
return toTimescaleFromBase(value, destScale, 1 / srcScale, round);
}
function toMsFromMpegTsClock(value, round) {
if (round === void 0) {
round = false;
}
return toTimescaleFromBase(value, 1000, 1 / MPEG_TS_CLOCK_FREQ_HZ, round);
}
function toMpegTsClockFromTimescale(value, srcScale) {
if (srcScale === void 0) {
srcScale = 1;
}
return toTimescaleFromBase(value, MPEG_TS_CLOCK_FREQ_HZ, 1 / srcScale);
}
/***/ }),
/***/ "./src/utils/typed-array.ts":
/*!**********************************!*\
!*** ./src/utils/typed-array.ts ***!
\**********************************/
/*! exports provided: sliceUint8 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sliceUint8", function() { return sliceUint8; });
function sliceUint8(array, start, end) {
// @ts-expect-error This polyfills IE11 usage of Uint8Array slice.
// It always exists in the TypeScript definition so fails, but it fails at runtime on IE11.
return Uint8Array.prototype.slice ? array.slice(start, end) : new Uint8Array(Array.prototype.slice.call(array, start, end));
}
/***/ }),
/***/ "./src/utils/xhr-loader.ts":
/*!*********************************!*\
!*** ./src/utils/xhr-loader.ts ***!
\*********************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/* harmony import */ var _loader_load_stats__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../loader/load-stats */ "./src/loader/load-stats.ts");
var AGE_HEADER_LINE_REGEX = /^age:\s*[\d.]+\s*$/m;
var XhrLoader = /*#__PURE__*/function () {
function XhrLoader(config
/* HlsConfig */
) {
this.xhrSetup = void 0;
this.requestTimeout = void 0;
this.retryTimeout = void 0;
this.retryDelay = void 0;
this.config = null;
this.callbacks = null;
this.context = void 0;
this.loader = null;
this.stats = void 0;
this.xhrSetup = config ? config.xhrSetup : null;
this.stats = new _loader_load_stats__WEBPACK_IMPORTED_MODULE_1__["LoadStats"]();
this.retryDelay = 0;
}
var _proto = XhrLoader.prototype;
_proto.destroy = function destroy() {
this.callbacks = null;
this.abortInternal();
this.loader = null;
this.config = null;
};
_proto.abortInternal = function abortInternal() {
var loader = this.loader;
self.clearTimeout(this.requestTimeout);
self.clearTimeout(this.retryTimeout);
if (loader) {
loader.onreadystatechange = null;
loader.onprogress = null;
if (loader.readyState !== 4) {
this.stats.aborted = true;
loader.abort();
}
}
};
_proto.abort = function abort() {
var _this$callbacks;
this.abortInternal();
if ((_this$callbacks = this.callbacks) !== null && _this$callbacks !== void 0 && _this$callbacks.onAbort) {
this.callbacks.onAbort(this.stats, this.context, this.loader);
}
};
_proto.load = function load(context, config, callbacks) {
if (this.stats.loading.start) {
throw new Error('Loader can only be used once.');
}
this.stats.loading.start = self.performance.now();
this.context = context;
this.config = config;
this.callbacks = callbacks;
this.retryDelay = config.retryDelay;
this.loadInternal();
};
_proto.loadInternal = function loadInternal() {
var config = this.config,
context = this.context;
if (!config) {
return;
}
var xhr = this.loader = new self.XMLHttpRequest();
var stats = this.stats;
stats.loading.first = 0;
stats.loaded = 0;
var xhrSetup = this.xhrSetup;
try {
if (xhrSetup) {
try {
xhrSetup(xhr, context.url);
} catch (e) {
// fix xhrSetup: (xhr, url) => {xhr.setRequestHeader("Content-Language", "test");}
// not working, as xhr.setRequestHeader expects xhr.readyState === OPEN
xhr.open('GET', context.url, true);
xhrSetup(xhr, context.url);
}
}
if (!xhr.readyState) {
xhr.open('GET', context.url, true);
}
var headers = this.context.headers;
if (headers) {
for (var header in headers) {
xhr.setRequestHeader(header, headers[header]);
}
}
} catch (e) {
// IE11 throws an exception on xhr.open if attempting to access an HTTP resource over HTTPS
this.callbacks.onError({
code: xhr.status,
text: e.message
}, context, xhr);
return;
}
if (context.rangeEnd) {
xhr.setRequestHeader('Range', 'bytes=' + context.rangeStart + '-' + (context.rangeEnd - 1));
}
xhr.onreadystatechange = this.readystatechange.bind(this);
xhr.onprogress = this.loadprogress.bind(this);
xhr.responseType = context.responseType; // setup timeout before we perform request
self.clearTimeout(this.requestTimeout);
this.requestTimeout = self.setTimeout(this.loadtimeout.bind(this), config.timeout);
xhr.send();
};
_proto.readystatechange = function readystatechange() {
var context = this.context,
xhr = this.loader,
stats = this.stats;
if (!context || !xhr) {
return;
}
var readyState = xhr.readyState;
var config = this.config; // don't proceed if xhr has been aborted
if (stats.aborted) {
return;
} // >= HEADERS_RECEIVED
if (readyState >= 2) {
// clear xhr timeout and rearm it if readyState less than 4
self.clearTimeout(this.requestTimeout);
if (stats.loading.first === 0) {
stats.loading.first = Math.max(self.performance.now(), stats.loading.start);
}
if (readyState === 4) {
xhr.onreadystatechange = null;
xhr.onprogress = null;
var status = xhr.status; // http status between 200 to 299 are all successful
if (status >= 200 && status < 300) {
stats.loading.end = Math.max(self.performance.now(), stats.loading.first);
var data;
var len;
if (context.responseType === 'arraybuffer') {
data = xhr.response;
len = data.byteLength;
} else {
data = xhr.responseText;
len = data.length;
}
stats.loaded = stats.total = len;
if (!this.callbacks) {
return;
}
var onProgress = this.callbacks.onProgress;
if (onProgress) {
onProgress(stats, context, data, xhr);
}
if (!this.callbacks) {
return;
}
var response = {
url: xhr.responseURL,
data: data
};
this.callbacks.onSuccess(response, stats, context, xhr);
} else {
// if max nb of retries reached or if http status between 400 and 499 (such error cannot be recovered, retrying is useless), return error
if (stats.retry >= config.maxRetry || status >= 400 && status < 499) {
_utils_logger__WEBPACK_IMPORTED_MODULE_0__["logger"].error(status + " while loading " + context.url);
this.callbacks.onError({
code: status,
text: xhr.statusText
}, context, xhr);
} else {
// retry
_utils_logger__WEBPACK_IMPORTED_MODULE_0__["logger"].warn(status + " while loading " + context.url + ", retrying in " + this.retryDelay + "..."); // abort and reset internal state
this.abortInternal();
this.loader = null; // schedule retry
self.clearTimeout(this.retryTimeout);
this.retryTimeout = self.setTimeout(this.loadInternal.bind(this), this.retryDelay); // set exponential backoff
this.retryDelay = Math.min(2 * this.retryDelay, config.maxRetryDelay);
stats.retry++;
}
}
} else {
// readyState >= 2 AND readyState !==4 (readyState = HEADERS_RECEIVED || LOADING) rearm timeout as xhr not finished yet
self.clearTimeout(this.requestTimeout);
this.requestTimeout = self.setTimeout(this.loadtimeout.bind(this), config.timeout);
}
}
};
_proto.loadtimeout = function loadtimeout() {
_utils_logger__WEBPACK_IMPORTED_MODULE_0__["logger"].warn("timeout while loading " + this.context.url);
var callbacks = this.callbacks;
if (callbacks) {
this.abortInternal();
callbacks.onTimeout(this.stats, this.context, this.loader);
}
};
_proto.loadprogress = function loadprogress(event) {
var stats = this.stats;
stats.loaded = event.loaded;
if (event.lengthComputable) {
stats.total = event.total;
}
};
_proto.getCacheAge = function getCacheAge() {
var result = null;
if (this.loader && AGE_HEADER_LINE_REGEX.test(this.loader.getAllResponseHeaders())) {
var ageHeader = this.loader.getResponseHeader('age');
result = ageHeader ? parseFloat(ageHeader) : null;
}
return result;
};
return XhrLoader;
}();
/* harmony default export */ __webpack_exports__["default"] = (XhrLoader);
/***/ })
/******/ })["default"];
});
//# sourceMappingURL=hls.light.js.map |
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.Konva = factory());
})(this, (function () { 'use strict';
/*
* Konva JavaScript Framework v8.3.1
* http://konvajs.org/
* Licensed under the MIT
* Date: Thu Dec 09 2021
*
* Original work Copyright (C) 2011 - 2013 by Eric Rowell (KineticJS)
* Modified work Copyright (C) 2014 - present by Anton Lavrenov (Konva)
*
* @license
*/
var PI_OVER_180 = Math.PI / 180;
/**
* @namespace Konva
*/
function detectBrowser() {
return (typeof window !== 'undefined' &&
// browser case
({}.toString.call(window) === '[object Window]' ||
// electron case
{}.toString.call(window) === '[object global]'));
}
const glob = typeof global !== 'undefined'
? global
: typeof window !== 'undefined'
? window
: typeof WorkerGlobalScope !== 'undefined'
? self
: {};
const Konva$2 = {
_global: glob,
version: '8.3.1',
isBrowser: detectBrowser(),
isUnminified: /param/.test(function (param) { }.toString()),
dblClickWindow: 400,
getAngle(angle) {
return Konva$2.angleDeg ? angle * PI_OVER_180 : angle;
},
enableTrace: false,
pointerEventsEnabled: true,
/**
* Should Konva automatically update canvas on any changes. Default is true.
* @property autoDrawEnabled
* @default true
* @name autoDrawEnabled
* @memberof Konva
* @example
* Konva.autoDrawEnabled = true;
*/
autoDrawEnabled: true,
/**
* Should we enable hit detection while dragging? For performance reasons, by default it is false.
* But on some rare cases you want to see hit graph and check intersections. Just set it to true.
* @property hitOnDragEnabled
* @default false
* @name hitOnDragEnabled
* @memberof Konva
* @example
* Konva.hitOnDragEnabled = true;
*/
hitOnDragEnabled: false,
/**
* Should we capture touch events and bind them to the touchstart target? That is how it works on DOM elements.
* The case: we touchstart on div1, then touchmove out of that element into another element div2.
* DOM will continue trigger touchmove events on div1 (not div2). Because events are "captured" into initial target.
* By default Konva do not do that and will trigger touchmove on another element, while pointer is moving.
* @property capturePointerEventsEnabled
* @default false
* @name capturePointerEventsEnabled
* @memberof Konva
* @example
* Konva.capturePointerEventsEnabled = true;
*/
capturePointerEventsEnabled: false,
_mouseListenClick: false,
_touchListenClick: false,
_pointerListenClick: false,
_mouseInDblClickWindow: false,
_touchInDblClickWindow: false,
_pointerInDblClickWindow: false,
_mouseDblClickPointerId: null,
_touchDblClickPointerId: null,
_pointerDblClickPointerId: null,
/**
* Global pixel ratio configuration. KonvaJS automatically detect pixel ratio of current device.
* But you may override such property, if you want to use your value. Set this value before any components initializations.
* @property pixelRatio
* @default undefined
* @name pixelRatio
* @memberof Konva
* @example
* // before any Konva code:
* Konva.pixelRatio = 1;
*/
pixelRatio: (typeof window !== 'undefined' && window.devicePixelRatio) || 1,
/**
* Drag distance property. If you start to drag a node you may want to wait until pointer is moved to some distance from start point,
* only then start dragging. Default is 3px.
* @property dragDistance
* @default 0
* @memberof Konva
* @example
* Konva.dragDistance = 10;
*/
dragDistance: 3,
/**
* Use degree values for angle properties. You may set this property to false if you want to use radian values.
* @property angleDeg
* @default true
* @memberof Konva
* @example
* node.rotation(45); // 45 degrees
* Konva.angleDeg = false;
* node.rotation(Math.PI / 2); // PI/2 radian
*/
angleDeg: true,
/**
* Show different warnings about errors or wrong API usage
* @property showWarnings
* @default true
* @memberof Konva
* @example
* Konva.showWarnings = false;
*/
showWarnings: true,
/**
* Configure what mouse buttons can be used for drag and drop.
* Default value is [0] - only left mouse button.
* @property dragButtons
* @default true
* @memberof Konva
* @example
* // enable left and right mouse buttons
* Konva.dragButtons = [0, 2];
*/
dragButtons: [0, 1],
/**
* returns whether or not drag and drop is currently active
* @method
* @memberof Konva
*/
isDragging() {
return Konva$2['DD'].isDragging;
},
/**
* returns whether or not a drag and drop operation is ready, but may
* not necessarily have started
* @method
* @memberof Konva
*/
isDragReady() {
return !!Konva$2['DD'].node;
},
// user agent
document: glob.document,
// insert Konva into global namespace (window)
// it is required for npm packages
_injectGlobal(Konva) {
glob.Konva = Konva;
},
};
const _registerNode = (NodeClass) => {
Konva$2[NodeClass.prototype.getClassName()] = NodeClass;
};
Konva$2._injectGlobal(Konva$2);
/*
* Last updated November 2011
* By Simon Sarris
* www.simonsarris.com
* sarris@acm.org
*
* Free to use and distribute at will
* So long as you are nice to people, etc
*/
/*
* The usage of this class was inspired by some of the work done by a forked
* project, KineticJS-Ext by Wappworks, which is based on Simon's Transform
* class. Modified by Eric Rowell
*/
/**
* Transform constructor.
* In most of the cases you don't need to use it in your app. Because it is for internal usage in Konva core.
* But there is a documentation for that class in case you still want
* to make some manual calculations.
* @constructor
* @param {Array} [m] Optional six-element matrix
* @memberof Konva
*/
class Transform {
constructor(m = [1, 0, 0, 1, 0, 0]) {
this.dirty = false;
this.m = (m && m.slice()) || [1, 0, 0, 1, 0, 0];
}
reset() {
this.m[0] = 1;
this.m[1] = 0;
this.m[2] = 0;
this.m[3] = 1;
this.m[4] = 0;
this.m[5] = 0;
}
/**
* Copy Konva.Transform object
* @method
* @name Konva.Transform#copy
* @returns {Konva.Transform}
* @example
* const tr = shape.getTransform().copy()
*/
copy() {
return new Transform(this.m);
}
copyInto(tr) {
tr.m[0] = this.m[0];
tr.m[1] = this.m[1];
tr.m[2] = this.m[2];
tr.m[3] = this.m[3];
tr.m[4] = this.m[4];
tr.m[5] = this.m[5];
}
/**
* Transform point
* @method
* @name Konva.Transform#point
* @param {Object} point 2D point(x, y)
* @returns {Object} 2D point(x, y)
*/
point(point) {
var m = this.m;
return {
x: m[0] * point.x + m[2] * point.y + m[4],
y: m[1] * point.x + m[3] * point.y + m[5],
};
}
/**
* Apply translation
* @method
* @name Konva.Transform#translate
* @param {Number} x
* @param {Number} y
* @returns {Konva.Transform}
*/
translate(x, y) {
this.m[4] += this.m[0] * x + this.m[2] * y;
this.m[5] += this.m[1] * x + this.m[3] * y;
return this;
}
/**
* Apply scale
* @method
* @name Konva.Transform#scale
* @param {Number} sx
* @param {Number} sy
* @returns {Konva.Transform}
*/
scale(sx, sy) {
this.m[0] *= sx;
this.m[1] *= sx;
this.m[2] *= sy;
this.m[3] *= sy;
return this;
}
/**
* Apply rotation
* @method
* @name Konva.Transform#rotate
* @param {Number} rad Angle in radians
* @returns {Konva.Transform}
*/
rotate(rad) {
var c = Math.cos(rad);
var s = Math.sin(rad);
var m11 = this.m[0] * c + this.m[2] * s;
var m12 = this.m[1] * c + this.m[3] * s;
var m21 = this.m[0] * -s + this.m[2] * c;
var m22 = this.m[1] * -s + this.m[3] * c;
this.m[0] = m11;
this.m[1] = m12;
this.m[2] = m21;
this.m[3] = m22;
return this;
}
/**
* Returns the translation
* @method
* @name Konva.Transform#getTranslation
* @returns {Object} 2D point(x, y)
*/
getTranslation() {
return {
x: this.m[4],
y: this.m[5],
};
}
/**
* Apply skew
* @method
* @name Konva.Transform#skew
* @param {Number} sx
* @param {Number} sy
* @returns {Konva.Transform}
*/
skew(sx, sy) {
var m11 = this.m[0] + this.m[2] * sy;
var m12 = this.m[1] + this.m[3] * sy;
var m21 = this.m[2] + this.m[0] * sx;
var m22 = this.m[3] + this.m[1] * sx;
this.m[0] = m11;
this.m[1] = m12;
this.m[2] = m21;
this.m[3] = m22;
return this;
}
/**
* Transform multiplication
* @method
* @name Konva.Transform#multiply
* @param {Konva.Transform} matrix
* @returns {Konva.Transform}
*/
multiply(matrix) {
var m11 = this.m[0] * matrix.m[0] + this.m[2] * matrix.m[1];
var m12 = this.m[1] * matrix.m[0] + this.m[3] * matrix.m[1];
var m21 = this.m[0] * matrix.m[2] + this.m[2] * matrix.m[3];
var m22 = this.m[1] * matrix.m[2] + this.m[3] * matrix.m[3];
var dx = this.m[0] * matrix.m[4] + this.m[2] * matrix.m[5] + this.m[4];
var dy = this.m[1] * matrix.m[4] + this.m[3] * matrix.m[5] + this.m[5];
this.m[0] = m11;
this.m[1] = m12;
this.m[2] = m21;
this.m[3] = m22;
this.m[4] = dx;
this.m[5] = dy;
return this;
}
/**
* Invert the matrix
* @method
* @name Konva.Transform#invert
* @returns {Konva.Transform}
*/
invert() {
var d = 1 / (this.m[0] * this.m[3] - this.m[1] * this.m[2]);
var m0 = this.m[3] * d;
var m1 = -this.m[1] * d;
var m2 = -this.m[2] * d;
var m3 = this.m[0] * d;
var m4 = d * (this.m[2] * this.m[5] - this.m[3] * this.m[4]);
var m5 = d * (this.m[1] * this.m[4] - this.m[0] * this.m[5]);
this.m[0] = m0;
this.m[1] = m1;
this.m[2] = m2;
this.m[3] = m3;
this.m[4] = m4;
this.m[5] = m5;
return this;
}
/**
* return matrix
* @method
* @name Konva.Transform#getMatrix
*/
getMatrix() {
return this.m;
}
/**
* set to absolute position via translation
* @method
* @name Konva.Transform#setAbsolutePosition
* @returns {Konva.Transform}
* @author ericdrowell
*/
setAbsolutePosition(x, y) {
var m0 = this.m[0], m1 = this.m[1], m2 = this.m[2], m3 = this.m[3], m4 = this.m[4], m5 = this.m[5], yt = (m0 * (y - m5) - m1 * (x - m4)) / (m0 * m3 - m1 * m2), xt = (x - m4 - m2 * yt) / m0;
return this.translate(xt, yt);
}
/**
* convert transformation matrix back into node's attributes
* @method
* @name Konva.Transform#decompose
* @returns {Konva.Transform}
*/
decompose() {
var a = this.m[0];
var b = this.m[1];
var c = this.m[2];
var d = this.m[3];
var e = this.m[4];
var f = this.m[5];
var delta = a * d - b * c;
let result = {
x: e,
y: f,
rotation: 0,
scaleX: 0,
scaleY: 0,
skewX: 0,
skewY: 0,
};
// Apply the QR-like decomposition.
if (a != 0 || b != 0) {
var r = Math.sqrt(a * a + b * b);
result.rotation = b > 0 ? Math.acos(a / r) : -Math.acos(a / r);
result.scaleX = r;
result.scaleY = delta / r;
result.skewX = (a * c + b * d) / delta;
result.skewY = 0;
}
else if (c != 0 || d != 0) {
var s = Math.sqrt(c * c + d * d);
result.rotation =
Math.PI / 2 - (d > 0 ? Math.acos(-c / s) : -Math.acos(c / s));
result.scaleX = delta / s;
result.scaleY = s;
result.skewX = 0;
result.skewY = (a * c + b * d) / delta;
}
else ;
result.rotation = Util._getRotation(result.rotation);
return result;
}
}
// CONSTANTS
var OBJECT_ARRAY = '[object Array]', OBJECT_NUMBER = '[object Number]', OBJECT_STRING = '[object String]', OBJECT_BOOLEAN = '[object Boolean]', PI_OVER_DEG180 = Math.PI / 180, DEG180_OVER_PI = 180 / Math.PI, HASH$1 = '#', EMPTY_STRING$1 = '', ZERO = '0', KONVA_WARNING = 'Konva warning: ', KONVA_ERROR = 'Konva error: ', RGB_PAREN = 'rgb(', COLORS = {
aliceblue: [240, 248, 255],
antiquewhite: [250, 235, 215],
aqua: [0, 255, 255],
aquamarine: [127, 255, 212],
azure: [240, 255, 255],
beige: [245, 245, 220],
bisque: [255, 228, 196],
black: [0, 0, 0],
blanchedalmond: [255, 235, 205],
blue: [0, 0, 255],
blueviolet: [138, 43, 226],
brown: [165, 42, 42],
burlywood: [222, 184, 135],
cadetblue: [95, 158, 160],
chartreuse: [127, 255, 0],
chocolate: [210, 105, 30],
coral: [255, 127, 80],
cornflowerblue: [100, 149, 237],
cornsilk: [255, 248, 220],
crimson: [220, 20, 60],
cyan: [0, 255, 255],
darkblue: [0, 0, 139],
darkcyan: [0, 139, 139],
darkgoldenrod: [184, 132, 11],
darkgray: [169, 169, 169],
darkgreen: [0, 100, 0],
darkgrey: [169, 169, 169],
darkkhaki: [189, 183, 107],
darkmagenta: [139, 0, 139],
darkolivegreen: [85, 107, 47],
darkorange: [255, 140, 0],
darkorchid: [153, 50, 204],
darkred: [139, 0, 0],
darksalmon: [233, 150, 122],
darkseagreen: [143, 188, 143],
darkslateblue: [72, 61, 139],
darkslategray: [47, 79, 79],
darkslategrey: [47, 79, 79],
darkturquoise: [0, 206, 209],
darkviolet: [148, 0, 211],
deeppink: [255, 20, 147],
deepskyblue: [0, 191, 255],
dimgray: [105, 105, 105],
dimgrey: [105, 105, 105],
dodgerblue: [30, 144, 255],
firebrick: [178, 34, 34],
floralwhite: [255, 255, 240],
forestgreen: [34, 139, 34],
fuchsia: [255, 0, 255],
gainsboro: [220, 220, 220],
ghostwhite: [248, 248, 255],
gold: [255, 215, 0],
goldenrod: [218, 165, 32],
gray: [128, 128, 128],
green: [0, 128, 0],
greenyellow: [173, 255, 47],
grey: [128, 128, 128],
honeydew: [240, 255, 240],
hotpink: [255, 105, 180],
indianred: [205, 92, 92],
indigo: [75, 0, 130],
ivory: [255, 255, 240],
khaki: [240, 230, 140],
lavender: [230, 230, 250],
lavenderblush: [255, 240, 245],
lawngreen: [124, 252, 0],
lemonchiffon: [255, 250, 205],
lightblue: [173, 216, 230],
lightcoral: [240, 128, 128],
lightcyan: [224, 255, 255],
lightgoldenrodyellow: [250, 250, 210],
lightgray: [211, 211, 211],
lightgreen: [144, 238, 144],
lightgrey: [211, 211, 211],
lightpink: [255, 182, 193],
lightsalmon: [255, 160, 122],
lightseagreen: [32, 178, 170],
lightskyblue: [135, 206, 250],
lightslategray: [119, 136, 153],
lightslategrey: [119, 136, 153],
lightsteelblue: [176, 196, 222],
lightyellow: [255, 255, 224],
lime: [0, 255, 0],
limegreen: [50, 205, 50],
linen: [250, 240, 230],
magenta: [255, 0, 255],
maroon: [128, 0, 0],
mediumaquamarine: [102, 205, 170],
mediumblue: [0, 0, 205],
mediumorchid: [186, 85, 211],
mediumpurple: [147, 112, 219],
mediumseagreen: [60, 179, 113],
mediumslateblue: [123, 104, 238],
mediumspringgreen: [0, 250, 154],
mediumturquoise: [72, 209, 204],
mediumvioletred: [199, 21, 133],
midnightblue: [25, 25, 112],
mintcream: [245, 255, 250],
mistyrose: [255, 228, 225],
moccasin: [255, 228, 181],
navajowhite: [255, 222, 173],
navy: [0, 0, 128],
oldlace: [253, 245, 230],
olive: [128, 128, 0],
olivedrab: [107, 142, 35],
orange: [255, 165, 0],
orangered: [255, 69, 0],
orchid: [218, 112, 214],
palegoldenrod: [238, 232, 170],
palegreen: [152, 251, 152],
paleturquoise: [175, 238, 238],
palevioletred: [219, 112, 147],
papayawhip: [255, 239, 213],
peachpuff: [255, 218, 185],
peru: [205, 133, 63],
pink: [255, 192, 203],
plum: [221, 160, 203],
powderblue: [176, 224, 230],
purple: [128, 0, 128],
rebeccapurple: [102, 51, 153],
red: [255, 0, 0],
rosybrown: [188, 143, 143],
royalblue: [65, 105, 225],
saddlebrown: [139, 69, 19],
salmon: [250, 128, 114],
sandybrown: [244, 164, 96],
seagreen: [46, 139, 87],
seashell: [255, 245, 238],
sienna: [160, 82, 45],
silver: [192, 192, 192],
skyblue: [135, 206, 235],
slateblue: [106, 90, 205],
slategray: [119, 128, 144],
slategrey: [119, 128, 144],
snow: [255, 255, 250],
springgreen: [0, 255, 127],
steelblue: [70, 130, 180],
tan: [210, 180, 140],
teal: [0, 128, 128],
thistle: [216, 191, 216],
transparent: [255, 255, 255, 0],
tomato: [255, 99, 71],
turquoise: [64, 224, 208],
violet: [238, 130, 238],
wheat: [245, 222, 179],
white: [255, 255, 255],
whitesmoke: [245, 245, 245],
yellow: [255, 255, 0],
yellowgreen: [154, 205, 5],
}, RGB_REGEX = /rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)/, animQueue = [];
const req = (typeof requestAnimationFrame !== 'undefined' && requestAnimationFrame) ||
function (f) {
setTimeout(f, 60);
};
/**
* @namespace Util
* @memberof Konva
*/
const Util = {
/*
* cherry-picked utilities from underscore.js
*/
_isElement(obj) {
return !!(obj && obj.nodeType == 1);
},
_isFunction(obj) {
return !!(obj && obj.constructor && obj.call && obj.apply);
},
_isPlainObject(obj) {
return !!obj && obj.constructor === Object;
},
_isArray(obj) {
return Object.prototype.toString.call(obj) === OBJECT_ARRAY;
},
_isNumber(obj) {
return (Object.prototype.toString.call(obj) === OBJECT_NUMBER &&
!isNaN(obj) &&
isFinite(obj));
},
_isString(obj) {
return Object.prototype.toString.call(obj) === OBJECT_STRING;
},
_isBoolean(obj) {
return Object.prototype.toString.call(obj) === OBJECT_BOOLEAN;
},
// arrays are objects too
isObject(val) {
return val instanceof Object;
},
isValidSelector(selector) {
if (typeof selector !== 'string') {
return false;
}
var firstChar = selector[0];
return (firstChar === '#' ||
firstChar === '.' ||
firstChar === firstChar.toUpperCase());
},
_sign(number) {
if (number === 0) {
// that is not what sign usually returns
// but that is what we need
return 1;
}
if (number > 0) {
return 1;
}
else {
return -1;
}
},
requestAnimFrame(callback) {
animQueue.push(callback);
if (animQueue.length === 1) {
req(function () {
const queue = animQueue;
animQueue = [];
queue.forEach(function (cb) {
cb();
});
});
}
},
createCanvasElement() {
var canvas = document.createElement('canvas');
// on some environments canvas.style is readonly
try {
canvas.style = canvas.style || {};
}
catch (e) { }
return canvas;
},
createImageElement() {
return document.createElement('img');
},
_isInDocument(el) {
while ((el = el.parentNode)) {
if (el == document) {
return true;
}
}
return false;
},
/*
* arg can be an image object or image data
*/
_urlToImage(url, callback) {
// if arg is a string, then it's a data url
var imageObj = Util.createImageElement();
imageObj.onload = function () {
callback(imageObj);
};
imageObj.src = url;
},
_rgbToHex(r, g, b) {
return ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
},
_hexToRgb(hex) {
hex = hex.replace(HASH$1, EMPTY_STRING$1);
var bigint = parseInt(hex, 16);
return {
r: (bigint >> 16) & 255,
g: (bigint >> 8) & 255,
b: bigint & 255,
};
},
/**
* return random hex color
* @method
* @memberof Konva.Util
* @example
* shape.fill(Konva.Util.getRandomColor());
*/
getRandomColor() {
var randColor = ((Math.random() * 0xffffff) << 0).toString(16);
while (randColor.length < 6) {
randColor = ZERO + randColor;
}
return HASH$1 + randColor;
},
/**
* get RGB components of a color
* @method
* @memberof Konva.Util
* @param {String} color
* @example
* // each of the following examples return {r:0, g:0, b:255}
* var rgb = Konva.Util.getRGB('blue');
* var rgb = Konva.Util.getRGB('#0000ff');
* var rgb = Konva.Util.getRGB('rgb(0,0,255)');
*/
getRGB(color) {
var rgb;
// color string
if (color in COLORS) {
rgb = COLORS[color];
return {
r: rgb[0],
g: rgb[1],
b: rgb[2],
};
}
else if (color[0] === HASH$1) {
// hex
return this._hexToRgb(color.substring(1));
}
else if (color.substr(0, 4) === RGB_PAREN) {
// rgb string
rgb = RGB_REGEX.exec(color.replace(/ /g, ''));
return {
r: parseInt(rgb[1], 10),
g: parseInt(rgb[2], 10),
b: parseInt(rgb[3], 10),
};
}
else {
// default
return {
r: 0,
g: 0,
b: 0,
};
}
},
// convert any color string to RGBA object
// from https://github.com/component/color-parser
colorToRGBA(str) {
str = str || 'black';
return (Util._namedColorToRBA(str) ||
Util._hex3ColorToRGBA(str) ||
Util._hex6ColorToRGBA(str) ||
Util._rgbColorToRGBA(str) ||
Util._rgbaColorToRGBA(str) ||
Util._hslColorToRGBA(str));
},
// Parse named css color. Like "green"
_namedColorToRBA(str) {
var c = COLORS[str.toLowerCase()];
if (!c) {
return null;
}
return {
r: c[0],
g: c[1],
b: c[2],
a: 1,
};
},
// Parse rgb(n, n, n)
_rgbColorToRGBA(str) {
if (str.indexOf('rgb(') === 0) {
str = str.match(/rgb\(([^)]+)\)/)[1];
var parts = str.split(/ *, */).map(Number);
return {
r: parts[0],
g: parts[1],
b: parts[2],
a: 1,
};
}
},
// Parse rgba(n, n, n, n)
_rgbaColorToRGBA(str) {
if (str.indexOf('rgba(') === 0) {
str = str.match(/rgba\(([^)]+)\)/)[1];
var parts = str.split(/ *, */).map(Number);
return {
r: parts[0],
g: parts[1],
b: parts[2],
a: parts[3],
};
}
},
// Parse #nnnnnn
_hex6ColorToRGBA(str) {
if (str[0] === '#' && str.length === 7) {
return {
r: parseInt(str.slice(1, 3), 16),
g: parseInt(str.slice(3, 5), 16),
b: parseInt(str.slice(5, 7), 16),
a: 1,
};
}
},
// Parse #nnn
_hex3ColorToRGBA(str) {
if (str[0] === '#' && str.length === 4) {
return {
r: parseInt(str[1] + str[1], 16),
g: parseInt(str[2] + str[2], 16),
b: parseInt(str[3] + str[3], 16),
a: 1,
};
}
},
// Code adapted from https://github.com/Qix-/color-convert/blob/master/conversions.js#L244
_hslColorToRGBA(str) {
// Check hsl() format
if (/hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g.test(str)) {
// Extract h, s, l
const [_, ...hsl] = /hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g.exec(str);
const h = Number(hsl[0]) / 360;
const s = Number(hsl[1]) / 100;
const l = Number(hsl[2]) / 100;
let t2;
let t3;
let val;
if (s === 0) {
val = l * 255;
return {
r: Math.round(val),
g: Math.round(val),
b: Math.round(val),
a: 1,
};
}
if (l < 0.5) {
t2 = l * (1 + s);
}
else {
t2 = l + s - l * s;
}
const t1 = 2 * l - t2;
const rgb = [0, 0, 0];
for (let i = 0; i < 3; i++) {
t3 = h + (1 / 3) * -(i - 1);
if (t3 < 0) {
t3++;
}
if (t3 > 1) {
t3--;
}
if (6 * t3 < 1) {
val = t1 + (t2 - t1) * 6 * t3;
}
else if (2 * t3 < 1) {
val = t2;
}
else if (3 * t3 < 2) {
val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
}
else {
val = t1;
}
rgb[i] = val * 255;
}
return {
r: Math.round(rgb[0]),
g: Math.round(rgb[1]),
b: Math.round(rgb[2]),
a: 1,
};
}
},
/**
* check intersection of two client rectangles
* @method
* @memberof Konva.Util
* @param {Object} r1 - { x, y, width, height } client rectangle
* @param {Object} r2 - { x, y, width, height } client rectangle
* @example
* const overlapping = Konva.Util.haveIntersection(shape1.getClientRect(), shape2.getClientRect());
*/
haveIntersection(r1, r2) {
return !(r2.x > r1.x + r1.width ||
r2.x + r2.width < r1.x ||
r2.y > r1.y + r1.height ||
r2.y + r2.height < r1.y);
},
cloneObject(obj) {
var retObj = {};
for (var key in obj) {
if (this._isPlainObject(obj[key])) {
retObj[key] = this.cloneObject(obj[key]);
}
else if (this._isArray(obj[key])) {
retObj[key] = this.cloneArray(obj[key]);
}
else {
retObj[key] = obj[key];
}
}
return retObj;
},
cloneArray(arr) {
return arr.slice(0);
},
degToRad(deg) {
return deg * PI_OVER_DEG180;
},
radToDeg(rad) {
return rad * DEG180_OVER_PI;
},
_degToRad(deg) {
Util.warn('Util._degToRad is removed. Please use public Util.degToRad instead.');
return Util.degToRad(deg);
},
_radToDeg(rad) {
Util.warn('Util._radToDeg is removed. Please use public Util.radToDeg instead.');
return Util.radToDeg(rad);
},
_getRotation(radians) {
return Konva$2.angleDeg ? Util.radToDeg(radians) : radians;
},
_capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
},
throw(str) {
throw new Error(KONVA_ERROR + str);
},
error(str) {
console.error(KONVA_ERROR + str);
},
warn(str) {
if (!Konva$2.showWarnings) {
return;
}
console.warn(KONVA_WARNING + str);
},
each(obj, func) {
for (var key in obj) {
func(key, obj[key]);
}
},
_inRange(val, left, right) {
return left <= val && val < right;
},
_getProjectionToSegment(x1, y1, x2, y2, x3, y3) {
var x, y, dist;
var pd2 = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2);
if (pd2 == 0) {
x = x1;
y = y1;
dist = (x3 - x2) * (x3 - x2) + (y3 - y2) * (y3 - y2);
}
else {
var u = ((x3 - x1) * (x2 - x1) + (y3 - y1) * (y2 - y1)) / pd2;
if (u < 0) {
x = x1;
y = y1;
dist = (x1 - x3) * (x1 - x3) + (y1 - y3) * (y1 - y3);
}
else if (u > 1.0) {
x = x2;
y = y2;
dist = (x2 - x3) * (x2 - x3) + (y2 - y3) * (y2 - y3);
}
else {
x = x1 + u * (x2 - x1);
y = y1 + u * (y2 - y1);
dist = (x - x3) * (x - x3) + (y - y3) * (y - y3);
}
}
return [x, y, dist];
},
// line as array of points.
// line might be closed
_getProjectionToLine(pt, line, isClosed) {
var pc = Util.cloneObject(pt);
var dist = Number.MAX_VALUE;
line.forEach(function (p1, i) {
if (!isClosed && i === line.length - 1) {
return;
}
var p2 = line[(i + 1) % line.length];
var proj = Util._getProjectionToSegment(p1.x, p1.y, p2.x, p2.y, pt.x, pt.y);
var px = proj[0], py = proj[1], pdist = proj[2];
if (pdist < dist) {
pc.x = px;
pc.y = py;
dist = pdist;
}
});
return pc;
},
_prepareArrayForTween(startArray, endArray, isClosed) {
var n, start = [], end = [];
if (startArray.length > endArray.length) {
var temp = endArray;
endArray = startArray;
startArray = temp;
}
for (n = 0; n < startArray.length; n += 2) {
start.push({
x: startArray[n],
y: startArray[n + 1],
});
}
for (n = 0; n < endArray.length; n += 2) {
end.push({
x: endArray[n],
y: endArray[n + 1],
});
}
var newStart = [];
end.forEach(function (point) {
var pr = Util._getProjectionToLine(point, start, isClosed);
newStart.push(pr.x);
newStart.push(pr.y);
});
return newStart;
},
_prepareToStringify(obj) {
var desc;
obj.visitedByCircularReferenceRemoval = true;
for (var key in obj) {
if (!(obj.hasOwnProperty(key) && obj[key] && typeof obj[key] == 'object')) {
continue;
}
desc = Object.getOwnPropertyDescriptor(obj, key);
if (obj[key].visitedByCircularReferenceRemoval ||
Util._isElement(obj[key])) {
if (desc.configurable) {
delete obj[key];
}
else {
return null;
}
}
else if (Util._prepareToStringify(obj[key]) === null) {
if (desc.configurable) {
delete obj[key];
}
else {
return null;
}
}
}
delete obj.visitedByCircularReferenceRemoval;
return obj;
},
// very simplified version of Object.assign
_assign(target, source) {
for (var key in source) {
target[key] = source[key];
}
return target;
},
_getFirstPointerId(evt) {
if (!evt.touches) {
// try to use pointer id or fake id
return evt.pointerId || 999;
}
else {
return evt.changedTouches[0].identifier;
}
},
};
function _formatValue(val) {
if (Util._isString(val)) {
return '"' + val + '"';
}
if (Object.prototype.toString.call(val) === '[object Number]') {
return val;
}
if (Util._isBoolean(val)) {
return val;
}
return Object.prototype.toString.call(val);
}
function RGBComponent(val) {
if (val > 255) {
return 255;
}
else if (val < 0) {
return 0;
}
return Math.round(val);
}
function getNumberValidator() {
if (Konva$2.isUnminified) {
return function (val, attr) {
if (!Util._isNumber(val)) {
Util.warn(_formatValue(val) +
' is a not valid value for "' +
attr +
'" attribute. The value should be a number.');
}
return val;
};
}
}
function getNumberOrArrayOfNumbersValidator(noOfElements) {
if (Konva$2.isUnminified) {
return function (val, attr) {
let isNumber = Util._isNumber(val);
let isValidArray = Util._isArray(val) && val.length == noOfElements;
if (!isNumber && !isValidArray) {
Util.warn(_formatValue(val) +
' is a not valid value for "' +
attr +
'" attribute. The value should be a number or Array<number>(' +
noOfElements +
')');
}
return val;
};
}
}
function getNumberOrAutoValidator() {
if (Konva$2.isUnminified) {
return function (val, attr) {
var isNumber = Util._isNumber(val);
var isAuto = val === 'auto';
if (!(isNumber || isAuto)) {
Util.warn(_formatValue(val) +
' is a not valid value for "' +
attr +
'" attribute. The value should be a number or "auto".');
}
return val;
};
}
}
function getStringValidator() {
if (Konva$2.isUnminified) {
return function (val, attr) {
if (!Util._isString(val)) {
Util.warn(_formatValue(val) +
' is a not valid value for "' +
attr +
'" attribute. The value should be a string.');
}
return val;
};
}
}
function getStringOrGradientValidator() {
if (Konva$2.isUnminified) {
return function (val, attr) {
const isString = Util._isString(val);
const isGradient = Object.prototype.toString.call(val) === '[object CanvasGradient]' ||
(val && val.addColorStop);
if (!(isString || isGradient)) {
Util.warn(_formatValue(val) +
' is a not valid value for "' +
attr +
'" attribute. The value should be a string or a native gradient.');
}
return val;
};
}
}
function getNumberArrayValidator() {
if (Konva$2.isUnminified) {
return function (val, attr) {
if (!Util._isArray(val)) {
Util.warn(_formatValue(val) +
' is a not valid value for "' +
attr +
'" attribute. The value should be a array of numbers.');
}
else {
val.forEach(function (item) {
if (!Util._isNumber(item)) {
Util.warn('"' +
attr +
'" attribute has non numeric element ' +
item +
'. Make sure that all elements are numbers.');
}
});
}
return val;
};
}
}
function getBooleanValidator() {
if (Konva$2.isUnminified) {
return function (val, attr) {
var isBool = val === true || val === false;
if (!isBool) {
Util.warn(_formatValue(val) +
' is a not valid value for "' +
attr +
'" attribute. The value should be a boolean.');
}
return val;
};
}
}
function getComponentValidator(components) {
if (Konva$2.isUnminified) {
return function (val, attr) {
if (!Util.isObject(val)) {
Util.warn(_formatValue(val) +
' is a not valid value for "' +
attr +
'" attribute. The value should be an object with properties ' +
components);
}
return val;
};
}
}
var GET = 'get', SET$1 = 'set';
const Factory = {
addGetterSetter(constructor, attr, def, validator, after) {
Factory.addGetter(constructor, attr, def);
Factory.addSetter(constructor, attr, validator, after);
Factory.addOverloadedGetterSetter(constructor, attr);
},
addGetter(constructor, attr, def) {
var method = GET + Util._capitalize(attr);
constructor.prototype[method] =
constructor.prototype[method] ||
function () {
var val = this.attrs[attr];
return val === undefined ? def : val;
};
},
addSetter(constructor, attr, validator, after) {
var method = SET$1 + Util._capitalize(attr);
if (!constructor.prototype[method]) {
Factory.overWriteSetter(constructor, attr, validator, after);
}
},
overWriteSetter(constructor, attr, validator, after) {
var method = SET$1 + Util._capitalize(attr);
constructor.prototype[method] = function (val) {
if (validator && val !== undefined && val !== null) {
val = validator.call(this, val, attr);
}
this._setAttr(attr, val);
if (after) {
after.call(this);
}
return this;
};
},
addComponentsGetterSetter(constructor, attr, components, validator, after) {
var len = components.length, capitalize = Util._capitalize, getter = GET + capitalize(attr), setter = SET$1 + capitalize(attr), n, component;
// getter
constructor.prototype[getter] = function () {
var ret = {};
for (n = 0; n < len; n++) {
component = components[n];
ret[component] = this.getAttr(attr + capitalize(component));
}
return ret;
};
var basicValidator = getComponentValidator(components);
// setter
constructor.prototype[setter] = function (val) {
var oldVal = this.attrs[attr], key;
if (validator) {
val = validator.call(this, val);
}
if (basicValidator) {
basicValidator.call(this, val, attr);
}
for (key in val) {
if (!val.hasOwnProperty(key)) {
continue;
}
this._setAttr(attr + capitalize(key), val[key]);
}
this._fireChangeEvent(attr, oldVal, val);
if (after) {
after.call(this);
}
return this;
};
Factory.addOverloadedGetterSetter(constructor, attr);
},
addOverloadedGetterSetter(constructor, attr) {
var capitalizedAttr = Util._capitalize(attr), setter = SET$1 + capitalizedAttr, getter = GET + capitalizedAttr;
constructor.prototype[attr] = function () {
// setting
if (arguments.length) {
this[setter](arguments[0]);
return this;
}
// getting
return this[getter]();
};
},
addDeprecatedGetterSetter(constructor, attr, def, validator) {
Util.error('Adding deprecated ' + attr);
var method = GET + Util._capitalize(attr);
var message = attr +
' property is deprecated and will be removed soon. Look at Konva change log for more information.';
constructor.prototype[method] = function () {
Util.error(message);
var val = this.attrs[attr];
return val === undefined ? def : val;
};
Factory.addSetter(constructor, attr, validator, function () {
Util.error(message);
});
Factory.addOverloadedGetterSetter(constructor, attr);
},
backCompat(constructor, methods) {
Util.each(methods, function (oldMethodName, newMethodName) {
var method = constructor.prototype[newMethodName];
var oldGetter = GET + Util._capitalize(oldMethodName);
var oldSetter = SET$1 + Util._capitalize(oldMethodName);
function deprecated() {
method.apply(this, arguments);
Util.error('"' +
oldMethodName +
'" method is deprecated and will be removed soon. Use ""' +
newMethodName +
'" instead.');
}
constructor.prototype[oldMethodName] = deprecated;
constructor.prototype[oldGetter] = deprecated;
constructor.prototype[oldSetter] = deprecated;
});
},
afterSetFilter() {
this._filterUpToDate = false;
},
};
function simplifyArray(arr) {
var retArr = [], len = arr.length, util = Util, n, val;
for (n = 0; n < len; n++) {
val = arr[n];
if (util._isNumber(val)) {
val = Math.round(val * 1000) / 1000;
}
else if (!util._isString(val)) {
val = val + '';
}
retArr.push(val);
}
return retArr;
}
var COMMA = ',', OPEN_PAREN = '(', CLOSE_PAREN = ')', OPEN_PAREN_BRACKET = '([', CLOSE_BRACKET_PAREN = '])', SEMICOLON = ';', DOUBLE_PAREN = '()',
// EMPTY_STRING = '',
EQUALS = '=',
// SET = 'set',
CONTEXT_METHODS = [
'arc',
'arcTo',
'beginPath',
'bezierCurveTo',
'clearRect',
'clip',
'closePath',
'createLinearGradient',
'createPattern',
'createRadialGradient',
'drawImage',
'ellipse',
'fill',
'fillText',
'getImageData',
'createImageData',
'lineTo',
'moveTo',
'putImageData',
'quadraticCurveTo',
'rect',
'restore',
'rotate',
'save',
'scale',
'setLineDash',
'setTransform',
'stroke',
'strokeText',
'transform',
'translate',
];
var CONTEXT_PROPERTIES = [
'fillStyle',
'strokeStyle',
'shadowColor',
'shadowBlur',
'shadowOffsetX',
'shadowOffsetY',
'lineCap',
'lineDashOffset',
'lineJoin',
'lineWidth',
'miterLimit',
'font',
'textAlign',
'textBaseline',
'globalAlpha',
'globalCompositeOperation',
'imageSmoothingEnabled',
];
const traceArrMax = 100;
/**
* Konva wrapper around native 2d canvas context. It has almost the same API of 2d context with some additional functions.
* With core Konva shapes you don't need to use this object. But you will use it if you want to create
* a [custom shape](/docs/react/Custom_Shape.html) or a [custom hit regions](/docs/events/Custom_Hit_Region.html).
* For full information about each 2d context API use [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D)
* @constructor
* @memberof Konva
* @example
* const rect = new Konva.Shape({
* fill: 'red',
* width: 100,
* height: 100,
* sceneFunc: (ctx, shape) => {
* // ctx - is context wrapper
* // shape - is instance of Konva.Shape, so it equals to "rect" variable
* ctx.rect(0, 0, shape.getAttr('width'), shape.getAttr('height'));
*
* // automatically fill shape from props and draw hit region
* ctx.fillStrokeShape(shape);
* }
* })
*/
class Context {
constructor(canvas) {
this.canvas = canvas;
this._context = canvas._canvas.getContext('2d');
if (Konva$2.enableTrace) {
this.traceArr = [];
this._enableTrace();
}
}
/**
* fill shape
* @method
* @name Konva.Context#fillShape
* @param {Konva.Shape} shape
*/
fillShape(shape) {
if (shape.fillEnabled()) {
this._fill(shape);
}
}
_fill(shape) {
// abstract
}
/**
* stroke shape
* @method
* @name Konva.Context#strokeShape
* @param {Konva.Shape} shape
*/
strokeShape(shape) {
if (shape.hasStroke()) {
this._stroke(shape);
}
}
_stroke(shape) {
// abstract
}
/**
* fill then stroke
* @method
* @name Konva.Context#fillStrokeShape
* @param {Konva.Shape} shape
*/
fillStrokeShape(shape) {
if (shape.attrs.fillAfterStrokeEnabled) {
this.strokeShape(shape);
this.fillShape(shape);
}
else {
this.fillShape(shape);
this.strokeShape(shape);
}
}
getTrace(relaxed, rounded) {
var traceArr = this.traceArr, len = traceArr.length, str = '', n, trace, method, args;
for (n = 0; n < len; n++) {
trace = traceArr[n];
method = trace.method;
// methods
if (method) {
args = trace.args;
str += method;
if (relaxed) {
str += DOUBLE_PAREN;
}
else {
if (Util._isArray(args[0])) {
str += OPEN_PAREN_BRACKET + args.join(COMMA) + CLOSE_BRACKET_PAREN;
}
else {
if (rounded) {
args = args.map((a) => typeof a === 'number' ? Math.floor(a) : a);
}
str += OPEN_PAREN + args.join(COMMA) + CLOSE_PAREN;
}
}
}
else {
// properties
str += trace.property;
if (!relaxed) {
str += EQUALS + trace.val;
}
}
str += SEMICOLON;
}
return str;
}
clearTrace() {
this.traceArr = [];
}
_trace(str) {
var traceArr = this.traceArr, len;
traceArr.push(str);
len = traceArr.length;
if (len >= traceArrMax) {
traceArr.shift();
}
}
/**
* reset canvas context transform
* @method
* @name Konva.Context#reset
*/
reset() {
var pixelRatio = this.getCanvas().getPixelRatio();
this.setTransform(1 * pixelRatio, 0, 0, 1 * pixelRatio, 0, 0);
}
/**
* get canvas wrapper
* @method
* @name Konva.Context#getCanvas
* @returns {Konva.Canvas}
*/
getCanvas() {
return this.canvas;
}
/**
* clear canvas
* @method
* @name Konva.Context#clear
* @param {Object} [bounds]
* @param {Number} [bounds.x]
* @param {Number} [bounds.y]
* @param {Number} [bounds.width]
* @param {Number} [bounds.height]
*/
clear(bounds) {
var canvas = this.getCanvas();
if (bounds) {
this.clearRect(bounds.x || 0, bounds.y || 0, bounds.width || 0, bounds.height || 0);
}
else {
this.clearRect(0, 0, canvas.getWidth() / canvas.pixelRatio, canvas.getHeight() / canvas.pixelRatio);
}
}
_applyLineCap(shape) {
var lineCap = shape.getLineCap();
if (lineCap) {
this.setAttr('lineCap', lineCap);
}
}
_applyOpacity(shape) {
var absOpacity = shape.getAbsoluteOpacity();
if (absOpacity !== 1) {
this.setAttr('globalAlpha', absOpacity);
}
}
_applyLineJoin(shape) {
var lineJoin = shape.attrs.lineJoin;
if (lineJoin) {
this.setAttr('lineJoin', lineJoin);
}
}
setAttr(attr, val) {
this._context[attr] = val;
}
/**
* arc function.
* @method
* @name Konva.Context#arc
*/
arc(a0, a1, a2, a3, a4, a5) {
this._context.arc(a0, a1, a2, a3, a4, a5);
}
/**
* arcTo function.
* @method
* @name Konva.Context#arcTo
*/
arcTo(a0, a1, a2, a3, a4) {
this._context.arcTo(a0, a1, a2, a3, a4);
}
/**
* beginPath function.
* @method
* @name Konva.Context#beginPath
*/
beginPath() {
this._context.beginPath();
}
/**
* bezierCurveTo function.
* @method
* @name Konva.Context#bezierCurveTo
*/
bezierCurveTo(a0, a1, a2, a3, a4, a5) {
this._context.bezierCurveTo(a0, a1, a2, a3, a4, a5);
}
/**
* clearRect function.
* @method
* @name Konva.Context#clearRect
*/
clearRect(a0, a1, a2, a3) {
this._context.clearRect(a0, a1, a2, a3);
}
/**
* clip function.
* @method
* @name Konva.Context#clip
*/
clip() {
this._context.clip();
}
/**
* closePath function.
* @method
* @name Konva.Context#closePath
*/
closePath() {
this._context.closePath();
}
/**
* createImageData function.
* @method
* @name Konva.Context#createImageData
*/
createImageData(a0, a1) {
var a = arguments;
if (a.length === 2) {
return this._context.createImageData(a0, a1);
}
else if (a.length === 1) {
return this._context.createImageData(a0);
}
}
/**
* createLinearGradient function.
* @method
* @name Konva.Context#createLinearGradient
*/
createLinearGradient(a0, a1, a2, a3) {
return this._context.createLinearGradient(a0, a1, a2, a3);
}
/**
* createPattern function.
* @method
* @name Konva.Context#createPattern
*/
createPattern(a0, a1) {
return this._context.createPattern(a0, a1);
}
/**
* createRadialGradient function.
* @method
* @name Konva.Context#createRadialGradient
*/
createRadialGradient(a0, a1, a2, a3, a4, a5) {
return this._context.createRadialGradient(a0, a1, a2, a3, a4, a5);
}
/**
* drawImage function.
* @method
* @name Konva.Context#drawImage
*/
drawImage(a0, a1, a2, a3, a4, a5, a6, a7, a8) {
// this._context.drawImage(...arguments);
var a = arguments, _context = this._context;
if (a.length === 3) {
_context.drawImage(a0, a1, a2);
}
else if (a.length === 5) {
_context.drawImage(a0, a1, a2, a3, a4);
}
else if (a.length === 9) {
_context.drawImage(a0, a1, a2, a3, a4, a5, a6, a7, a8);
}
}
/**
* ellipse function.
* @method
* @name Konva.Context#ellipse
*/
ellipse(a0, a1, a2, a3, a4, a5, a6, a7) {
this._context.ellipse(a0, a1, a2, a3, a4, a5, a6, a7);
}
/**
* isPointInPath function.
* @method
* @name Konva.Context#isPointInPath
*/
isPointInPath(x, y) {
return this._context.isPointInPath(x, y);
}
/**
* fill function.
* @method
* @name Konva.Context#fill
*/
fill(path2d) {
if (path2d) {
this._context.fill(path2d);
}
else {
this._context.fill();
}
}
/**
* fillRect function.
* @method
* @name Konva.Context#fillRect
*/
fillRect(x, y, width, height) {
this._context.fillRect(x, y, width, height);
}
/**
* strokeRect function.
* @method
* @name Konva.Context#strokeRect
*/
strokeRect(x, y, width, height) {
this._context.strokeRect(x, y, width, height);
}
/**
* fillText function.
* @method
* @name Konva.Context#fillText
*/
fillText(text, x, y, maxWidth) {
if (maxWidth) {
this._context.fillText(text, x, y, maxWidth);
}
else {
this._context.fillText(text, x, y);
}
}
/**
* measureText function.
* @method
* @name Konva.Context#measureText
*/
measureText(text) {
return this._context.measureText(text);
}
/**
* getImageData function.
* @method
* @name Konva.Context#getImageData
*/
getImageData(a0, a1, a2, a3) {
return this._context.getImageData(a0, a1, a2, a3);
}
/**
* lineTo function.
* @method
* @name Konva.Context#lineTo
*/
lineTo(a0, a1) {
this._context.lineTo(a0, a1);
}
/**
* moveTo function.
* @method
* @name Konva.Context#moveTo
*/
moveTo(a0, a1) {
this._context.moveTo(a0, a1);
}
/**
* rect function.
* @method
* @name Konva.Context#rect
*/
rect(a0, a1, a2, a3) {
this._context.rect(a0, a1, a2, a3);
}
/**
* putImageData function.
* @method
* @name Konva.Context#putImageData
*/
putImageData(a0, a1, a2) {
this._context.putImageData(a0, a1, a2);
}
/**
* quadraticCurveTo function.
* @method
* @name Konva.Context#quadraticCurveTo
*/
quadraticCurveTo(a0, a1, a2, a3) {
this._context.quadraticCurveTo(a0, a1, a2, a3);
}
/**
* restore function.
* @method
* @name Konva.Context#restore
*/
restore() {
this._context.restore();
}
/**
* rotate function.
* @method
* @name Konva.Context#rotate
*/
rotate(a0) {
this._context.rotate(a0);
}
/**
* save function.
* @method
* @name Konva.Context#save
*/
save() {
this._context.save();
}
/**
* scale function.
* @method
* @name Konva.Context#scale
*/
scale(a0, a1) {
this._context.scale(a0, a1);
}
/**
* setLineDash function.
* @method
* @name Konva.Context#setLineDash
*/
setLineDash(a0) {
// works for Chrome and IE11
if (this._context.setLineDash) {
this._context.setLineDash(a0);
}
else if ('mozDash' in this._context) {
// verified that this works in firefox
this._context['mozDash'] = a0;
}
else if ('webkitLineDash' in this._context) {
// does not currently work for Safari
this._context['webkitLineDash'] = a0;
}
// no support for IE9 and IE10
}
/**
* getLineDash function.
* @method
* @name Konva.Context#getLineDash
*/
getLineDash() {
return this._context.getLineDash();
}
/**
* setTransform function.
* @method
* @name Konva.Context#setTransform
*/
setTransform(a0, a1, a2, a3, a4, a5) {
this._context.setTransform(a0, a1, a2, a3, a4, a5);
}
/**
* stroke function.
* @method
* @name Konva.Context#stroke
*/
stroke(path2d) {
if (path2d) {
this._context.stroke(path2d);
}
else {
this._context.stroke();
}
}
/**
* strokeText function.
* @method
* @name Konva.Context#strokeText
*/
strokeText(a0, a1, a2, a3) {
this._context.strokeText(a0, a1, a2, a3);
}
/**
* transform function.
* @method
* @name Konva.Context#transform
*/
transform(a0, a1, a2, a3, a4, a5) {
this._context.transform(a0, a1, a2, a3, a4, a5);
}
/**
* translate function.
* @method
* @name Konva.Context#translate
*/
translate(a0, a1) {
this._context.translate(a0, a1);
}
_enableTrace() {
var that = this, len = CONTEXT_METHODS.length, origSetter = this.setAttr, n, args;
// to prevent creating scope function at each loop
var func = function (methodName) {
var origMethod = that[methodName], ret;
that[methodName] = function () {
args = simplifyArray(Array.prototype.slice.call(arguments, 0));
ret = origMethod.apply(that, arguments);
that._trace({
method: methodName,
args: args,
});
return ret;
};
};
// methods
for (n = 0; n < len; n++) {
func(CONTEXT_METHODS[n]);
}
// attrs
that.setAttr = function () {
origSetter.apply(that, arguments);
var prop = arguments[0];
var val = arguments[1];
if (prop === 'shadowOffsetX' ||
prop === 'shadowOffsetY' ||
prop === 'shadowBlur') {
val = val / this.canvas.getPixelRatio();
}
that._trace({
property: prop,
val: val,
});
};
}
_applyGlobalCompositeOperation(node) {
const op = node.attrs.globalCompositeOperation;
var def = !op || op === 'source-over';
if (!def) {
this.setAttr('globalCompositeOperation', op);
}
}
}
CONTEXT_PROPERTIES.forEach(function (prop) {
Object.defineProperty(Context.prototype, prop, {
get() {
return this._context[prop];
},
set(val) {
this._context[prop] = val;
},
});
});
class SceneContext extends Context {
_fillColor(shape) {
var fill = shape.fill();
this.setAttr('fillStyle', fill);
shape._fillFunc(this);
}
_fillPattern(shape) {
this.setAttr('fillStyle', shape._getFillPattern());
shape._fillFunc(this);
}
_fillLinearGradient(shape) {
var grd = shape._getLinearGradient();
if (grd) {
this.setAttr('fillStyle', grd);
shape._fillFunc(this);
}
}
_fillRadialGradient(shape) {
var grd = shape._getRadialGradient();
if (grd) {
this.setAttr('fillStyle', grd);
shape._fillFunc(this);
}
}
_fill(shape) {
var hasColor = shape.fill(), fillPriority = shape.getFillPriority();
// priority fills
if (hasColor && fillPriority === 'color') {
this._fillColor(shape);
return;
}
var hasPattern = shape.getFillPatternImage();
if (hasPattern && fillPriority === 'pattern') {
this._fillPattern(shape);
return;
}
var hasLinearGradient = shape.getFillLinearGradientColorStops();
if (hasLinearGradient && fillPriority === 'linear-gradient') {
this._fillLinearGradient(shape);
return;
}
var hasRadialGradient = shape.getFillRadialGradientColorStops();
if (hasRadialGradient && fillPriority === 'radial-gradient') {
this._fillRadialGradient(shape);
return;
}
// now just try and fill with whatever is available
if (hasColor) {
this._fillColor(shape);
}
else if (hasPattern) {
this._fillPattern(shape);
}
else if (hasLinearGradient) {
this._fillLinearGradient(shape);
}
else if (hasRadialGradient) {
this._fillRadialGradient(shape);
}
}
_strokeLinearGradient(shape) {
var start = shape.getStrokeLinearGradientStartPoint(), end = shape.getStrokeLinearGradientEndPoint(), colorStops = shape.getStrokeLinearGradientColorStops(), grd = this.createLinearGradient(start.x, start.y, end.x, end.y);
if (colorStops) {
// build color stops
for (var n = 0; n < colorStops.length; n += 2) {
grd.addColorStop(colorStops[n], colorStops[n + 1]);
}
this.setAttr('strokeStyle', grd);
}
}
_stroke(shape) {
var dash = shape.dash(),
// ignore strokeScaleEnabled for Text
strokeScaleEnabled = shape.getStrokeScaleEnabled();
if (shape.hasStroke()) {
if (!strokeScaleEnabled) {
this.save();
var pixelRatio = this.getCanvas().getPixelRatio();
this.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0);
}
this._applyLineCap(shape);
if (dash && shape.dashEnabled()) {
this.setLineDash(dash);
this.setAttr('lineDashOffset', shape.dashOffset());
}
this.setAttr('lineWidth', shape.strokeWidth());
if (!shape.getShadowForStrokeEnabled()) {
this.setAttr('shadowColor', 'rgba(0,0,0,0)');
}
var hasLinearGradient = shape.getStrokeLinearGradientColorStops();
if (hasLinearGradient) {
this._strokeLinearGradient(shape);
}
else {
this.setAttr('strokeStyle', shape.stroke());
}
shape._strokeFunc(this);
if (!strokeScaleEnabled) {
this.restore();
}
}
}
_applyShadow(shape) {
var _a, _b, _c;
var color = (_a = shape.getShadowRGBA()) !== null && _a !== void 0 ? _a : 'black', blur = (_b = shape.getShadowBlur()) !== null && _b !== void 0 ? _b : 5, offset = (_c = shape.getShadowOffset()) !== null && _c !== void 0 ? _c : {
x: 0,
y: 0,
}, scale = shape.getAbsoluteScale(), ratio = this.canvas.getPixelRatio(), scaleX = scale.x * ratio, scaleY = scale.y * ratio;
this.setAttr('shadowColor', color);
this.setAttr('shadowBlur', blur * Math.min(Math.abs(scaleX), Math.abs(scaleY)));
this.setAttr('shadowOffsetX', offset.x * scaleX);
this.setAttr('shadowOffsetY', offset.y * scaleY);
}
}
class HitContext extends Context {
_fill(shape) {
this.save();
this.setAttr('fillStyle', shape.colorKey);
shape._fillFuncHit(this);
this.restore();
}
strokeShape(shape) {
if (shape.hasHitStroke()) {
this._stroke(shape);
}
}
_stroke(shape) {
if (shape.hasHitStroke()) {
// ignore strokeScaleEnabled for Text
var strokeScaleEnabled = shape.getStrokeScaleEnabled();
if (!strokeScaleEnabled) {
this.save();
var pixelRatio = this.getCanvas().getPixelRatio();
this.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0);
}
this._applyLineCap(shape);
var hitStrokeWidth = shape.hitStrokeWidth();
var strokeWidth = hitStrokeWidth === 'auto' ? shape.strokeWidth() : hitStrokeWidth;
this.setAttr('lineWidth', strokeWidth);
this.setAttr('strokeStyle', shape.colorKey);
shape._strokeFuncHit(this);
if (!strokeScaleEnabled) {
this.restore();
}
}
}
}
// calculate pixel ratio
var _pixelRatio;
function getDevicePixelRatio() {
if (_pixelRatio) {
return _pixelRatio;
}
var canvas = Util.createCanvasElement();
var context = canvas.getContext('2d');
_pixelRatio = (function () {
var devicePixelRatio = Konva$2._global.devicePixelRatio || 1, backingStoreRatio = context.webkitBackingStorePixelRatio ||
context.mozBackingStorePixelRatio ||
context.msBackingStorePixelRatio ||
context.oBackingStorePixelRatio ||
context.backingStorePixelRatio ||
1;
return devicePixelRatio / backingStoreRatio;
})();
return _pixelRatio;
}
/**
* Canvas Renderer constructor. It is a wrapper around native canvas element.
* Usually you don't need to use it manually.
* @constructor
* @abstract
* @memberof Konva
* @param {Object} config
* @param {Number} config.width
* @param {Number} config.height
* @param {Number} config.pixelRatio
*/
class Canvas {
constructor(config) {
this.pixelRatio = 1;
this.width = 0;
this.height = 0;
this.isCache = false;
var conf = config || {};
var pixelRatio = conf.pixelRatio || Konva$2.pixelRatio || getDevicePixelRatio();
this.pixelRatio = pixelRatio;
this._canvas = Util.createCanvasElement();
// set inline styles
this._canvas.style.padding = '0';
this._canvas.style.margin = '0';
this._canvas.style.border = '0';
this._canvas.style.background = 'transparent';
this._canvas.style.position = 'absolute';
this._canvas.style.top = '0';
this._canvas.style.left = '0';
}
/**
* get canvas context
* @method
* @name Konva.Canvas#getContext
* @returns {CanvasContext} context
*/
getContext() {
return this.context;
}
getPixelRatio() {
return this.pixelRatio;
}
setPixelRatio(pixelRatio) {
var previousRatio = this.pixelRatio;
this.pixelRatio = pixelRatio;
this.setSize(this.getWidth() / previousRatio, this.getHeight() / previousRatio);
}
setWidth(width) {
// take into account pixel ratio
this.width = this._canvas.width = width * this.pixelRatio;
this._canvas.style.width = width + 'px';
var pixelRatio = this.pixelRatio, _context = this.getContext()._context;
_context.scale(pixelRatio, pixelRatio);
}
setHeight(height) {
// take into account pixel ratio
this.height = this._canvas.height = height * this.pixelRatio;
this._canvas.style.height = height + 'px';
var pixelRatio = this.pixelRatio, _context = this.getContext()._context;
_context.scale(pixelRatio, pixelRatio);
}
getWidth() {
return this.width;
}
getHeight() {
return this.height;
}
setSize(width, height) {
this.setWidth(width || 0);
this.setHeight(height || 0);
}
/**
* to data url
* @method
* @name Konva.Canvas#toDataURL
* @param {String} mimeType
* @param {Number} quality between 0 and 1 for jpg mime types
* @returns {String} data url string
*/
toDataURL(mimeType, quality) {
try {
// If this call fails (due to browser bug, like in Firefox 3.6),
// then revert to previous no-parameter image/png behavior
return this._canvas.toDataURL(mimeType, quality);
}
catch (e) {
try {
return this._canvas.toDataURL();
}
catch (err) {
Util.error('Unable to get data URL. ' +
err.message +
' For more info read https://konvajs.org/docs/posts/Tainted_Canvas.html.');
return '';
}
}
}
}
/**
* get/set pixel ratio.
* KonvaJS automatically handles pixel ratio adustments in order to render crisp drawings
* on all devices. Most desktops, low end tablets, and low end phones, have device pixel ratios
* of 1. Some high end tablets and phones, like iPhones and iPads have a device pixel ratio
* of 2. Some Macbook Pros, and iMacs also have a device pixel ratio of 2. Some high end Android devices have pixel
* ratios of 2 or 3. Some browsers like Firefox allow you to configure the pixel ratio of the viewport. Unless otherwise
* specificed, the pixel ratio will be defaulted to the actual device pixel ratio. You can override the device pixel
* ratio for special situations, or, if you don't want the pixel ratio to be taken into account, you can set it to 1.
* @name Konva.Canvas#pixelRatio
* @method
* @param {Number} pixelRatio
* @returns {Number}
* @example
* // get
* var pixelRatio = layer.getCanvas.pixelRatio();
*
* // set
* layer.getCanvas().pixelRatio(3);
*/
Factory.addGetterSetter(Canvas, 'pixelRatio', undefined, getNumberValidator());
class SceneCanvas extends Canvas {
constructor(config = { width: 0, height: 0 }) {
super(config);
this.context = new SceneContext(this);
this.setSize(config.width, config.height);
}
}
class HitCanvas extends Canvas {
constructor(config = { width: 0, height: 0 }) {
super(config);
this.hitCanvas = true;
this.context = new HitContext(this);
this.setSize(config.width, config.height);
}
}
const DD = {
get isDragging() {
var flag = false;
DD._dragElements.forEach((elem) => {
if (elem.dragStatus === 'dragging') {
flag = true;
}
});
return flag;
},
justDragged: false,
get node() {
// return first dragging node
var node;
DD._dragElements.forEach((elem) => {
node = elem.node;
});
return node;
},
_dragElements: new Map(),
// methods
_drag(evt) {
const nodesToFireEvents = [];
DD._dragElements.forEach((elem, key) => {
const { node } = elem;
// we need to find pointer relative to that node
const stage = node.getStage();
stage.setPointersPositions(evt);
// it is possible that user call startDrag without any event
// it that case we need to detect first movable pointer and attach it into the node
if (elem.pointerId === undefined) {
elem.pointerId = Util._getFirstPointerId(evt);
}
const pos = stage._changedPointerPositions.find((pos) => pos.id === elem.pointerId);
// not related pointer
if (!pos) {
return;
}
if (elem.dragStatus !== 'dragging') {
var dragDistance = node.dragDistance();
var distance = Math.max(Math.abs(pos.x - elem.startPointerPos.x), Math.abs(pos.y - elem.startPointerPos.y));
if (distance < dragDistance) {
return;
}
node.startDrag({ evt });
// a user can stop dragging inside `dragstart`
if (!node.isDragging()) {
return;
}
}
node._setDragPosition(evt, elem);
nodesToFireEvents.push(node);
});
// call dragmove only after ALL positions are changed
nodesToFireEvents.forEach((node) => {
node.fire('dragmove', {
type: 'dragmove',
target: node,
evt: evt,
}, true);
});
},
// dragBefore and dragAfter allows us to set correct order of events
// setup all in dragbefore, and stop dragging only after pointerup triggered.
_endDragBefore(evt) {
DD._dragElements.forEach((elem) => {
const { node } = elem;
// we need to find pointer relative to that node
const stage = node.getStage();
if (evt) {
stage.setPointersPositions(evt);
}
const pos = stage._changedPointerPositions.find((pos) => pos.id === elem.pointerId);
// that pointer is not related
if (!pos) {
return;
}
if (elem.dragStatus === 'dragging' || elem.dragStatus === 'stopped') {
// if a node is stopped manually we still need to reset events:
DD.justDragged = true;
Konva$2._mouseListenClick = false;
Konva$2._touchListenClick = false;
Konva$2._pointerListenClick = false;
elem.dragStatus = 'stopped';
}
const drawNode = elem.node.getLayer() ||
(elem.node instanceof Konva$2['Stage'] && elem.node);
if (drawNode) {
drawNode.batchDraw();
}
});
},
_endDragAfter(evt) {
DD._dragElements.forEach((elem, key) => {
if (elem.dragStatus === 'stopped') {
elem.node.fire('dragend', {
type: 'dragend',
target: elem.node,
evt: evt,
}, true);
}
if (elem.dragStatus !== 'dragging') {
DD._dragElements.delete(key);
}
});
},
};
if (Konva$2.isBrowser) {
window.addEventListener('mouseup', DD._endDragBefore, true);
window.addEventListener('touchend', DD._endDragBefore, true);
window.addEventListener('mousemove', DD._drag);
window.addEventListener('touchmove', DD._drag);
window.addEventListener('mouseup', DD._endDragAfter, false);
window.addEventListener('touchend', DD._endDragAfter, false);
}
// CONSTANTS
var ABSOLUTE_OPACITY = 'absoluteOpacity', ALL_LISTENERS = 'allEventListeners', ABSOLUTE_TRANSFORM = 'absoluteTransform', ABSOLUTE_SCALE = 'absoluteScale', CANVAS = 'canvas', CHANGE = 'Change', CHILDREN = 'children', KONVA = 'konva', LISTENING = 'listening', MOUSEENTER$1 = 'mouseenter', MOUSELEAVE$1 = 'mouseleave', SET = 'set', SHAPE = 'Shape', SPACE$1 = ' ', STAGE$1 = 'stage', TRANSFORM = 'transform', UPPER_STAGE = 'Stage', VISIBLE = 'visible', TRANSFORM_CHANGE_STR$1 = [
'xChange.konva',
'yChange.konva',
'scaleXChange.konva',
'scaleYChange.konva',
'skewXChange.konva',
'skewYChange.konva',
'rotationChange.konva',
'offsetXChange.konva',
'offsetYChange.konva',
'transformsEnabledChange.konva',
].join(SPACE$1);
let idCounter$1 = 1;
/**
* Node constructor. Nodes are entities that can be transformed, layered,
* and have bound events. The stage, layers, groups, and shapes all extend Node.
* @constructor
* @memberof Konva
* @param {Object} config
* @param {Number} [config.x]
* @param {Number} [config.y]
* @param {Number} [config.width]
* @param {Number} [config.height]
* @param {Boolean} [config.visible]
* @param {Boolean} [config.listening] whether or not the node is listening for events
* @param {String} [config.id] unique id
* @param {String} [config.name] non-unique name
* @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1
* @param {Object} [config.scale] set scale
* @param {Number} [config.scaleX] set scale x
* @param {Number} [config.scaleY] set scale y
* @param {Number} [config.rotation] rotation in degrees
* @param {Object} [config.offset] offset from center point and rotation point
* @param {Number} [config.offsetX] set offset x
* @param {Number} [config.offsetY] set offset y
* @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop
* the entire stage by dragging any portion of the stage
* @param {Number} [config.dragDistance]
* @param {Function} [config.dragBoundFunc]
*/
class Node {
constructor(config) {
this._id = idCounter$1++;
this.eventListeners = {};
this.attrs = {};
this.index = 0;
this._allEventListeners = null;
this.parent = null;
this._cache = new Map();
this._attachedDepsListeners = new Map();
this._lastPos = null;
this._batchingTransformChange = false;
this._needClearTransformCache = false;
this._filterUpToDate = false;
this._isUnderCache = false;
this._dragEventId = null;
this._shouldFireChangeEvents = false;
// on initial set attrs wi don't need to fire change events
// because nobody is listening to them yet
this.setAttrs(config);
this._shouldFireChangeEvents = true;
// all change event listeners are attached to the prototype
}
hasChildren() {
return false;
}
_clearCache(attr) {
// if we want to clear transform cache
// we don't really need to remove it from the cache
// but instead mark as "dirty"
// so we don't need to create a new instance next time
if ((attr === TRANSFORM || attr === ABSOLUTE_TRANSFORM) &&
this._cache.get(attr)) {
this._cache.get(attr).dirty = true;
}
else if (attr) {
this._cache.delete(attr);
}
else {
this._cache.clear();
}
}
_getCache(attr, privateGetter) {
var cache = this._cache.get(attr);
// for transform the cache can be NOT empty
// but we still need to recalculate it if it is dirty
var isTransform = attr === TRANSFORM || attr === ABSOLUTE_TRANSFORM;
var invalid = cache === undefined || (isTransform && cache.dirty === true);
// if not cached, we need to set it using the private getter method.
if (invalid) {
cache = privateGetter.call(this);
this._cache.set(attr, cache);
}
return cache;
}
_calculate(name, deps, getter) {
// if we are trying to calculate function for the first time
// we need to attach listeners for change events
if (!this._attachedDepsListeners.get(name)) {
const depsString = deps.map((dep) => dep + 'Change.konva').join(SPACE$1);
this.on(depsString, () => {
this._clearCache(name);
});
this._attachedDepsListeners.set(name, true);
}
// just use cache function
return this._getCache(name, getter);
}
_getCanvasCache() {
return this._cache.get(CANVAS);
}
/*
* when the logic for a cached result depends on ancestor propagation, use this
* method to clear self and children cache
*/
_clearSelfAndDescendantCache(attr) {
this._clearCache(attr);
// trigger clear cache, so transformer can use it
if (attr === ABSOLUTE_TRANSFORM) {
this.fire('absoluteTransformChange');
}
}
/**
* clear cached canvas
* @method
* @name Konva.Node#clearCache
* @returns {Konva.Node}
* @example
* node.clearCache();
*/
clearCache() {
this._cache.delete(CANVAS);
this._clearSelfAndDescendantCache();
this._requestDraw();
return this;
}
/**
* cache node to improve drawing performance, apply filters, or create more accurate
* hit regions. For all basic shapes size of cache canvas will be automatically detected.
* If you need to cache your custom `Konva.Shape` instance you have to pass shape's bounding box
* properties. Look at [https://konvajs.org/docs/performance/Shape_Caching.html](https://konvajs.org/docs/performance/Shape_Caching.html) for more information.
* @method
* @name Konva.Node#cache
* @param {Object} [config]
* @param {Number} [config.x]
* @param {Number} [config.y]
* @param {Number} [config.width]
* @param {Number} [config.height]
* @param {Number} [config.offset] increase canvas size by `offset` pixel in all directions.
* @param {Boolean} [config.drawBorder] when set to true, a red border will be drawn around the cached
* region for debugging purposes
* @param {Number} [config.pixelRatio] change quality (or pixel ratio) of cached image. pixelRatio = 2 will produce 2x sized cache.
* @param {Boolean} [config.imageSmoothingEnabled] control imageSmoothingEnabled property of created canvas for cache
* @param {Number} [config.hitCanvasPixelRatio] change quality (or pixel ratio) of cached hit canvas.
* @returns {Konva.Node}
* @example
* // cache a shape with the x,y position of the bounding box at the center and
* // the width and height of the bounding box equal to the width and height of
* // the shape obtained from shape.width() and shape.height()
* image.cache();
*
* // cache a node and define the bounding box position and size
* node.cache({
* x: -30,
* y: -30,
* width: 100,
* height: 200
* });
*
* // cache a node and draw a red border around the bounding box
* // for debugging purposes
* node.cache({
* x: -30,
* y: -30,
* width: 100,
* height: 200,
* offset : 10,
* drawBorder: true
* });
*/
cache(config) {
var conf = config || {};
var rect = {};
// don't call getClientRect if we have all attributes
// it means call it only if have one undefined
if (conf.x === undefined ||
conf.y === undefined ||
conf.width === undefined ||
conf.height === undefined) {
rect = this.getClientRect({
skipTransform: true,
relativeTo: this.getParent(),
});
}
var width = Math.ceil(conf.width || rect.width), height = Math.ceil(conf.height || rect.height), pixelRatio = conf.pixelRatio, x = conf.x === undefined ? rect.x : conf.x, y = conf.y === undefined ? rect.y : conf.y, offset = conf.offset || 0, drawBorder = conf.drawBorder || false, hitCanvasPixelRatio = conf.hitCanvasPixelRatio || 1;
if (!width || !height) {
Util.error('Can not cache the node. Width or height of the node equals 0. Caching is skipped.');
return;
}
width += offset * 2;
height += offset * 2;
x -= offset;
y -= offset;
var cachedSceneCanvas = new SceneCanvas({
pixelRatio: pixelRatio,
width: width,
height: height,
}), cachedFilterCanvas = new SceneCanvas({
pixelRatio: pixelRatio,
width: 0,
height: 0,
}), cachedHitCanvas = new HitCanvas({
pixelRatio: hitCanvasPixelRatio,
width: width,
height: height,
}), sceneContext = cachedSceneCanvas.getContext(), hitContext = cachedHitCanvas.getContext();
cachedHitCanvas.isCache = true;
cachedSceneCanvas.isCache = true;
this._cache.delete(CANVAS);
this._filterUpToDate = false;
if (conf.imageSmoothingEnabled === false) {
cachedSceneCanvas.getContext()._context.imageSmoothingEnabled = false;
cachedFilterCanvas.getContext()._context.imageSmoothingEnabled = false;
}
sceneContext.save();
hitContext.save();
sceneContext.translate(-x, -y);
hitContext.translate(-x, -y);
// extra flag to skip on getAbsolute opacity calc
this._isUnderCache = true;
this._clearSelfAndDescendantCache(ABSOLUTE_OPACITY);
this._clearSelfAndDescendantCache(ABSOLUTE_SCALE);
this.drawScene(cachedSceneCanvas, this);
this.drawHit(cachedHitCanvas, this);
this._isUnderCache = false;
sceneContext.restore();
hitContext.restore();
// this will draw a red border around the cached box for
// debugging purposes
if (drawBorder) {
sceneContext.save();
sceneContext.beginPath();
sceneContext.rect(0, 0, width, height);
sceneContext.closePath();
sceneContext.setAttr('strokeStyle', 'red');
sceneContext.setAttr('lineWidth', 5);
sceneContext.stroke();
sceneContext.restore();
}
this._cache.set(CANVAS, {
scene: cachedSceneCanvas,
filter: cachedFilterCanvas,
hit: cachedHitCanvas,
x: x,
y: y,
});
this._requestDraw();
return this;
}
/**
* determine if node is currently cached
* @method
* @name Konva.Node#isCached
* @returns {Boolean}
*/
isCached() {
return this._cache.has(CANVAS);
}
/**
* Return client rectangle {x, y, width, height} of node. This rectangle also include all styling (strokes, shadows, etc).
* The purpose of the method is similar to getBoundingClientRect API of the DOM.
* @method
* @name Konva.Node#getClientRect
* @param {Object} config
* @param {Boolean} [config.skipTransform] should we apply transform to node for calculating rect?
* @param {Boolean} [config.skipShadow] should we apply shadow to the node for calculating bound box?
* @param {Boolean} [config.skipStroke] should we apply stroke to the node for calculating bound box?
* @param {Object} [config.relativeTo] calculate client rect relative to one of the parents
* @returns {Object} rect with {x, y, width, height} properties
* @example
* var rect = new Konva.Rect({
* width : 100,
* height : 100,
* x : 50,
* y : 50,
* strokeWidth : 4,
* stroke : 'black',
* offsetX : 50,
* scaleY : 2
* });
*
* // get client rect without think off transformations (position, rotation, scale, offset, etc)
* rect.getClientRect({ skipTransform: true});
* // returns {
* // x : -2, // two pixels for stroke / 2
* // y : -2,
* // width : 104, // increased by 4 for stroke
* // height : 104
* //}
*
* // get client rect with transformation applied
* rect.getClientRect();
* // returns Object {x: -2, y: 46, width: 104, height: 208}
*/
getClientRect(config) {
// abstract method
// redefine in Container and Shape
throw new Error('abstract "getClientRect" method call');
}
_transformedRect(rect, top) {
var points = [
{ x: rect.x, y: rect.y },
{ x: rect.x + rect.width, y: rect.y },
{ x: rect.x + rect.width, y: rect.y + rect.height },
{ x: rect.x, y: rect.y + rect.height },
];
var minX, minY, maxX, maxY;
var trans = this.getAbsoluteTransform(top);
points.forEach(function (point) {
var transformed = trans.point(point);
if (minX === undefined) {
minX = maxX = transformed.x;
minY = maxY = transformed.y;
}
minX = Math.min(minX, transformed.x);
minY = Math.min(minY, transformed.y);
maxX = Math.max(maxX, transformed.x);
maxY = Math.max(maxY, transformed.y);
});
return {
x: minX,
y: minY,
width: maxX - minX,
height: maxY - minY,
};
}
_drawCachedSceneCanvas(context) {
context.save();
context._applyOpacity(this);
context._applyGlobalCompositeOperation(this);
const canvasCache = this._getCanvasCache();
context.translate(canvasCache.x, canvasCache.y);
var cacheCanvas = this._getCachedSceneCanvas();
var ratio = cacheCanvas.pixelRatio;
context.drawImage(cacheCanvas._canvas, 0, 0, cacheCanvas.width / ratio, cacheCanvas.height / ratio);
context.restore();
}
_drawCachedHitCanvas(context) {
var canvasCache = this._getCanvasCache(), hitCanvas = canvasCache.hit;
context.save();
context.translate(canvasCache.x, canvasCache.y);
context.drawImage(hitCanvas._canvas, 0, 0, hitCanvas.width / hitCanvas.pixelRatio, hitCanvas.height / hitCanvas.pixelRatio);
context.restore();
}
_getCachedSceneCanvas() {
var filters = this.filters(), cachedCanvas = this._getCanvasCache(), sceneCanvas = cachedCanvas.scene, filterCanvas = cachedCanvas.filter, filterContext = filterCanvas.getContext(), len, imageData, n, filter;
if (filters) {
if (!this._filterUpToDate) {
var ratio = sceneCanvas.pixelRatio;
filterCanvas.setSize(sceneCanvas.width / sceneCanvas.pixelRatio, sceneCanvas.height / sceneCanvas.pixelRatio);
try {
len = filters.length;
filterContext.clear();
// copy cached canvas onto filter context
filterContext.drawImage(sceneCanvas._canvas, 0, 0, sceneCanvas.getWidth() / ratio, sceneCanvas.getHeight() / ratio);
imageData = filterContext.getImageData(0, 0, filterCanvas.getWidth(), filterCanvas.getHeight());
// apply filters to filter context
for (n = 0; n < len; n++) {
filter = filters[n];
if (typeof filter !== 'function') {
Util.error('Filter should be type of function, but got ' +
typeof filter +
' instead. Please check correct filters');
continue;
}
filter.call(this, imageData);
filterContext.putImageData(imageData, 0, 0);
}
}
catch (e) {
Util.error('Unable to apply filter. ' +
e.message +
' This post my help you https://konvajs.org/docs/posts/Tainted_Canvas.html.');
}
this._filterUpToDate = true;
}
return filterCanvas;
}
return sceneCanvas;
}
/**
* bind events to the node. KonvaJS supports mouseover, mousemove,
* mouseout, mouseenter, mouseleave, mousedown, mouseup, wheel, contextmenu, click, dblclick, touchstart, touchmove,
* touchend, tap, dbltap, dragstart, dragmove, and dragend events.
* Pass in a string of events delimited by a space to bind multiple events at once
* such as 'mousedown mouseup mousemove'. Include a namespace to bind an
* event by name such as 'click.foobar'.
* @method
* @name Konva.Node#on
* @param {String} evtStr e.g. 'click', 'mousedown touchstart', 'mousedown.foo touchstart.foo'
* @param {Function} handler The handler function. The first argument of that function is event object. Event object has `target` as main target of the event, `currentTarget` as current node listener and `evt` as native browser event.
* @returns {Konva.Node}
* @example
* // add click listener
* node.on('click', function() {
* console.log('you clicked me!');
* });
*
* // get the target node
* node.on('click', function(evt) {
* console.log(evt.target);
* });
*
* // stop event propagation
* node.on('click', function(evt) {
* evt.cancelBubble = true;
* });
*
* // bind multiple listeners
* node.on('click touchstart', function() {
* console.log('you clicked/touched me!');
* });
*
* // namespace listener
* node.on('click.foo', function() {
* console.log('you clicked/touched me!');
* });
*
* // get the event type
* node.on('click tap', function(evt) {
* var eventType = evt.type;
* });
*
* // get native event object
* node.on('click tap', function(evt) {
* var nativeEvent = evt.evt;
* });
*
* // for change events, get the old and new val
* node.on('xChange', function(evt) {
* var oldVal = evt.oldVal;
* var newVal = evt.newVal;
* });
*
* // get event targets
* // with event delegations
* layer.on('click', 'Group', function(evt) {
* var shape = evt.target;
* var group = evt.currentTarget;
* });
*/
on(evtStr, handler) {
this._cache && this._cache.delete(ALL_LISTENERS);
if (arguments.length === 3) {
return this._delegate.apply(this, arguments);
}
var events = evtStr.split(SPACE$1), len = events.length, n, event, parts, baseEvent, name;
/*
* loop through types and attach event listeners to
* each one. eg. 'click mouseover.namespace mouseout'
* will create three event bindings
*/
for (n = 0; n < len; n++) {
event = events[n];
parts = event.split('.');
baseEvent = parts[0];
name = parts[1] || '';
// create events array if it doesn't exist
if (!this.eventListeners[baseEvent]) {
this.eventListeners[baseEvent] = [];
}
this.eventListeners[baseEvent].push({
name: name,
handler: handler,
});
}
return this;
}
/**
* remove event bindings from the node. Pass in a string of
* event types delimmited by a space to remove multiple event
* bindings at once such as 'mousedown mouseup mousemove'.
* include a namespace to remove an event binding by name
* such as 'click.foobar'. If you only give a name like '.foobar',
* all events in that namespace will be removed.
* @method
* @name Konva.Node#off
* @param {String} evtStr e.g. 'click', 'mousedown touchstart', '.foobar'
* @returns {Konva.Node}
* @example
* // remove listener
* node.off('click');
*
* // remove multiple listeners
* node.off('click touchstart');
*
* // remove listener by name
* node.off('click.foo');
*/
off(evtStr, callback) {
var events = (evtStr || '').split(SPACE$1), len = events.length, n, t, event, parts, baseEvent, name;
this._cache && this._cache.delete(ALL_LISTENERS);
if (!evtStr) {
// remove all events
for (t in this.eventListeners) {
this._off(t);
}
}
for (n = 0; n < len; n++) {
event = events[n];
parts = event.split('.');
baseEvent = parts[0];
name = parts[1];
if (baseEvent) {
if (this.eventListeners[baseEvent]) {
this._off(baseEvent, name, callback);
}
}
else {
for (t in this.eventListeners) {
this._off(t, name, callback);
}
}
}
return this;
}
// some event aliases for third party integration like HammerJS
dispatchEvent(evt) {
var e = {
target: this,
type: evt.type,
evt: evt,
};
this.fire(evt.type, e);
return this;
}
addEventListener(type, handler) {
// we have to pass native event to handler
this.on(type, function (evt) {
handler.call(this, evt.evt);
});
return this;
}
removeEventListener(type) {
this.off(type);
return this;
}
// like node.on
_delegate(event, selector, handler) {
var stopNode = this;
this.on(event, function (evt) {
var targets = evt.target.findAncestors(selector, true, stopNode);
for (var i = 0; i < targets.length; i++) {
evt = Util.cloneObject(evt);
evt.currentTarget = targets[i];
handler.call(targets[i], evt);
}
});
}
/**
* remove a node from parent, but don't destroy. You can reuse the node later.
* @method
* @name Konva.Node#remove
* @returns {Konva.Node}
* @example
* node.remove();
*/
remove() {
if (this.isDragging()) {
this.stopDrag();
}
// we can have drag element but that is not dragged yet
// so just clear it
DD._dragElements.delete(this._id);
this._remove();
return this;
}
_clearCaches() {
this._clearSelfAndDescendantCache(ABSOLUTE_TRANSFORM);
this._clearSelfAndDescendantCache(ABSOLUTE_OPACITY);
this._clearSelfAndDescendantCache(ABSOLUTE_SCALE);
this._clearSelfAndDescendantCache(STAGE$1);
this._clearSelfAndDescendantCache(VISIBLE);
this._clearSelfAndDescendantCache(LISTENING);
}
_remove() {
// every cached attr that is calculated via node tree
// traversal must be cleared when removing a node
this._clearCaches();
var parent = this.getParent();
if (parent && parent.children) {
parent.children.splice(this.index, 1);
parent._setChildrenIndices();
this.parent = null;
}
}
/**
* remove and destroy a node. Kill it and delete forever! You should not reuse node after destroy().
* If the node is a container (Group, Stage or Layer) it will destroy all children too.
* @method
* @name Konva.Node#destroy
* @example
* node.destroy();
*/
destroy() {
this.remove();
return this;
}
/**
* get attr
* @method
* @name Konva.Node#getAttr
* @param {String} attr
* @returns {Integer|String|Object|Array}
* @example
* var x = node.getAttr('x');
*/
getAttr(attr) {
var method = 'get' + Util._capitalize(attr);
if (Util._isFunction(this[method])) {
return this[method]();
}
// otherwise get directly
return this.attrs[attr];
}
/**
* get ancestors
* @method
* @name Konva.Node#getAncestors
* @returns {Array}
* @example
* shape.getAncestors().forEach(function(node) {
* console.log(node.getId());
* })
*/
getAncestors() {
var parent = this.getParent(), ancestors = [];
while (parent) {
ancestors.push(parent);
parent = parent.getParent();
}
return ancestors;
}
/**
* get attrs object literal
* @method
* @name Konva.Node#getAttrs
* @returns {Object}
*/
getAttrs() {
return this.attrs || {};
}
/**
* set multiple attrs at once using an object literal
* @method
* @name Konva.Node#setAttrs
* @param {Object} config object containing key value pairs
* @returns {Konva.Node}
* @example
* node.setAttrs({
* x: 5,
* fill: 'red'
* });
*/
setAttrs(config) {
this._batchTransformChanges(() => {
var key, method;
if (!config) {
return this;
}
for (key in config) {
if (key === CHILDREN) {
continue;
}
method = SET + Util._capitalize(key);
// use setter if available
if (Util._isFunction(this[method])) {
this[method](config[key]);
}
else {
// otherwise set directly
this._setAttr(key, config[key]);
}
}
});
return this;
}
/**
* determine if node is listening for events by taking into account ancestors.
*
* Parent | Self | isListening
* listening | listening |
* ----------+-----------+------------
* T | T | T
* T | F | F
* F | T | F
* F | F | F
*
* @method
* @name Konva.Node#isListening
* @returns {Boolean}
*/
isListening() {
return this._getCache(LISTENING, this._isListening);
}
_isListening(relativeTo) {
const listening = this.listening();
if (!listening) {
return false;
}
const parent = this.getParent();
if (parent && parent !== relativeTo && this !== relativeTo) {
return parent._isListening(relativeTo);
}
else {
return true;
}
}
/**
* determine if node is visible by taking into account ancestors.
*
* Parent | Self | isVisible
* visible | visible |
* ----------+-----------+------------
* T | T | T
* T | F | F
* F | T | F
* F | F | F
* @method
* @name Konva.Node#isVisible
* @returns {Boolean}
*/
isVisible() {
return this._getCache(VISIBLE, this._isVisible);
}
_isVisible(relativeTo) {
const visible = this.visible();
if (!visible) {
return false;
}
const parent = this.getParent();
if (parent && parent !== relativeTo && this !== relativeTo) {
return parent._isVisible(relativeTo);
}
else {
return true;
}
}
shouldDrawHit(top, skipDragCheck = false) {
if (top) {
return this._isVisible(top) && this._isListening(top);
}
var layer = this.getLayer();
var layerUnderDrag = false;
DD._dragElements.forEach((elem) => {
if (elem.dragStatus !== 'dragging') {
return;
}
else if (elem.node.nodeType === 'Stage') {
layerUnderDrag = true;
}
else if (elem.node.getLayer() === layer) {
layerUnderDrag = true;
}
});
var dragSkip = !skipDragCheck && !Konva$2.hitOnDragEnabled && layerUnderDrag;
return this.isListening() && this.isVisible() && !dragSkip;
}
/**
* show node. set visible = true
* @method
* @name Konva.Node#show
* @returns {Konva.Node}
*/
show() {
this.visible(true);
return this;
}
/**
* hide node. Hidden nodes are no longer detectable
* @method
* @name Konva.Node#hide
* @returns {Konva.Node}
*/
hide() {
this.visible(false);
return this;
}
getZIndex() {
return this.index || 0;
}
/**
* get absolute z-index which takes into account sibling
* and ancestor indices
* @method
* @name Konva.Node#getAbsoluteZIndex
* @returns {Integer}
*/
getAbsoluteZIndex() {
var depth = this.getDepth(), that = this, index = 0, nodes, len, n, child;
function addChildren(children) {
nodes = [];
len = children.length;
for (n = 0; n < len; n++) {
child = children[n];
index++;
if (child.nodeType !== SHAPE) {
nodes = nodes.concat(child.getChildren().slice());
}
if (child._id === that._id) {
n = len;
}
}
if (nodes.length > 0 && nodes[0].getDepth() <= depth) {
addChildren(nodes);
}
}
if (that.nodeType !== UPPER_STAGE) {
addChildren(that.getStage().getChildren());
}
return index;
}
/**
* get node depth in node tree. Returns an integer.
* e.g. Stage depth will always be 0. Layers will always be 1. Groups and Shapes will always
* be >= 2
* @method
* @name Konva.Node#getDepth
* @returns {Integer}
*/
getDepth() {
var depth = 0, parent = this.parent;
while (parent) {
depth++;
parent = parent.parent;
}
return depth;
}
// sometimes we do several attributes changes
// like node.position(pos)
// for performance reasons, lets batch transform reset
// so it work faster
_batchTransformChanges(func) {
this._batchingTransformChange = true;
func();
this._batchingTransformChange = false;
if (this._needClearTransformCache) {
this._clearCache(TRANSFORM);
this._clearSelfAndDescendantCache(ABSOLUTE_TRANSFORM);
}
this._needClearTransformCache = false;
}
setPosition(pos) {
this._batchTransformChanges(() => {
this.x(pos.x);
this.y(pos.y);
});
return this;
}
getPosition() {
return {
x: this.x(),
y: this.y(),
};
}
/**
* get position of first pointer (like mouse or first touch) relative to local coordinates of current node
* @method
* @name Konva.Node#getRelativePointerPosition
* @returns {Konva.Node}
* @example
*
* // let's think we have a rectangle at position x = 10, y = 10
* // now we clicked at x = 15, y = 15 of the stage
* // if you want to know position of the click, related to the rectangle you can use
* rect.getRelativePointerPosition();
*/
getRelativePointerPosition() {
if (!this.getStage()) {
return null;
}
// get pointer (say mouse or touch) position
var pos = this.getStage().getPointerPosition();
if (!pos) {
return null;
}
var transform = this.getAbsoluteTransform().copy();
// to detect relative position we need to invert transform
transform.invert();
// now we can find relative point
return transform.point(pos);
}
/**
* get absolute position of a node. That function can be used to calculate absolute position, but relative to any ancestor
* @method
* @name Konva.Node#getAbsolutePosition
* @param {Object} Ancestor optional ancestor node
* @returns {Konva.Node}
* @example
*
* // returns absolute position relative to top-left corner of canvas
* node.getAbsolutePosition();
*
* // calculate absolute position of node, inside stage
* // so stage transforms are ignored
* node.getAbsolutePosition(stage)
*/
getAbsolutePosition(top) {
let haveCachedParent = false;
let parent = this.parent;
while (parent) {
if (parent.isCached()) {
haveCachedParent = true;
break;
}
parent = parent.parent;
}
if (haveCachedParent && !top) {
// make fake top element
// "true" is not a node, but it will just allow skip all caching
top = true;
}
var absoluteMatrix = this.getAbsoluteTransform(top).getMatrix(), absoluteTransform = new Transform(), offset = this.offset();
// clone the matrix array
absoluteTransform.m = absoluteMatrix.slice();
absoluteTransform.translate(offset.x, offset.y);
return absoluteTransform.getTranslation();
}
setAbsolutePosition(pos) {
var origTrans = this._clearTransform();
// don't clear translation
this.attrs.x = origTrans.x;
this.attrs.y = origTrans.y;
delete origTrans.x;
delete origTrans.y;
// important, use non cached value
this._clearCache(TRANSFORM);
var it = this._getAbsoluteTransform().copy();
it.invert();
it.translate(pos.x, pos.y);
pos = {
x: this.attrs.x + it.getTranslation().x,
y: this.attrs.y + it.getTranslation().y,
};
this._setTransform(origTrans);
this.setPosition({ x: pos.x, y: pos.y });
this._clearCache(TRANSFORM);
this._clearSelfAndDescendantCache(ABSOLUTE_TRANSFORM);
return this;
}
_setTransform(trans) {
var key;
for (key in trans) {
this.attrs[key] = trans[key];
}
// this._clearCache(TRANSFORM);
// this._clearSelfAndDescendantCache(ABSOLUTE_TRANSFORM);
}
_clearTransform() {
var trans = {
x: this.x(),
y: this.y(),
rotation: this.rotation(),
scaleX: this.scaleX(),
scaleY: this.scaleY(),
offsetX: this.offsetX(),
offsetY: this.offsetY(),
skewX: this.skewX(),
skewY: this.skewY(),
};
this.attrs.x = 0;
this.attrs.y = 0;
this.attrs.rotation = 0;
this.attrs.scaleX = 1;
this.attrs.scaleY = 1;
this.attrs.offsetX = 0;
this.attrs.offsetY = 0;
this.attrs.skewX = 0;
this.attrs.skewY = 0;
// return original transform
return trans;
}
/**
* move node by an amount relative to its current position
* @method
* @name Konva.Node#move
* @param {Object} change
* @param {Number} change.x
* @param {Number} change.y
* @returns {Konva.Node}
* @example
* // move node in x direction by 1px and y direction by 2px
* node.move({
* x: 1,
* y: 2
* });
*/
move(change) {
var changeX = change.x, changeY = change.y, x = this.x(), y = this.y();
if (changeX !== undefined) {
x += changeX;
}
if (changeY !== undefined) {
y += changeY;
}
this.setPosition({ x: x, y: y });
return this;
}
_eachAncestorReverse(func, top) {
var family = [], parent = this.getParent(), len, n;
// if top node is defined, and this node is top node,
// there's no need to build a family tree. just execute
// func with this because it will be the only node
if (top && top._id === this._id) {
// func(this);
return;
}
family.unshift(this);
while (parent && (!top || parent._id !== top._id)) {
family.unshift(parent);
parent = parent.parent;
}
len = family.length;
for (n = 0; n < len; n++) {
func(family[n]);
}
}
/**
* rotate node by an amount in degrees relative to its current rotation
* @method
* @name Konva.Node#rotate
* @param {Number} theta
* @returns {Konva.Node}
*/
rotate(theta) {
this.rotation(this.rotation() + theta);
return this;
}
/**
* move node to the top of its siblings
* @method
* @name Konva.Node#moveToTop
* @returns {Boolean}
*/
moveToTop() {
if (!this.parent) {
Util.warn('Node has no parent. moveToTop function is ignored.');
return false;
}
var index = this.index, len = this.parent.getChildren().length;
if (index < len - 1) {
this.parent.children.splice(index, 1);
this.parent.children.push(this);
this.parent._setChildrenIndices();
return true;
}
return false;
}
/**
* move node up
* @method
* @name Konva.Node#moveUp
* @returns {Boolean} flag is moved or not
*/
moveUp() {
if (!this.parent) {
Util.warn('Node has no parent. moveUp function is ignored.');
return false;
}
var index = this.index, len = this.parent.getChildren().length;
if (index < len - 1) {
this.parent.children.splice(index, 1);
this.parent.children.splice(index + 1, 0, this);
this.parent._setChildrenIndices();
return true;
}
return false;
}
/**
* move node down
* @method
* @name Konva.Node#moveDown
* @returns {Boolean}
*/
moveDown() {
if (!this.parent) {
Util.warn('Node has no parent. moveDown function is ignored.');
return false;
}
var index = this.index;
if (index > 0) {
this.parent.children.splice(index, 1);
this.parent.children.splice(index - 1, 0, this);
this.parent._setChildrenIndices();
return true;
}
return false;
}
/**
* move node to the bottom of its siblings
* @method
* @name Konva.Node#moveToBottom
* @returns {Boolean}
*/
moveToBottom() {
if (!this.parent) {
Util.warn('Node has no parent. moveToBottom function is ignored.');
return false;
}
var index = this.index;
if (index > 0) {
this.parent.children.splice(index, 1);
this.parent.children.unshift(this);
this.parent._setChildrenIndices();
return true;
}
return false;
}
setZIndex(zIndex) {
if (!this.parent) {
Util.warn('Node has no parent. zIndex parameter is ignored.');
return this;
}
if (zIndex < 0 || zIndex >= this.parent.children.length) {
Util.warn('Unexpected value ' +
zIndex +
' for zIndex property. zIndex is just index of a node in children of its parent. Expected value is from 0 to ' +
(this.parent.children.length - 1) +
'.');
}
var index = this.index;
this.parent.children.splice(index, 1);
this.parent.children.splice(zIndex, 0, this);
this.parent._setChildrenIndices();
return this;
}
/**
* get absolute opacity
* @method
* @name Konva.Node#getAbsoluteOpacity
* @returns {Number}
*/
getAbsoluteOpacity() {
return this._getCache(ABSOLUTE_OPACITY, this._getAbsoluteOpacity);
}
_getAbsoluteOpacity() {
var absOpacity = this.opacity();
var parent = this.getParent();
if (parent && !parent._isUnderCache) {
absOpacity *= parent.getAbsoluteOpacity();
}
return absOpacity;
}
/**
* move node to another container
* @method
* @name Konva.Node#moveTo
* @param {Container} newContainer
* @returns {Konva.Node}
* @example
* // move node from current layer into layer2
* node.moveTo(layer2);
*/
moveTo(newContainer) {
// do nothing if new container is already parent
if (this.getParent() !== newContainer) {
this._remove();
newContainer.add(this);
}
return this;
}
/**
* convert Node into an object for serialization. Returns an object.
* @method
* @name Konva.Node#toObject
* @returns {Object}
*/
toObject() {
var obj = {}, attrs = this.getAttrs(), key, val, getter, defaultValue, nonPlainObject;
obj.attrs = {};
for (key in attrs) {
val = attrs[key];
// if value is object and object is not plain
// like class instance, we should skip it and to not include
nonPlainObject =
Util.isObject(val) && !Util._isPlainObject(val) && !Util._isArray(val);
if (nonPlainObject) {
continue;
}
getter = typeof this[key] === 'function' && this[key];
// remove attr value so that we can extract the default value from the getter
delete attrs[key];
defaultValue = getter ? getter.call(this) : null;
// restore attr value
attrs[key] = val;
if (defaultValue !== val) {
obj.attrs[key] = val;
}
}
obj.className = this.getClassName();
return Util._prepareToStringify(obj);
}
/**
* convert Node into a JSON string. Returns a JSON string.
* @method
* @name Konva.Node#toJSON
* @returns {String}
*/
toJSON() {
return JSON.stringify(this.toObject());
}
/**
* get parent container
* @method
* @name Konva.Node#getParent
* @returns {Konva.Node}
*/
getParent() {
return this.parent;
}
/**
* get all ancestors (parent then parent of the parent, etc) of the node
* @method
* @name Konva.Node#findAncestors
* @param {String} selector selector for search
* @param {Boolean} [includeSelf] show we think that node is ancestro itself?
* @param {Konva.Node} [stopNode] optional node where we need to stop searching (one of ancestors)
* @returns {Array} [ancestors]
* @example
* // get one of the parent group
* var parentGroups = node.findAncestors('Group');
*/
findAncestors(selector, includeSelf, stopNode) {
var res = [];
if (includeSelf && this._isMatch(selector)) {
res.push(this);
}
var ancestor = this.parent;
while (ancestor) {
if (ancestor === stopNode) {
return res;
}
if (ancestor._isMatch(selector)) {
res.push(ancestor);
}
ancestor = ancestor.parent;
}
return res;
}
isAncestorOf(node) {
return false;
}
/**
* get ancestor (parent or parent of the parent, etc) of the node that match passed selector
* @method
* @name Konva.Node#findAncestor
* @param {String} selector selector for search
* @param {Boolean} [includeSelf] show we think that node is ancestro itself?
* @param {Konva.Node} [stopNode] optional node where we need to stop searching (one of ancestors)
* @returns {Konva.Node} ancestor
* @example
* // get one of the parent group
* var group = node.findAncestors('.mygroup');
*/
findAncestor(selector, includeSelf, stopNode) {
return this.findAncestors(selector, includeSelf, stopNode)[0];
}
// is current node match passed selector?
_isMatch(selector) {
if (!selector) {
return false;
}
if (typeof selector === 'function') {
return selector(this);
}
var selectorArr = selector.replace(/ /g, '').split(','), len = selectorArr.length, n, sel;
for (n = 0; n < len; n++) {
sel = selectorArr[n];
if (!Util.isValidSelector(sel)) {
Util.warn('Selector "' +
sel +
'" is invalid. Allowed selectors examples are "#foo", ".bar" or "Group".');
Util.warn('If you have a custom shape with such className, please change it to start with upper letter like "Triangle".');
Util.warn('Konva is awesome, right?');
}
// id selector
if (sel.charAt(0) === '#') {
if (this.id() === sel.slice(1)) {
return true;
}
}
else if (sel.charAt(0) === '.') {
// name selector
if (this.hasName(sel.slice(1))) {
return true;
}
}
else if (this.className === sel || this.nodeType === sel) {
return true;
}
}
return false;
}
/**
* get layer ancestor
* @method
* @name Konva.Node#getLayer
* @returns {Konva.Layer}
*/
getLayer() {
var parent = this.getParent();
return parent ? parent.getLayer() : null;
}
/**
* get stage ancestor
* @method
* @name Konva.Node#getStage
* @returns {Konva.Stage}
*/
getStage() {
return this._getCache(STAGE$1, this._getStage);
}
_getStage() {
var parent = this.getParent();
if (parent) {
return parent.getStage();
}
else {
return undefined;
}
}
/**
* fire event
* @method
* @name Konva.Node#fire
* @param {String} eventType event type. can be a regular event, like click, mouseover, or mouseout, or it can be a custom event, like myCustomEvent
* @param {Event} [evt] event object
* @param {Boolean} [bubble] setting the value to false, or leaving it undefined, will result in the event
* not bubbling. Setting the value to true will result in the event bubbling.
* @returns {Konva.Node}
* @example
* // manually fire click event
* node.fire('click');
*
* // fire custom event
* node.fire('foo');
*
* // fire custom event with custom event object
* node.fire('foo', {
* bar: 10
* });
*
* // fire click event that bubbles
* node.fire('click', null, true);
*/
fire(eventType, evt = {}, bubble) {
evt.target = evt.target || this;
// bubble
if (bubble) {
this._fireAndBubble(eventType, evt);
}
else {
// no bubble
this._fire(eventType, evt);
}
return this;
}
/**
* get absolute transform of the node which takes into
* account its ancestor transforms
* @method
* @name Konva.Node#getAbsoluteTransform
* @returns {Konva.Transform}
*/
getAbsoluteTransform(top) {
// if using an argument, we can't cache the result.
if (top) {
return this._getAbsoluteTransform(top);
}
else {
// if no argument, we can cache the result
return this._getCache(ABSOLUTE_TRANSFORM, this._getAbsoluteTransform);
}
}
_getAbsoluteTransform(top) {
var at;
// we we need position relative to an ancestor, we will iterate for all
if (top) {
at = new Transform();
// start with stage and traverse downwards to self
this._eachAncestorReverse(function (node) {
var transformsEnabled = node.transformsEnabled();
if (transformsEnabled === 'all') {
at.multiply(node.getTransform());
}
else if (transformsEnabled === 'position') {
at.translate(node.x() - node.offsetX(), node.y() - node.offsetY());
}
}, top);
return at;
}
else {
// try to use a cached value
at = this._cache.get(ABSOLUTE_TRANSFORM) || new Transform();
if (this.parent) {
// transform will be cached
this.parent.getAbsoluteTransform().copyInto(at);
}
else {
at.reset();
}
var transformsEnabled = this.transformsEnabled();
if (transformsEnabled === 'all') {
at.multiply(this.getTransform());
}
else if (transformsEnabled === 'position') {
// use "attrs" directly, because it is a bit faster
const x = this.attrs.x || 0;
const y = this.attrs.y || 0;
const offsetX = this.attrs.offsetX || 0;
const offsetY = this.attrs.offsetY || 0;
at.translate(x - offsetX, y - offsetY);
}
at.dirty = false;
return at;
}
}
/**
* get absolute scale of the node which takes into
* account its ancestor scales
* @method
* @name Konva.Node#getAbsoluteScale
* @returns {Object}
* @example
* // get absolute scale x
* var scaleX = node.getAbsoluteScale().x;
*/
getAbsoluteScale(top) {
// do not cache this calculations,
// because it use cache transform
// this is special logic for caching with some shapes with shadow
var parent = this;
while (parent) {
if (parent._isUnderCache) {
top = parent;
}
parent = parent.getParent();
}
const transform = this.getAbsoluteTransform(top);
const attrs = transform.decompose();
return {
x: attrs.scaleX,
y: attrs.scaleY,
};
}
/**
* get absolute rotation of the node which takes into
* account its ancestor rotations
* @method
* @name Konva.Node#getAbsoluteRotation
* @returns {Number}
* @example
* // get absolute rotation
* var rotation = node.getAbsoluteRotation();
*/
getAbsoluteRotation() {
// var parent: Node = this;
// var rotation = 0;
// while (parent) {
// rotation += parent.rotation();
// parent = parent.getParent();
// }
// return rotation;
return this.getAbsoluteTransform().decompose().rotation;
}
/**
* get transform of the node
* @method
* @name Konva.Node#getTransform
* @returns {Konva.Transform}
*/
getTransform() {
return this._getCache(TRANSFORM, this._getTransform);
}
_getTransform() {
var _a, _b;
var m = this._cache.get(TRANSFORM) || new Transform();
m.reset();
// I was trying to use attributes directly here
// but it doesn't work for Transformer well
// because it overwrite x,y getters
var x = this.x(), y = this.y(), rotation = Konva$2.getAngle(this.rotation()), scaleX = (_a = this.attrs.scaleX) !== null && _a !== void 0 ? _a : 1, scaleY = (_b = this.attrs.scaleY) !== null && _b !== void 0 ? _b : 1, skewX = this.attrs.skewX || 0, skewY = this.attrs.skewY || 0, offsetX = this.attrs.offsetX || 0, offsetY = this.attrs.offsetY || 0;
if (x !== 0 || y !== 0) {
m.translate(x, y);
}
if (rotation !== 0) {
m.rotate(rotation);
}
if (skewX !== 0 || skewY !== 0) {
m.skew(skewX, skewY);
}
if (scaleX !== 1 || scaleY !== 1) {
m.scale(scaleX, scaleY);
}
if (offsetX !== 0 || offsetY !== 0) {
m.translate(-1 * offsetX, -1 * offsetY);
}
m.dirty = false;
return m;
}
/**
* clone node. Returns a new Node instance with identical attributes. You can also override
* the node properties with an object literal, enabling you to use an existing node as a template
* for another node
* @method
* @name Konva.Node#clone
* @param {Object} obj override attrs
* @returns {Konva.Node}
* @example
* // simple clone
* var clone = node.clone();
*
* // clone a node and override the x position
* var clone = rect.clone({
* x: 5
* });
*/
clone(obj) {
// instantiate new node
var attrs = Util.cloneObject(this.attrs), key, allListeners, len, n, listener;
// apply attr overrides
for (key in obj) {
attrs[key] = obj[key];
}
var node = new this.constructor(attrs);
// copy over listeners
for (key in this.eventListeners) {
allListeners = this.eventListeners[key];
len = allListeners.length;
for (n = 0; n < len; n++) {
listener = allListeners[n];
/*
* don't include konva namespaced listeners because
* these are generated by the constructors
*/
if (listener.name.indexOf(KONVA) < 0) {
// if listeners array doesn't exist, then create it
if (!node.eventListeners[key]) {
node.eventListeners[key] = [];
}
node.eventListeners[key].push(listener);
}
}
}
return node;
}
_toKonvaCanvas(config) {
config = config || {};
var box = this.getClientRect();
var stage = this.getStage(), x = config.x !== undefined ? config.x : box.x, y = config.y !== undefined ? config.y : box.y, pixelRatio = config.pixelRatio || 1, canvas = new SceneCanvas({
width: config.width || box.width || (stage ? stage.width() : 0),
height: config.height || box.height || (stage ? stage.height() : 0),
pixelRatio: pixelRatio,
}), context = canvas.getContext();
context.save();
if (x || y) {
context.translate(-1 * x, -1 * y);
}
this.drawScene(canvas);
context.restore();
return canvas;
}
/**
* converts node into an canvas element.
* @method
* @name Konva.Node#toCanvas
* @param {Object} config
* @param {Function} config.callback function executed when the composite has completed
* @param {Number} [config.x] x position of canvas section
* @param {Number} [config.y] y position of canvas section
* @param {Number} [config.width] width of canvas section
* @param {Number} [config.height] height of canvas section
* @param {Number} [config.pixelRatio] pixelRatio of output canvas. Default is 1.
* You can use that property to increase quality of the image, for example for super hight quality exports
* or usage on retina (or similar) displays. pixelRatio will be used to multiply the size of exported image.
* If you export to 500x500 size with pixelRatio = 2, then produced image will have size 1000x1000.
* @example
* var canvas = node.toCanvas();
*/
toCanvas(config) {
return this._toKonvaCanvas(config)._canvas;
}
/**
* Creates a composite data URL (base64 string). If MIME type is not
* specified, then "image/png" will result. For "image/jpeg", specify a quality
* level as quality (range 0.0 - 1.0)
* @method
* @name Konva.Node#toDataURL
* @param {Object} config
* @param {String} [config.mimeType] can be "image/png" or "image/jpeg".
* "image/png" is the default
* @param {Number} [config.x] x position of canvas section
* @param {Number} [config.y] y position of canvas section
* @param {Number} [config.width] width of canvas section
* @param {Number} [config.height] height of canvas section
* @param {Number} [config.quality] jpeg quality. If using an "image/jpeg" mimeType,
* you can specify the quality from 0 to 1, where 0 is very poor quality and 1
* is very high quality
* @param {Number} [config.pixelRatio] pixelRatio of output image url. Default is 1.
* You can use that property to increase quality of the image, for example for super hight quality exports
* or usage on retina (or similar) displays. pixelRatio will be used to multiply the size of exported image.
* If you export to 500x500 size with pixelRatio = 2, then produced image will have size 1000x1000.
* @returns {String}
*/
toDataURL(config) {
config = config || {};
var mimeType = config.mimeType || null, quality = config.quality || null;
var url = this._toKonvaCanvas(config).toDataURL(mimeType, quality);
if (config.callback) {
config.callback(url);
}
return url;
}
/**
* converts node into an image. Since the toImage
* method is asynchronous, a callback is required. toImage is most commonly used
* to cache complex drawings as an image so that they don't have to constantly be redrawn
* @method
* @name Konva.Node#toImage
* @param {Object} config
* @param {Function} config.callback function executed when the composite has completed
* @param {String} [config.mimeType] can be "image/png" or "image/jpeg".
* "image/png" is the default
* @param {Number} [config.x] x position of canvas section
* @param {Number} [config.y] y position of canvas section
* @param {Number} [config.width] width of canvas section
* @param {Number} [config.height] height of canvas section
* @param {Number} [config.quality] jpeg quality. If using an "image/jpeg" mimeType,
* you can specify the quality from 0 to 1, where 0 is very poor quality and 1
* is very high quality
* @param {Number} [config.pixelRatio] pixelRatio of output image. Default is 1.
* You can use that property to increase quality of the image, for example for super hight quality exports
* or usage on retina (or similar) displays. pixelRatio will be used to multiply the size of exported image.
* If you export to 500x500 size with pixelRatio = 2, then produced image will have size 1000x1000.
* @example
* var image = node.toImage({
* callback(img) {
* // do stuff with img
* }
* });
*/
toImage(config) {
if (!config || !config.callback) {
throw 'callback required for toImage method config argument';
}
var callback = config.callback;
delete config.callback;
Util._urlToImage(this.toDataURL(config), function (img) {
callback(img);
});
}
setSize(size) {
this.width(size.width);
this.height(size.height);
return this;
}
getSize() {
return {
width: this.width(),
height: this.height(),
};
}
/**
* get class name, which may return Stage, Layer, Group, or shape class names like Rect, Circle, Text, etc.
* @method
* @name Konva.Node#getClassName
* @returns {String}
*/
getClassName() {
return this.className || this.nodeType;
}
/**
* get the node type, which may return Stage, Layer, Group, or Shape
* @method
* @name Konva.Node#getType
* @returns {String}
*/
getType() {
return this.nodeType;
}
getDragDistance() {
// compare with undefined because we need to track 0 value
if (this.attrs.dragDistance !== undefined) {
return this.attrs.dragDistance;
}
else if (this.parent) {
return this.parent.getDragDistance();
}
else {
return Konva$2.dragDistance;
}
}
_off(type, name, callback) {
var evtListeners = this.eventListeners[type], i, evtName, handler;
for (i = 0; i < evtListeners.length; i++) {
evtName = evtListeners[i].name;
handler = evtListeners[i].handler;
// the following two conditions must be true in order to remove a handler:
// 1) the current event name cannot be konva unless the event name is konva
// this enables developers to force remove a konva specific listener for whatever reason
// 2) an event name is not specified, or if one is specified, it matches the current event name
if ((evtName !== 'konva' || name === 'konva') &&
(!name || evtName === name) &&
(!callback || callback === handler)) {
evtListeners.splice(i, 1);
if (evtListeners.length === 0) {
delete this.eventListeners[type];
break;
}
i--;
}
}
}
_fireChangeEvent(attr, oldVal, newVal) {
this._fire(attr + CHANGE, {
oldVal: oldVal,
newVal: newVal,
});
}
/**
* add name to node
* @method
* @name Konva.Node#addName
* @param {String} name
* @returns {Konva.Node}
* @example
* node.name('red');
* node.addName('selected');
* node.name(); // return 'red selected'
*/
addName(name) {
if (!this.hasName(name)) {
var oldName = this.name();
var newName = oldName ? oldName + ' ' + name : name;
this.name(newName);
}
return this;
}
/**
* check is node has name
* @method
* @name Konva.Node#hasName
* @param {String} name
* @returns {Boolean}
* @example
* node.name('red');
* node.hasName('red'); // return true
* node.hasName('selected'); // return false
* node.hasName(''); // return false
*/
hasName(name) {
if (!name) {
return false;
}
const fullName = this.name();
if (!fullName) {
return false;
}
// if name is '' the "names" will be [''], so I added extra check above
var names = (fullName || '').split(/\s/g);
return names.indexOf(name) !== -1;
}
/**
* remove name from node
* @method
* @name Konva.Node#removeName
* @param {String} name
* @returns {Konva.Node}
* @example
* node.name('red selected');
* node.removeName('selected');
* node.hasName('selected'); // return false
* node.name(); // return 'red'
*/
removeName(name) {
var names = (this.name() || '').split(/\s/g);
var index = names.indexOf(name);
if (index !== -1) {
names.splice(index, 1);
this.name(names.join(' '));
}
return this;
}
/**
* set attr
* @method
* @name Konva.Node#setAttr
* @param {String} attr
* @param {*} val
* @returns {Konva.Node}
* @example
* node.setAttr('x', 5);
*/
setAttr(attr, val) {
var func = this[SET + Util._capitalize(attr)];
if (Util._isFunction(func)) {
func.call(this, val);
}
else {
// otherwise set directly
this._setAttr(attr, val);
}
return this;
}
_requestDraw() {
if (Konva$2.autoDrawEnabled) {
const drawNode = this.getLayer() || this.getStage();
drawNode === null || drawNode === void 0 ? void 0 : drawNode.batchDraw();
}
}
_setAttr(key, val) {
var oldVal = this.attrs[key];
if (oldVal === val && !Util.isObject(val)) {
return;
}
if (val === undefined || val === null) {
delete this.attrs[key];
}
else {
this.attrs[key] = val;
}
if (this._shouldFireChangeEvents) {
this._fireChangeEvent(key, oldVal, val);
}
this._requestDraw();
}
_setComponentAttr(key, component, val) {
var oldVal;
if (val !== undefined) {
oldVal = this.attrs[key];
if (!oldVal) {
// set value to default value using getAttr
this.attrs[key] = this.getAttr(key);
}
this.attrs[key][component] = val;
this._fireChangeEvent(key, oldVal, val);
}
}
_fireAndBubble(eventType, evt, compareShape) {
if (evt && this.nodeType === SHAPE) {
evt.target = this;
}
var shouldStop = (eventType === MOUSEENTER$1 || eventType === MOUSELEAVE$1) &&
((compareShape &&
(this === compareShape ||
(this.isAncestorOf && this.isAncestorOf(compareShape)))) ||
(this.nodeType === 'Stage' && !compareShape));
if (!shouldStop) {
this._fire(eventType, evt);
// simulate event bubbling
var stopBubble = (eventType === MOUSEENTER$1 || eventType === MOUSELEAVE$1) &&
compareShape &&
compareShape.isAncestorOf &&
compareShape.isAncestorOf(this) &&
!compareShape.isAncestorOf(this.parent);
if (((evt && !evt.cancelBubble) || !evt) &&
this.parent &&
this.parent.isListening() &&
!stopBubble) {
if (compareShape && compareShape.parent) {
this._fireAndBubble.call(this.parent, eventType, evt, compareShape);
}
else {
this._fireAndBubble.call(this.parent, eventType, evt);
}
}
}
}
_getProtoListeners(eventType) {
let listeners = this._cache.get(ALL_LISTENERS);
// if no cache for listeners, we need to pre calculate it
if (!listeners) {
listeners = {};
let obj = Object.getPrototypeOf(this);
while (obj) {
if (!obj.eventListeners) {
obj = Object.getPrototypeOf(obj);
continue;
}
for (var event in obj.eventListeners) {
const newEvents = obj.eventListeners[event];
const oldEvents = listeners[event] || [];
listeners[event] = newEvents.concat(oldEvents);
}
obj = Object.getPrototypeOf(obj);
}
this._cache.set(ALL_LISTENERS, listeners);
}
return listeners[eventType];
}
_fire(eventType, evt) {
evt = evt || {};
evt.currentTarget = this;
evt.type = eventType;
const topListeners = this._getProtoListeners(eventType);
if (topListeners) {
for (var i = 0; i < topListeners.length; i++) {
topListeners[i].handler.call(this, evt);
}
}
// it is important to iterate over self listeners without cache
// because events can be added/removed while firing
const selfListeners = this.eventListeners[eventType];
if (selfListeners) {
for (var i = 0; i < selfListeners.length; i++) {
selfListeners[i].handler.call(this, evt);
}
}
}
/**
* draw both scene and hit graphs. If the node being drawn is the stage, all of the layers will be cleared and redrawn
* @method
* @name Konva.Node#draw
* @returns {Konva.Node}
*/
draw() {
this.drawScene();
this.drawHit();
return this;
}
// drag & drop
_createDragElement(evt) {
var pointerId = evt ? evt.pointerId : undefined;
var stage = this.getStage();
var ap = this.getAbsolutePosition();
var pos = stage._getPointerById(pointerId) ||
stage._changedPointerPositions[0] ||
ap;
DD._dragElements.set(this._id, {
node: this,
startPointerPos: pos,
offset: {
x: pos.x - ap.x,
y: pos.y - ap.y,
},
dragStatus: 'ready',
pointerId,
});
}
/**
* initiate drag and drop.
* @method
* @name Konva.Node#startDrag
*/
startDrag(evt, bubbleEvent = true) {
if (!DD._dragElements.has(this._id)) {
this._createDragElement(evt);
}
const elem = DD._dragElements.get(this._id);
elem.dragStatus = 'dragging';
this.fire('dragstart', {
type: 'dragstart',
target: this,
evt: evt && evt.evt,
}, bubbleEvent);
}
_setDragPosition(evt, elem) {
// const pointers = this.getStage().getPointersPositions();
// const pos = pointers.find(p => p.id === this._dragEventId);
const pos = this.getStage()._getPointerById(elem.pointerId);
if (!pos) {
return;
}
var newNodePos = {
x: pos.x - elem.offset.x,
y: pos.y - elem.offset.y,
};
var dbf = this.dragBoundFunc();
if (dbf !== undefined) {
const bounded = dbf.call(this, newNodePos, evt);
if (!bounded) {
Util.warn('dragBoundFunc did not return any value. That is unexpected behavior. You must return new absolute position from dragBoundFunc.');
}
else {
newNodePos = bounded;
}
}
if (!this._lastPos ||
this._lastPos.x !== newNodePos.x ||
this._lastPos.y !== newNodePos.y) {
this.setAbsolutePosition(newNodePos);
this._requestDraw();
}
this._lastPos = newNodePos;
}
/**
* stop drag and drop
* @method
* @name Konva.Node#stopDrag
*/
stopDrag(evt) {
const elem = DD._dragElements.get(this._id);
if (elem) {
elem.dragStatus = 'stopped';
}
DD._endDragBefore(evt);
DD._endDragAfter(evt);
}
setDraggable(draggable) {
this._setAttr('draggable', draggable);
this._dragChange();
}
/**
* determine if node is currently in drag and drop mode
* @method
* @name Konva.Node#isDragging
*/
isDragging() {
const elem = DD._dragElements.get(this._id);
return elem ? elem.dragStatus === 'dragging' : false;
}
_listenDrag() {
this._dragCleanup();
this.on('mousedown.konva touchstart.konva', function (evt) {
var shouldCheckButton = evt.evt['button'] !== undefined;
var canDrag = !shouldCheckButton || Konva$2.dragButtons.indexOf(evt.evt['button']) >= 0;
if (!canDrag) {
return;
}
if (this.isDragging()) {
return;
}
var hasDraggingChild = false;
DD._dragElements.forEach((elem) => {
if (this.isAncestorOf(elem.node)) {
hasDraggingChild = true;
}
});
// nested drag can be started
// in that case we don't need to start new drag
if (!hasDraggingChild) {
this._createDragElement(evt);
}
});
}
_dragChange() {
if (this.attrs.draggable) {
this._listenDrag();
}
else {
// remove event listeners
this._dragCleanup();
/*
* force drag and drop to end
* if this node is currently in
* drag and drop mode
*/
var stage = this.getStage();
if (!stage) {
return;
}
const dragElement = DD._dragElements.get(this._id);
const isDragging = dragElement && dragElement.dragStatus === 'dragging';
const isReady = dragElement && dragElement.dragStatus === 'ready';
if (isDragging) {
this.stopDrag();
}
else if (isReady) {
DD._dragElements.delete(this._id);
}
}
}
_dragCleanup() {
this.off('mousedown.konva');
this.off('touchstart.konva');
}
/**
* determine if node (at least partially) is currently in user-visible area
* @method
* @param {(Number | Object)} margin optional margin in pixels
* @param {Number} margin.x
* @param {Number} margin.y
* @returns {Boolean}
* @name Konva.Node#isClientRectOnScreen
* @example
* // get index
* // default calculations
* var isOnScreen = node.isClientRectOnScreen()
* // increase object size (or screen size) for cases when objects close to the screen still need to be marked as "visible"
* var isOnScreen = node.isClientRectOnScreen({ x: stage.width(), y: stage.height() })
*/
isClientRectOnScreen(margin = { x: 0, y: 0 }) {
const stage = this.getStage();
if (!stage) {
return false;
}
const screenRect = {
x: -margin.x,
y: -margin.y,
width: stage.width() + margin.x,
height: stage.height() + margin.y,
};
return Util.haveIntersection(screenRect, this.getClientRect());
}
/**
* create node with JSON string or an Object. De-serializtion does not generate custom
* shape drawing functions, images, or event handlers (this would make the
* serialized object huge). If your app uses custom shapes, images, and
* event handlers (it probably does), then you need to select the appropriate
* shapes after loading the stage and set these properties via on(), setSceneFunc(),
* and setImage() methods
* @method
* @memberof Konva.Node
* @param {String|Object} json string or object
* @param {Element} [container] optional container dom element used only if you're
* creating a stage node
*/
static create(data, container) {
if (Util._isString(data)) {
data = JSON.parse(data);
}
return this._createNode(data, container);
}
static _createNode(obj, container) {
var className = Node.prototype.getClassName.call(obj), children = obj.children, no, len, n;
// if container was passed in, add it to attrs
if (container) {
obj.attrs.container = container;
}
if (!Konva$2[className]) {
Util.warn('Can not find a node with class name "' +
className +
'". Fallback to "Shape".');
className = 'Shape';
}
const Class = Konva$2[className];
no = new Class(obj.attrs);
if (children) {
len = children.length;
for (n = 0; n < len; n++) {
no.add(Node._createNode(children[n]));
}
}
return no;
}
}
Node.prototype.nodeType = 'Node';
Node.prototype._attrsAffectingSize = [];
// attache events listeners once into prototype
// that way we don't spend too much time on making an new instance
Node.prototype.eventListeners = {};
Node.prototype.on.call(Node.prototype, TRANSFORM_CHANGE_STR$1, function () {
if (this._batchingTransformChange) {
this._needClearTransformCache = true;
return;
}
this._clearCache(TRANSFORM);
this._clearSelfAndDescendantCache(ABSOLUTE_TRANSFORM);
});
Node.prototype.on.call(Node.prototype, 'visibleChange.konva', function () {
this._clearSelfAndDescendantCache(VISIBLE);
});
Node.prototype.on.call(Node.prototype, 'listeningChange.konva', function () {
this._clearSelfAndDescendantCache(LISTENING);
});
Node.prototype.on.call(Node.prototype, 'opacityChange.konva', function () {
this._clearSelfAndDescendantCache(ABSOLUTE_OPACITY);
});
const addGetterSetter = Factory.addGetterSetter;
/**
* get/set zIndex relative to the node's siblings who share the same parent.
* Please remember that zIndex is not absolute (like in CSS). It is relative to parent element only.
* @name Konva.Node#zIndex
* @method
* @param {Number} index
* @returns {Number}
* @example
* // get index
* var index = node.zIndex();
*
* // set index
* node.zIndex(2);
*/
addGetterSetter(Node, 'zIndex');
/**
* get/set node absolute position
* @name Konva.Node#absolutePosition
* @method
* @param {Object} pos
* @param {Number} pos.x
* @param {Number} pos.y
* @returns {Object}
* @example
* // get position
* var position = node.absolutePosition();
*
* // set position
* node.absolutePosition({
* x: 5,
* y: 10
* });
*/
addGetterSetter(Node, 'absolutePosition');
addGetterSetter(Node, 'position');
/**
* get/set node position relative to parent
* @name Konva.Node#position
* @method
* @param {Object} pos
* @param {Number} pos.x
* @param {Number} pos.y
* @returns {Object}
* @example
* // get position
* var position = node.position();
*
* // set position
* node.position({
* x: 5,
* y: 10
* });
*/
addGetterSetter(Node, 'x', 0, getNumberValidator());
/**
* get/set x position
* @name Konva.Node#x
* @method
* @param {Number} x
* @returns {Object}
* @example
* // get x
* var x = node.x();
*
* // set x
* node.x(5);
*/
addGetterSetter(Node, 'y', 0, getNumberValidator());
/**
* get/set y position
* @name Konva.Node#y
* @method
* @param {Number} y
* @returns {Integer}
* @example
* // get y
* var y = node.y();
*
* // set y
* node.y(5);
*/
addGetterSetter(Node, 'globalCompositeOperation', 'source-over', getStringValidator());
/**
* get/set globalCompositeOperation of a node. globalCompositeOperation DOESN'T affect hit graph of nodes. So they are still trigger to events as they have default "source-over" globalCompositeOperation.
* @name Konva.Node#globalCompositeOperation
* @method
* @param {String} type
* @returns {String}
* @example
* // get globalCompositeOperation
* var globalCompositeOperation = shape.globalCompositeOperation();
*
* // set globalCompositeOperation
* shape.globalCompositeOperation('source-in');
*/
addGetterSetter(Node, 'opacity', 1, getNumberValidator());
/**
* get/set opacity. Opacity values range from 0 to 1.
* A node with an opacity of 0 is fully transparent, and a node
* with an opacity of 1 is fully opaque
* @name Konva.Node#opacity
* @method
* @param {Object} opacity
* @returns {Number}
* @example
* // get opacity
* var opacity = node.opacity();
*
* // set opacity
* node.opacity(0.5);
*/
addGetterSetter(Node, 'name', '', getStringValidator());
/**
* get/set name.
* @name Konva.Node#name
* @method
* @param {String} name
* @returns {String}
* @example
* // get name
* var name = node.name();
*
* // set name
* node.name('foo');
*
* // also node may have multiple names (as css classes)
* node.name('foo bar');
*/
addGetterSetter(Node, 'id', '', getStringValidator());
/**
* get/set id. Id is global for whole page.
* @name Konva.Node#id
* @method
* @param {String} id
* @returns {String}
* @example
* // get id
* var name = node.id();
*
* // set id
* node.id('foo');
*/
addGetterSetter(Node, 'rotation', 0, getNumberValidator());
/**
* get/set rotation in degrees
* @name Konva.Node#rotation
* @method
* @param {Number} rotation
* @returns {Number}
* @example
* // get rotation in degrees
* var rotation = node.rotation();
*
* // set rotation in degrees
* node.rotation(45);
*/
Factory.addComponentsGetterSetter(Node, 'scale', ['x', 'y']);
/**
* get/set scale
* @name Konva.Node#scale
* @param {Object} scale
* @param {Number} scale.x
* @param {Number} scale.y
* @method
* @returns {Object}
* @example
* // get scale
* var scale = node.scale();
*
* // set scale
* shape.scale({
* x: 2,
* y: 3
* });
*/
addGetterSetter(Node, 'scaleX', 1, getNumberValidator());
/**
* get/set scale x
* @name Konva.Node#scaleX
* @param {Number} x
* @method
* @returns {Number}
* @example
* // get scale x
* var scaleX = node.scaleX();
*
* // set scale x
* node.scaleX(2);
*/
addGetterSetter(Node, 'scaleY', 1, getNumberValidator());
/**
* get/set scale y
* @name Konva.Node#scaleY
* @param {Number} y
* @method
* @returns {Number}
* @example
* // get scale y
* var scaleY = node.scaleY();
*
* // set scale y
* node.scaleY(2);
*/
Factory.addComponentsGetterSetter(Node, 'skew', ['x', 'y']);
/**
* get/set skew
* @name Konva.Node#skew
* @param {Object} skew
* @param {Number} skew.x
* @param {Number} skew.y
* @method
* @returns {Object}
* @example
* // get skew
* var skew = node.skew();
*
* // set skew
* node.skew({
* x: 20,
* y: 10
* });
*/
addGetterSetter(Node, 'skewX', 0, getNumberValidator());
/**
* get/set skew x
* @name Konva.Node#skewX
* @param {Number} x
* @method
* @returns {Number}
* @example
* // get skew x
* var skewX = node.skewX();
*
* // set skew x
* node.skewX(3);
*/
addGetterSetter(Node, 'skewY', 0, getNumberValidator());
/**
* get/set skew y
* @name Konva.Node#skewY
* @param {Number} y
* @method
* @returns {Number}
* @example
* // get skew y
* var skewY = node.skewY();
*
* // set skew y
* node.skewY(3);
*/
Factory.addComponentsGetterSetter(Node, 'offset', ['x', 'y']);
/**
* get/set offset. Offsets the default position and rotation point
* @method
* @param {Object} offset
* @param {Number} offset.x
* @param {Number} offset.y
* @returns {Object}
* @example
* // get offset
* var offset = node.offset();
*
* // set offset
* node.offset({
* x: 20,
* y: 10
* });
*/
addGetterSetter(Node, 'offsetX', 0, getNumberValidator());
/**
* get/set offset x
* @name Konva.Node#offsetX
* @method
* @param {Number} x
* @returns {Number}
* @example
* // get offset x
* var offsetX = node.offsetX();
*
* // set offset x
* node.offsetX(3);
*/
addGetterSetter(Node, 'offsetY', 0, getNumberValidator());
/**
* get/set offset y
* @name Konva.Node#offsetY
* @method
* @param {Number} y
* @returns {Number}
* @example
* // get offset y
* var offsetY = node.offsetY();
*
* // set offset y
* node.offsetY(3);
*/
addGetterSetter(Node, 'dragDistance', null, getNumberValidator());
/**
* get/set drag distance
* @name Konva.Node#dragDistance
* @method
* @param {Number} distance
* @returns {Number}
* @example
* // get drag distance
* var dragDistance = node.dragDistance();
*
* // set distance
* // node starts dragging only if pointer moved more then 3 pixels
* node.dragDistance(3);
* // or set globally
* Konva.dragDistance = 3;
*/
addGetterSetter(Node, 'width', 0, getNumberValidator());
/**
* get/set width
* @name Konva.Node#width
* @method
* @param {Number} width
* @returns {Number}
* @example
* // get width
* var width = node.width();
*
* // set width
* node.width(100);
*/
addGetterSetter(Node, 'height', 0, getNumberValidator());
/**
* get/set height
* @name Konva.Node#height
* @method
* @param {Number} height
* @returns {Number}
* @example
* // get height
* var height = node.height();
*
* // set height
* node.height(100);
*/
addGetterSetter(Node, 'listening', true, getBooleanValidator());
/**
* get/set listening attr. If you need to determine if a node is listening or not
* by taking into account its parents, use the isListening() method
* @name Konva.Node#listening
* @method
* @param {Boolean} listening Can be true, or false. The default is true.
* @returns {Boolean}
* @example
* // get listening attr
* var listening = node.listening();
*
* // stop listening for events, remove node and all its children from hit graph
* node.listening(false);
*
* // listen to events according to the parent
* node.listening(true);
*/
/**
* get/set preventDefault
* By default all shapes will prevent default behavior
* of a browser on a pointer move or tap.
* that will prevent native scrolling when you are trying to drag&drop a node
* but sometimes you may need to enable default actions
* in that case you can set the property to false
* @name Konva.Node#preventDefault
* @method
* @param {Boolean} preventDefault
* @returns {Boolean}
* @example
* // get preventDefault
* var shouldPrevent = shape.preventDefault();
*
* // set preventDefault
* shape.preventDefault(false);
*/
addGetterSetter(Node, 'preventDefault', true, getBooleanValidator());
addGetterSetter(Node, 'filters', null, function (val) {
this._filterUpToDate = false;
return val;
});
/**
* get/set filters. Filters are applied to cached canvases
* @name Konva.Node#filters
* @method
* @param {Array} filters array of filters
* @returns {Array}
* @example
* // get filters
* var filters = node.filters();
*
* // set a single filter
* node.cache();
* node.filters([Konva.Filters.Blur]);
*
* // set multiple filters
* node.cache();
* node.filters([
* Konva.Filters.Blur,
* Konva.Filters.Sepia,
* Konva.Filters.Invert
* ]);
*/
addGetterSetter(Node, 'visible', true, getBooleanValidator());
/**
* get/set visible attr. Can be true, or false. The default is true.
* If you need to determine if a node is visible or not
* by taking into account its parents, use the isVisible() method
* @name Konva.Node#visible
* @method
* @param {Boolean} visible
* @returns {Boolean}
* @example
* // get visible attr
* var visible = node.visible();
*
* // make invisible
* node.visible(false);
*
* // make visible (according to the parent)
* node.visible(true);
*
*/
addGetterSetter(Node, 'transformsEnabled', 'all', getStringValidator());
/**
* get/set transforms that are enabled. Can be "all", "none", or "position". The default
* is "all"
* @name Konva.Node#transformsEnabled
* @method
* @param {String} enabled
* @returns {String}
* @example
* // enable position transform only to improve draw performance
* node.transformsEnabled('position');
*
* // enable all transforms
* node.transformsEnabled('all');
*/
/**
* get/set node size
* @name Konva.Node#size
* @method
* @param {Object} size
* @param {Number} size.width
* @param {Number} size.height
* @returns {Object}
* @example
* // get node size
* var size = node.size();
* var width = size.width;
* var height = size.height;
*
* // set size
* node.size({
* width: 100,
* height: 200
* });
*/
addGetterSetter(Node, 'size');
/**
* get/set drag bound function. This is used to override the default
* drag and drop position.
* @name Konva.Node#dragBoundFunc
* @method
* @param {Function} dragBoundFunc
* @returns {Function}
* @example
* // get drag bound function
* var dragBoundFunc = node.dragBoundFunc();
*
* // create vertical drag and drop
* node.dragBoundFunc(function(pos){
* // important pos - is absolute position of the node
* // you should return absolute position too
* return {
* x: this.absolutePosition().x,
* y: pos.y
* };
* });
*/
addGetterSetter(Node, 'dragBoundFunc');
/**
* get/set draggable flag
* @name Konva.Node#draggable
* @method
* @param {Boolean} draggable
* @returns {Boolean}
* @example
* // get draggable flag
* var draggable = node.draggable();
*
* // enable drag and drop
* node.draggable(true);
*
* // disable drag and drop
* node.draggable(false);
*/
addGetterSetter(Node, 'draggable', false, getBooleanValidator());
Factory.backCompat(Node, {
rotateDeg: 'rotate',
setRotationDeg: 'setRotation',
getRotationDeg: 'getRotation',
});
/**
* Container constructor. Containers are used to contain nodes or other containers
* @constructor
* @memberof Konva
* @augments Konva.Node
* @abstract
* @param {Object} config
* @param {Number} [config.x]
* @param {Number} [config.y]
* @param {Number} [config.width]
* @param {Number} [config.height]
* @param {Boolean} [config.visible]
* @param {Boolean} [config.listening] whether or not the node is listening for events
* @param {String} [config.id] unique id
* @param {String} [config.name] non-unique name
* @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1
* @param {Object} [config.scale] set scale
* @param {Number} [config.scaleX] set scale x
* @param {Number} [config.scaleY] set scale y
* @param {Number} [config.rotation] rotation in degrees
* @param {Object} [config.offset] offset from center point and rotation point
* @param {Number} [config.offsetX] set offset x
* @param {Number} [config.offsetY] set offset y
* @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop
* the entire stage by dragging any portion of the stage
* @param {Number} [config.dragDistance]
* @param {Function} [config.dragBoundFunc]
* * @param {Object} [config.clip] set clip
* @param {Number} [config.clipX] set clip x
* @param {Number} [config.clipY] set clip y
* @param {Number} [config.clipWidth] set clip width
* @param {Number} [config.clipHeight] set clip height
* @param {Function} [config.clipFunc] set clip func
*/
class Container extends Node {
constructor() {
super(...arguments);
this.children = [];
}
/**
* returns an array of direct descendant nodes
* @method
* @name Konva.Container#getChildren
* @param {Function} [filterFunc] filter function
* @returns {Array}
* @example
* // get all children
* var children = layer.getChildren();
*
* // get only circles
* var circles = layer.getChildren(function(node){
* return node.getClassName() === 'Circle';
* });
*/
getChildren(filterFunc) {
if (!filterFunc) {
return this.children || [];
}
const children = this.children || [];
var results = [];
children.forEach(function (child) {
if (filterFunc(child)) {
results.push(child);
}
});
return results;
}
/**
* determine if node has children
* @method
* @name Konva.Container#hasChildren
* @returns {Boolean}
*/
hasChildren() {
return this.getChildren().length > 0;
}
/**
* remove all children. Children will be still in memory.
* If you want to completely destroy all children please use "destroyChildren" method instead
* @method
* @name Konva.Container#removeChildren
*/
removeChildren() {
this.getChildren().forEach((child) => {
// reset parent to prevent many _setChildrenIndices calls
child.parent = null;
child.index = 0;
child.remove();
});
this.children = [];
// because all children were detached from parent, request draw via container
this._requestDraw();
return this;
}
/**
* destroy all children nodes.
* @method
* @name Konva.Container#destroyChildren
*/
destroyChildren() {
this.getChildren().forEach((child) => {
// reset parent to prevent many _setChildrenIndices calls
child.parent = null;
child.index = 0;
child.destroy();
});
this.children = [];
// because all children were detached from parent, request draw via container
this._requestDraw();
return this;
}
/**
* add a child and children into container
* @name Konva.Container#add
* @method
* @param {...Konva.Node} child
* @returns {Container}
* @example
* layer.add(rect);
* layer.add(shape1, shape2, shape3);
* // remember to redraw layer if you changed something
* layer.draw();
*/
add(...children) {
if (arguments.length > 1) {
for (var i = 0; i < arguments.length; i++) {
this.add(arguments[i]);
}
return this;
}
var child = children[0];
if (child.getParent()) {
child.moveTo(this);
return this;
}
this._validateAdd(child);
child.index = this.getChildren().length;
child.parent = this;
child._clearCaches();
this.getChildren().push(child);
this._fire('add', {
child: child,
});
this._requestDraw();
// chainable
return this;
}
destroy() {
if (this.hasChildren()) {
this.destroyChildren();
}
super.destroy();
return this;
}
/**
* return an array of nodes that match the selector.
* You can provide a string with '#' for id selections and '.' for name selections.
* Or a function that will return true/false when a node is passed through. See example below.
* With strings you can also select by type or class name. Pass multiple selectors
* separated by a comma.
* @method
* @name Konva.Container#find
* @param {String | Function} selector
* @returns {Array}
* @example
*
* Passing a string as a selector
* // select node with id foo
* var node = stage.find('#foo');
*
* // select nodes with name bar inside layer
* var nodes = layer.find('.bar');
*
* // select all groups inside layer
* var nodes = layer.find('Group');
*
* // select all rectangles inside layer
* var nodes = layer.find('Rect');
*
* // select node with an id of foo or a name of bar inside layer
* var nodes = layer.find('#foo, .bar');
*
* Passing a function as a selector
*
* // get all groups with a function
* var groups = stage.find(node => {
* return node.getType() === 'Group';
* });
*
* // get only Nodes with partial opacity
* var alphaNodes = layer.find(node => {
* return node.getType() === 'Node' && node.getAbsoluteOpacity() < 1;
* });
*/
find(selector) {
// protecting _generalFind to prevent user from accidentally adding
// second argument and getting unexpected `findOne` result
return this._generalFind(selector, false);
}
/**
* return a first node from `find` method
* @method
* @name Konva.Container#findOne
* @param {String | Function} selector
* @returns {Konva.Node | Undefined}
* @example
* // select node with id foo
* var node = stage.findOne('#foo');
*
* // select node with name bar inside layer
* var nodes = layer.findOne('.bar');
*
* // select the first node to return true in a function
* var node = stage.findOne(node => {
* return node.getType() === 'Shape'
* })
*/
findOne(selector) {
var result = this._generalFind(selector, true);
return result.length > 0 ? result[0] : undefined;
}
_generalFind(selector, findOne) {
var retArr = [];
this._descendants((node) => {
const valid = node._isMatch(selector);
if (valid) {
retArr.push(node);
}
if (valid && findOne) {
return true;
}
return false;
});
return retArr;
}
_descendants(fn) {
let shouldStop = false;
const children = this.getChildren();
for (const child of children) {
shouldStop = fn(child);
if (shouldStop) {
return true;
}
if (!child.hasChildren()) {
continue;
}
shouldStop = child._descendants(fn);
if (shouldStop) {
return true;
}
}
return false;
}
// extenders
toObject() {
var obj = Node.prototype.toObject.call(this);
obj.children = [];
this.getChildren().forEach((child) => {
obj.children.push(child.toObject());
});
return obj;
}
/**
* determine if node is an ancestor
* of descendant
* @method
* @name Konva.Container#isAncestorOf
* @param {Konva.Node} node
*/
isAncestorOf(node) {
var parent = node.getParent();
while (parent) {
if (parent._id === this._id) {
return true;
}
parent = parent.getParent();
}
return false;
}
clone(obj) {
// call super method
var node = Node.prototype.clone.call(this, obj);
this.getChildren().forEach(function (no) {
node.add(no.clone());
});
return node;
}
/**
* get all shapes that intersect a point. Note: because this method must clear a temporary
* canvas and redraw every shape inside the container, it should only be used for special situations
* because it performs very poorly. Please use the {@link Konva.Stage#getIntersection} method if at all possible
* because it performs much better
* @method
* @name Konva.Container#getAllIntersections
* @param {Object} pos
* @param {Number} pos.x
* @param {Number} pos.y
* @returns {Array} array of shapes
*/
getAllIntersections(pos) {
var arr = [];
this.find('Shape').forEach(function (shape) {
if (shape.isVisible() && shape.intersects(pos)) {
arr.push(shape);
}
});
return arr;
}
_clearSelfAndDescendantCache(attr) {
var _a;
super._clearSelfAndDescendantCache(attr);
// skip clearing if node is cached with canvas
// for performance reasons !!!
if (this.isCached()) {
return;
}
(_a = this.children) === null || _a === void 0 ? void 0 : _a.forEach(function (node) {
node._clearSelfAndDescendantCache(attr);
});
}
_setChildrenIndices() {
var _a;
(_a = this.children) === null || _a === void 0 ? void 0 : _a.forEach(function (child, n) {
child.index = n;
});
this._requestDraw();
}
drawScene(can, top) {
var layer = this.getLayer(), canvas = can || (layer && layer.getCanvas()), context = canvas && canvas.getContext(), cachedCanvas = this._getCanvasCache(), cachedSceneCanvas = cachedCanvas && cachedCanvas.scene;
var caching = canvas && canvas.isCache;
if (!this.isVisible() && !caching) {
return this;
}
if (cachedSceneCanvas) {
context.save();
var m = this.getAbsoluteTransform(top).getMatrix();
context.transform(m[0], m[1], m[2], m[3], m[4], m[5]);
this._drawCachedSceneCanvas(context);
context.restore();
}
else {
this._drawChildren('drawScene', canvas, top);
}
return this;
}
drawHit(can, top) {
if (!this.shouldDrawHit(top)) {
return this;
}
var layer = this.getLayer(), canvas = can || (layer && layer.hitCanvas), context = canvas && canvas.getContext(), cachedCanvas = this._getCanvasCache(), cachedHitCanvas = cachedCanvas && cachedCanvas.hit;
if (cachedHitCanvas) {
context.save();
var m = this.getAbsoluteTransform(top).getMatrix();
context.transform(m[0], m[1], m[2], m[3], m[4], m[5]);
this._drawCachedHitCanvas(context);
context.restore();
}
else {
this._drawChildren('drawHit', canvas, top);
}
return this;
}
_drawChildren(drawMethod, canvas, top) {
var _a;
var context = canvas && canvas.getContext(), clipWidth = this.clipWidth(), clipHeight = this.clipHeight(), clipFunc = this.clipFunc(), hasClip = (clipWidth && clipHeight) || clipFunc;
const selfCache = top === this;
if (hasClip) {
context.save();
var transform = this.getAbsoluteTransform(top);
var m = transform.getMatrix();
context.transform(m[0], m[1], m[2], m[3], m[4], m[5]);
context.beginPath();
if (clipFunc) {
clipFunc.call(this, context, this);
}
else {
var clipX = this.clipX();
var clipY = this.clipY();
context.rect(clipX, clipY, clipWidth, clipHeight);
}
context.clip();
m = transform.copy().invert().getMatrix();
context.transform(m[0], m[1], m[2], m[3], m[4], m[5]);
}
var hasComposition = !selfCache &&
this.globalCompositeOperation() !== 'source-over' &&
drawMethod === 'drawScene';
if (hasComposition) {
context.save();
context._applyGlobalCompositeOperation(this);
}
(_a = this.children) === null || _a === void 0 ? void 0 : _a.forEach(function (child) {
child[drawMethod](canvas, top);
});
if (hasComposition) {
context.restore();
}
if (hasClip) {
context.restore();
}
}
getClientRect(config) {
var _a;
config = config || {};
var skipTransform = config.skipTransform;
var relativeTo = config.relativeTo;
var minX, minY, maxX, maxY;
var selfRect = {
x: Infinity,
y: Infinity,
width: 0,
height: 0,
};
var that = this;
(_a = this.children) === null || _a === void 0 ? void 0 : _a.forEach(function (child) {
// skip invisible children
if (!child.visible()) {
return;
}
var rect = child.getClientRect({
relativeTo: that,
skipShadow: config.skipShadow,
skipStroke: config.skipStroke,
});
// skip invisible children (like empty groups)
if (rect.width === 0 && rect.height === 0) {
return;
}
if (minX === undefined) {
// initial value for first child
minX = rect.x;
minY = rect.y;
maxX = rect.x + rect.width;
maxY = rect.y + rect.height;
}
else {
minX = Math.min(minX, rect.x);
minY = Math.min(minY, rect.y);
maxX = Math.max(maxX, rect.x + rect.width);
maxY = Math.max(maxY, rect.y + rect.height);
}
});
// if child is group we need to make sure it has visible shapes inside
var shapes = this.find('Shape');
var hasVisible = false;
for (var i = 0; i < shapes.length; i++) {
var shape = shapes[i];
if (shape._isVisible(this)) {
hasVisible = true;
break;
}
}
if (hasVisible && minX !== undefined) {
selfRect = {
x: minX,
y: minY,
width: maxX - minX,
height: maxY - minY,
};
}
else {
selfRect = {
x: 0,
y: 0,
width: 0,
height: 0,
};
}
if (!skipTransform) {
return this._transformedRect(selfRect, relativeTo);
}
return selfRect;
}
}
// add getters setters
Factory.addComponentsGetterSetter(Container, 'clip', [
'x',
'y',
'width',
'height',
]);
/**
* get/set clip
* @method
* @name Konva.Container#clip
* @param {Object} clip
* @param {Number} clip.x
* @param {Number} clip.y
* @param {Number} clip.width
* @param {Number} clip.height
* @returns {Object}
* @example
* // get clip
* var clip = container.clip();
*
* // set clip
* container.clip({
* x: 20,
* y: 20,
* width: 20,
* height: 20
* });
*/
Factory.addGetterSetter(Container, 'clipX', undefined, getNumberValidator());
/**
* get/set clip x
* @name Konva.Container#clipX
* @method
* @param {Number} x
* @returns {Number}
* @example
* // get clip x
* var clipX = container.clipX();
*
* // set clip x
* container.clipX(10);
*/
Factory.addGetterSetter(Container, 'clipY', undefined, getNumberValidator());
/**
* get/set clip y
* @name Konva.Container#clipY
* @method
* @param {Number} y
* @returns {Number}
* @example
* // get clip y
* var clipY = container.clipY();
*
* // set clip y
* container.clipY(10);
*/
Factory.addGetterSetter(Container, 'clipWidth', undefined, getNumberValidator());
/**
* get/set clip width
* @name Konva.Container#clipWidth
* @method
* @param {Number} width
* @returns {Number}
* @example
* // get clip width
* var clipWidth = container.clipWidth();
*
* // set clip width
* container.clipWidth(100);
*/
Factory.addGetterSetter(Container, 'clipHeight', undefined, getNumberValidator());
/**
* get/set clip height
* @name Konva.Container#clipHeight
* @method
* @param {Number} height
* @returns {Number}
* @example
* // get clip height
* var clipHeight = container.clipHeight();
*
* // set clip height
* container.clipHeight(100);
*/
Factory.addGetterSetter(Container, 'clipFunc');
/**
* get/set clip function
* @name Konva.Container#clipFunc
* @method
* @param {Function} function
* @returns {Function}
* @example
* // get clip function
* var clipFunction = container.clipFunc();
*
* // set clip height
* container.clipFunc(function(ctx) {
* ctx.rect(0, 0, 100, 100);
* });
*/
const Captures = new Map();
// we may use this module for capturing touch events too
// so make sure we don't do something super specific to pointer
const SUPPORT_POINTER_EVENTS = Konva$2._global['PointerEvent'] !== undefined;
function getCapturedShape(pointerId) {
return Captures.get(pointerId);
}
function createEvent(evt) {
return {
evt,
pointerId: evt.pointerId,
};
}
function hasPointerCapture(pointerId, shape) {
return Captures.get(pointerId) === shape;
}
function setPointerCapture(pointerId, shape) {
releaseCapture(pointerId);
const stage = shape.getStage();
if (!stage)
return;
Captures.set(pointerId, shape);
if (SUPPORT_POINTER_EVENTS) {
shape._fire('gotpointercapture', createEvent(new PointerEvent('gotpointercapture')));
}
}
function releaseCapture(pointerId, target) {
const shape = Captures.get(pointerId);
if (!shape)
return;
const stage = shape.getStage();
if (stage && stage.content) ;
Captures.delete(pointerId);
if (SUPPORT_POINTER_EVENTS) {
shape._fire('lostpointercapture', createEvent(new PointerEvent('lostpointercapture')));
}
}
// CONSTANTS
var STAGE = 'Stage', STRING = 'string', PX = 'px', MOUSEOUT = 'mouseout', MOUSELEAVE = 'mouseleave', MOUSEOVER = 'mouseover', MOUSEENTER = 'mouseenter', MOUSEMOVE = 'mousemove', MOUSEDOWN = 'mousedown', MOUSEUP = 'mouseup', POINTERMOVE = 'pointermove', POINTERDOWN = 'pointerdown', POINTERUP = 'pointerup', POINTERCANCEL = 'pointercancel', LOSTPOINTERCAPTURE = 'lostpointercapture', POINTEROUT = 'pointerout', POINTERLEAVE = 'pointerleave', POINTEROVER = 'pointerover', POINTERENTER = 'pointerenter', CONTEXTMENU = 'contextmenu', TOUCHSTART = 'touchstart', TOUCHEND = 'touchend', TOUCHMOVE = 'touchmove', TOUCHCANCEL = 'touchcancel', WHEEL = 'wheel', MAX_LAYERS_NUMBER = 5, EVENTS = [
[MOUSEENTER, '_pointerenter'],
[MOUSEDOWN, '_pointerdown'],
[MOUSEMOVE, '_pointermove'],
[MOUSEUP, '_pointerup'],
[MOUSELEAVE, '_pointerleave'],
[TOUCHSTART, '_pointerdown'],
[TOUCHMOVE, '_pointermove'],
[TOUCHEND, '_pointerup'],
[TOUCHCANCEL, '_pointercancel'],
[MOUSEOVER, '_pointerover'],
[WHEEL, '_wheel'],
[CONTEXTMENU, '_contextmenu'],
[POINTERDOWN, '_pointerdown'],
[POINTERMOVE, '_pointermove'],
[POINTERUP, '_pointerup'],
[POINTERCANCEL, '_pointercancel'],
[LOSTPOINTERCAPTURE, '_lostpointercapture'],
];
const EVENTS_MAP = {
mouse: {
[POINTEROUT]: MOUSEOUT,
[POINTERLEAVE]: MOUSELEAVE,
[POINTEROVER]: MOUSEOVER,
[POINTERENTER]: MOUSEENTER,
[POINTERMOVE]: MOUSEMOVE,
[POINTERDOWN]: MOUSEDOWN,
[POINTERUP]: MOUSEUP,
[POINTERCANCEL]: 'mousecancel',
pointerclick: 'click',
pointerdblclick: 'dblclick',
},
touch: {
[POINTEROUT]: 'touchout',
[POINTERLEAVE]: 'touchleave',
[POINTEROVER]: 'touchover',
[POINTERENTER]: 'touchenter',
[POINTERMOVE]: TOUCHMOVE,
[POINTERDOWN]: TOUCHSTART,
[POINTERUP]: TOUCHEND,
[POINTERCANCEL]: TOUCHCANCEL,
pointerclick: 'tap',
pointerdblclick: 'dbltap',
},
pointer: {
[POINTEROUT]: POINTEROUT,
[POINTERLEAVE]: POINTERLEAVE,
[POINTEROVER]: POINTEROVER,
[POINTERENTER]: POINTERENTER,
[POINTERMOVE]: POINTERMOVE,
[POINTERDOWN]: POINTERDOWN,
[POINTERUP]: POINTERUP,
[POINTERCANCEL]: POINTERCANCEL,
pointerclick: 'pointerclick',
pointerdblclick: 'pointerdblclick',
},
};
const getEventType = (type) => {
if (type.indexOf('pointer') >= 0) {
return 'pointer';
}
if (type.indexOf('touch') >= 0) {
return 'touch';
}
return 'mouse';
};
const getEventsMap = (eventType) => {
const type = getEventType(eventType);
if (type === 'pointer') {
return Konva$2.pointerEventsEnabled && EVENTS_MAP.pointer;
}
if (type === 'touch') {
return EVENTS_MAP.touch;
}
if (type === 'mouse') {
return EVENTS_MAP.mouse;
}
};
function checkNoClip(attrs = {}) {
if (attrs.clipFunc || attrs.clipWidth || attrs.clipHeight) {
Util.warn('Stage does not support clipping. Please use clip for Layers or Groups.');
}
return attrs;
}
const NO_POINTERS_MESSAGE = `Pointer position is missing and not registered by the stage. Looks like it is outside of the stage container. You can set it manually from event: stage.setPointersPositions(event);`;
const stages = [];
/**
* Stage constructor. A stage is used to contain multiple layers
* @constructor
* @memberof Konva
* @augments Konva.Container
* @param {Object} config
* @param {String|Element} config.container Container selector or DOM element
* @param {Number} [config.x]
* @param {Number} [config.y]
* @param {Number} [config.width]
* @param {Number} [config.height]
* @param {Boolean} [config.visible]
* @param {Boolean} [config.listening] whether or not the node is listening for events
* @param {String} [config.id] unique id
* @param {String} [config.name] non-unique name
* @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1
* @param {Object} [config.scale] set scale
* @param {Number} [config.scaleX] set scale x
* @param {Number} [config.scaleY] set scale y
* @param {Number} [config.rotation] rotation in degrees
* @param {Object} [config.offset] offset from center point and rotation point
* @param {Number} [config.offsetX] set offset x
* @param {Number} [config.offsetY] set offset y
* @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop
* the entire stage by dragging any portion of the stage
* @param {Number} [config.dragDistance]
* @param {Function} [config.dragBoundFunc]
* @example
* var stage = new Konva.Stage({
* width: 500,
* height: 800,
* container: 'containerId' // or "#containerId" or ".containerClass"
* });
*/
class Stage extends Container {
constructor(config) {
super(checkNoClip(config));
this._pointerPositions = [];
this._changedPointerPositions = [];
this._buildDOM();
this._bindContentEvents();
stages.push(this);
this.on('widthChange.konva heightChange.konva', this._resizeDOM);
this.on('visibleChange.konva', this._checkVisibility);
this.on('clipWidthChange.konva clipHeightChange.konva clipFuncChange.konva', () => {
checkNoClip(this.attrs);
});
this._checkVisibility();
}
_validateAdd(child) {
const isLayer = child.getType() === 'Layer';
const isFastLayer = child.getType() === 'FastLayer';
const valid = isLayer || isFastLayer;
if (!valid) {
Util.throw('You may only add layers to the stage.');
}
}
_checkVisibility() {
if (!this.content) {
return;
}
const style = this.visible() ? '' : 'none';
this.content.style.display = style;
}
/**
* set container dom element which contains the stage wrapper div element
* @method
* @name Konva.Stage#setContainer
* @param {DomElement} container can pass in a dom element or id string
*/
setContainer(container) {
if (typeof container === STRING) {
if (container.charAt(0) === '.') {
var className = container.slice(1);
container = document.getElementsByClassName(className)[0];
}
else {
var id;
if (container.charAt(0) !== '#') {
id = container;
}
else {
id = container.slice(1);
}
container = document.getElementById(id);
}
if (!container) {
throw 'Can not find container in document with id ' + id;
}
}
this._setAttr('container', container);
if (this.content) {
if (this.content.parentElement) {
this.content.parentElement.removeChild(this.content);
}
container.appendChild(this.content);
}
return this;
}
shouldDrawHit() {
return true;
}
/**
* clear all layers
* @method
* @name Konva.Stage#clear
*/
clear() {
var layers = this.children, len = layers.length, n;
for (n = 0; n < len; n++) {
layers[n].clear();
}
return this;
}
clone(obj) {
if (!obj) {
obj = {};
}
obj.container =
typeof document !== 'undefined' && document.createElement('div');
return Container.prototype.clone.call(this, obj);
}
destroy() {
super.destroy();
var content = this.content;
if (content && Util._isInDocument(content)) {
this.container().removeChild(content);
}
var index = stages.indexOf(this);
if (index > -1) {
stages.splice(index, 1);
}
return this;
}
/**
* returns ABSOLUTE pointer position which can be a touch position or mouse position
* pointer position doesn't include any transforms (such as scale) of the stage
* it is just a plain position of pointer relative to top-left corner of the canvas
* @method
* @name Konva.Stage#getPointerPosition
* @returns {Vector2d|null}
*/
getPointerPosition() {
const pos = this._pointerPositions[0] || this._changedPointerPositions[0];
if (!pos) {
Util.warn(NO_POINTERS_MESSAGE);
return null;
}
return {
x: pos.x,
y: pos.y,
};
}
_getPointerById(id) {
return this._pointerPositions.find((p) => p.id === id);
}
getPointersPositions() {
return this._pointerPositions;
}
getStage() {
return this;
}
getContent() {
return this.content;
}
_toKonvaCanvas(config) {
config = config || {};
config.x = config.x || 0;
config.y = config.y || 0;
config.width = config.width || this.width();
config.height = config.height || this.height();
var canvas = new SceneCanvas({
width: config.width,
height: config.height,
pixelRatio: config.pixelRatio || 1,
});
var _context = canvas.getContext()._context;
var layers = this.children;
if (config.x || config.y) {
_context.translate(-1 * config.x, -1 * config.y);
}
layers.forEach(function (layer) {
if (!layer.isVisible()) {
return;
}
var layerCanvas = layer._toKonvaCanvas(config);
_context.drawImage(layerCanvas._canvas, config.x, config.y, layerCanvas.getWidth() / layerCanvas.getPixelRatio(), layerCanvas.getHeight() / layerCanvas.getPixelRatio());
});
return canvas;
}
/**
* get visible intersection shape. This is the preferred
* method for determining if a point intersects a shape or not
* @method
* @name Konva.Stage#getIntersection
* @param {Object} pos
* @param {Number} pos.x
* @param {Number} pos.y
* @returns {Konva.Node}
* @example
* var shape = stage.getIntersection({x: 50, y: 50});
*/
getIntersection(pos) {
if (!pos) {
return null;
}
var layers = this.children, len = layers.length, end = len - 1, n;
for (n = end; n >= 0; n--) {
const shape = layers[n].getIntersection(pos);
if (shape) {
return shape;
}
}
return null;
}
_resizeDOM() {
var width = this.width();
var height = this.height();
if (this.content) {
// set content dimensions
this.content.style.width = width + PX;
this.content.style.height = height + PX;
}
this.bufferCanvas.setSize(width, height);
this.bufferHitCanvas.setSize(width, height);
// set layer dimensions
this.children.forEach((layer) => {
layer.setSize({ width, height });
layer.draw();
});
}
add(layer, ...rest) {
if (arguments.length > 1) {
for (var i = 0; i < arguments.length; i++) {
this.add(arguments[i]);
}
return this;
}
super.add(layer);
var length = this.children.length;
if (length > MAX_LAYERS_NUMBER) {
Util.warn('The stage has ' +
length +
' layers. Recommended maximum number of layers is 3-5. Adding more layers into the stage may drop the performance. Rethink your tree structure, you can use Konva.Group.');
}
layer.setSize({ width: this.width(), height: this.height() });
// draw layer and append canvas to container
layer.draw();
if (Konva$2.isBrowser) {
this.content.appendChild(layer.canvas._canvas);
}
// chainable
return this;
}
getParent() {
return null;
}
getLayer() {
return null;
}
hasPointerCapture(pointerId) {
return hasPointerCapture(pointerId, this);
}
setPointerCapture(pointerId) {
setPointerCapture(pointerId, this);
}
releaseCapture(pointerId) {
releaseCapture(pointerId);
}
/**
* returns an array of layers
* @method
* @name Konva.Stage#getLayers
*/
getLayers() {
return this.children;
}
_bindContentEvents() {
if (!Konva$2.isBrowser) {
return;
}
EVENTS.forEach(([event, methodName]) => {
this.content.addEventListener(event, (evt) => {
this[methodName](evt);
});
});
}
_pointerenter(evt) {
this.setPointersPositions(evt);
const events = getEventsMap(evt.type);
this._fire(events.pointerenter, {
evt: evt,
target: this,
currentTarget: this,
});
}
_pointerover(evt) {
this.setPointersPositions(evt);
const events = getEventsMap(evt.type);
this._fire(events.pointerover, {
evt: evt,
target: this,
currentTarget: this,
});
}
_getTargetShape(evenType) {
let shape = this[evenType + 'targetShape'];
if (shape && !shape.getStage()) {
shape = null;
}
return shape;
}
_pointerleave(evt) {
const events = getEventsMap(evt.type);
const eventType = getEventType(evt.type);
if (!events) {
return;
}
this.setPointersPositions(evt);
var targetShape = this._getTargetShape(eventType);
var eventsEnabled = !DD.isDragging || Konva$2.hitOnDragEnabled;
if (targetShape && eventsEnabled) {
targetShape._fireAndBubble(events.pointerout, { evt: evt });
targetShape._fireAndBubble(events.pointerleave, { evt: evt });
this._fire(events.pointerleave, {
evt: evt,
target: this,
currentTarget: this,
});
this[eventType + 'targetShape'] = null;
}
else if (eventsEnabled) {
this._fire(events.pointerleave, {
evt: evt,
target: this,
currentTarget: this,
});
this._fire(events.pointerout, {
evt: evt,
target: this,
currentTarget: this,
});
}
this.pointerPos = undefined;
this._pointerPositions = [];
}
_pointerdown(evt) {
const events = getEventsMap(evt.type);
const eventType = getEventType(evt.type);
if (!events) {
return;
}
this.setPointersPositions(evt);
var triggeredOnShape = false;
this._changedPointerPositions.forEach((pos) => {
var shape = this.getIntersection(pos);
DD.justDragged = false;
// probably we are staring a click
Konva$2['_' + eventType + 'ListenClick'] = true;
// no shape detected? do nothing
const hasShape = shape && shape.isListening();
if (!hasShape) {
return;
}
if (Konva$2.capturePointerEventsEnabled) {
shape.setPointerCapture(pos.id);
}
// save where we started the click
this[eventType + 'ClickStartShape'] = shape;
shape._fireAndBubble(events.pointerdown, {
evt: evt,
pointerId: pos.id,
});
triggeredOnShape = true;
// TODO: test in iframe
// only call preventDefault if the shape is listening for events
const isTouch = evt.type.indexOf('touch') >= 0;
if (shape.preventDefault() && evt.cancelable && isTouch) {
evt.preventDefault();
}
});
// trigger down on stage if not already
if (!triggeredOnShape) {
this._fire(events.pointerdown, {
evt: evt,
target: this,
currentTarget: this,
pointerId: this._pointerPositions[0].id,
});
}
}
_pointermove(evt) {
const events = getEventsMap(evt.type);
const eventType = getEventType(evt.type);
if (!events) {
return;
}
if (DD.isDragging && DD.node.preventDefault() && evt.cancelable) {
evt.preventDefault();
}
this.setPointersPositions(evt);
var eventsEnabled = !DD.isDragging || Konva$2.hitOnDragEnabled;
if (!eventsEnabled) {
return;
}
var processedShapesIds = {};
let triggeredOnShape = false;
var targetShape = this._getTargetShape(eventType);
this._changedPointerPositions.forEach((pos) => {
const shape = (getCapturedShape(pos.id) ||
this.getIntersection(pos));
const pointerId = pos.id;
const event = { evt: evt, pointerId };
var differentTarget = targetShape !== shape;
if (differentTarget && targetShape) {
targetShape._fireAndBubble(events.pointerout, Object.assign({}, event), shape);
targetShape._fireAndBubble(events.pointerleave, Object.assign({}, event), shape);
}
if (shape) {
if (processedShapesIds[shape._id]) {
return;
}
processedShapesIds[shape._id] = true;
}
if (shape && shape.isListening()) {
triggeredOnShape = true;
if (differentTarget) {
shape._fireAndBubble(events.pointerover, Object.assign({}, event), targetShape);
shape._fireAndBubble(events.pointerenter, Object.assign({}, event), targetShape);
this[eventType + 'targetShape'] = shape;
}
shape._fireAndBubble(events.pointermove, Object.assign({}, event));
}
else {
if (targetShape) {
this._fire(events.pointerover, {
evt: evt,
target: this,
currentTarget: this,
pointerId,
});
this[eventType + 'targetShape'] = null;
}
}
});
if (!triggeredOnShape) {
this._fire(events.pointermove, {
evt: evt,
target: this,
currentTarget: this,
pointerId: this._changedPointerPositions[0].id,
});
}
}
_pointerup(evt) {
const events = getEventsMap(evt.type);
const eventType = getEventType(evt.type);
if (!events) {
return;
}
this.setPointersPositions(evt);
const clickStartShape = this[eventType + 'ClickStartShape'];
const clickEndShape = this[eventType + 'ClickEndShape'];
var processedShapesIds = {};
let triggeredOnShape = false;
this._changedPointerPositions.forEach((pos) => {
const shape = (getCapturedShape(pos.id) ||
this.getIntersection(pos));
if (shape) {
shape.releaseCapture(pos.id);
if (processedShapesIds[shape._id]) {
return;
}
processedShapesIds[shape._id] = true;
}
const pointerId = pos.id;
const event = { evt: evt, pointerId };
let fireDblClick = false;
if (Konva$2['_' + eventType + 'InDblClickWindow']) {
fireDblClick = true;
clearTimeout(this[eventType + 'DblTimeout']);
}
else if (!DD.justDragged) {
// don't set inDblClickWindow after dragging
Konva$2['_' + eventType + 'InDblClickWindow'] = true;
clearTimeout(this[eventType + 'DblTimeout']);
}
this[eventType + 'DblTimeout'] = setTimeout(function () {
Konva$2['_' + eventType + 'InDblClickWindow'] = false;
}, Konva$2.dblClickWindow);
if (shape && shape.isListening()) {
triggeredOnShape = true;
this[eventType + 'ClickEndShape'] = shape;
shape._fireAndBubble(events.pointerup, Object.assign({}, event));
// detect if click or double click occurred
if (Konva$2['_' + eventType + 'ListenClick'] &&
clickStartShape &&
clickStartShape === shape) {
shape._fireAndBubble(events.pointerclick, Object.assign({}, event));
if (fireDblClick && clickEndShape && clickEndShape === shape) {
shape._fireAndBubble(events.pointerdblclick, Object.assign({}, event));
}
}
}
else {
this[eventType + 'ClickEndShape'] = null;
if (Konva$2['_' + eventType + 'ListenClick']) {
this._fire(events.pointerclick, {
evt: evt,
target: this,
currentTarget: this,
pointerId,
});
}
if (fireDblClick) {
this._fire(events.pointerdblclick, {
evt: evt,
target: this,
currentTarget: this,
pointerId,
});
}
}
});
if (!triggeredOnShape) {
this._fire(events.pointerup, {
evt: evt,
target: this,
currentTarget: this,
pointerId: this._changedPointerPositions[0].id,
});
}
Konva$2['_' + eventType + 'ListenClick'] = false;
// always call preventDefault for desktop events because some browsers
// try to drag and drop the canvas element
if (evt.cancelable) {
evt.preventDefault();
}
}
_contextmenu(evt) {
this.setPointersPositions(evt);
var shape = this.getIntersection(this.getPointerPosition());
if (shape && shape.isListening()) {
shape._fireAndBubble(CONTEXTMENU, { evt: evt });
}
else {
this._fire(CONTEXTMENU, {
evt: evt,
target: this,
currentTarget: this,
});
}
}
_wheel(evt) {
this.setPointersPositions(evt);
var shape = this.getIntersection(this.getPointerPosition());
if (shape && shape.isListening()) {
shape._fireAndBubble(WHEEL, { evt: evt });
}
else {
this._fire(WHEEL, {
evt: evt,
target: this,
currentTarget: this,
});
}
}
_pointercancel(evt) {
this.setPointersPositions(evt);
const shape = getCapturedShape(evt.pointerId) ||
this.getIntersection(this.getPointerPosition());
if (shape) {
shape._fireAndBubble(POINTERUP, createEvent(evt));
}
releaseCapture(evt.pointerId);
}
_lostpointercapture(evt) {
releaseCapture(evt.pointerId);
}
/**
* manually register pointers positions (mouse/touch) in the stage.
* So you can use stage.getPointerPosition(). Usually you don't need to use that method
* because all internal events are automatically registered. It may be useful if event
* is triggered outside of the stage, but you still want to use Konva methods to get pointers position.
* @method
* @name Konva.Stage#setPointersPositions
* @param {Object} event Event object
* @example
*
* window.addEventListener('mousemove', (e) => {
* stage.setPointersPositions(e);
* });
*/
setPointersPositions(evt) {
var contentPosition = this._getContentPosition(), x = null, y = null;
evt = evt ? evt : window.event;
// touch events
if (evt.touches !== undefined) {
// touchlist has not support for map method
// so we have to iterate
this._pointerPositions = [];
this._changedPointerPositions = [];
Array.prototype.forEach.call(evt.touches, (touch) => {
this._pointerPositions.push({
id: touch.identifier,
x: (touch.clientX - contentPosition.left) / contentPosition.scaleX,
y: (touch.clientY - contentPosition.top) / contentPosition.scaleY,
});
});
Array.prototype.forEach.call(evt.changedTouches || evt.touches, (touch) => {
this._changedPointerPositions.push({
id: touch.identifier,
x: (touch.clientX - contentPosition.left) / contentPosition.scaleX,
y: (touch.clientY - contentPosition.top) / contentPosition.scaleY,
});
});
}
else {
// mouse events
x = (evt.clientX - contentPosition.left) / contentPosition.scaleX;
y = (evt.clientY - contentPosition.top) / contentPosition.scaleY;
this.pointerPos = {
x: x,
y: y,
};
this._pointerPositions = [{ x, y, id: Util._getFirstPointerId(evt) }];
this._changedPointerPositions = [
{ x, y, id: Util._getFirstPointerId(evt) },
];
}
}
_setPointerPosition(evt) {
Util.warn('Method _setPointerPosition is deprecated. Use "stage.setPointersPositions(event)" instead.');
this.setPointersPositions(evt);
}
_getContentPosition() {
if (!this.content || !this.content.getBoundingClientRect) {
return {
top: 0,
left: 0,
scaleX: 1,
scaleY: 1,
};
}
var rect = this.content.getBoundingClientRect();
return {
top: rect.top,
left: rect.left,
// sometimes clientWidth can be equals to 0
// i saw it in react-konva test, looks like it is because of hidden testing element
scaleX: rect.width / this.content.clientWidth || 1,
scaleY: rect.height / this.content.clientHeight || 1,
};
}
_buildDOM() {
this.bufferCanvas = new SceneCanvas({
width: this.width(),
height: this.height(),
});
this.bufferHitCanvas = new HitCanvas({
pixelRatio: 1,
width: this.width(),
height: this.height(),
});
if (!Konva$2.isBrowser) {
return;
}
var container = this.container();
if (!container) {
throw 'Stage has no container. A container is required.';
}
// clear content inside container
container.innerHTML = '';
// content
this.content = document.createElement('div');
this.content.style.position = 'relative';
this.content.style.userSelect = 'none';
this.content.className = 'konvajs-content';
this.content.setAttribute('role', 'presentation');
container.appendChild(this.content);
this._resizeDOM();
}
// currently cache function is now working for stage, because stage has no its own canvas element
cache() {
Util.warn('Cache function is not allowed for stage. You may use cache only for layers, groups and shapes.');
return this;
}
clearCache() {
return this;
}
/**
* batch draw
* @method
* @name Konva.Stage#batchDraw
* @return {Konva.Stage} this
*/
batchDraw() {
this.getChildren().forEach(function (layer) {
layer.batchDraw();
});
return this;
}
}
Stage.prototype.nodeType = STAGE;
_registerNode(Stage);
/**
* get/set container DOM element
* @method
* @name Konva.Stage#container
* @returns {DomElement} container
* @example
* // get container
* var container = stage.container();
* // set container
* var container = document.createElement('div');
* body.appendChild(container);
* stage.container(container);
*/
Factory.addGetterSetter(Stage, 'container');
var HAS_SHADOW = 'hasShadow';
var SHADOW_RGBA = 'shadowRGBA';
var patternImage = 'patternImage';
var linearGradient = 'linearGradient';
var radialGradient = 'radialGradient';
let dummyContext$1;
function getDummyContext$1() {
if (dummyContext$1) {
return dummyContext$1;
}
dummyContext$1 = Util.createCanvasElement().getContext('2d');
return dummyContext$1;
}
const shapes = {};
// TODO: idea - use only "remove" (or destroy method)
// how? on add, check that every inner shape has reference in konva store with color
// on remove - clear that reference
// the approach is good. But what if we want to cache the shape before we add it into the stage
// what color to use for hit test?
function _fillFunc$2(context) {
context.fill();
}
function _strokeFunc$2(context) {
context.stroke();
}
function _fillFuncHit(context) {
context.fill();
}
function _strokeFuncHit(context) {
context.stroke();
}
function _clearHasShadowCache() {
this._clearCache(HAS_SHADOW);
}
function _clearGetShadowRGBACache() {
this._clearCache(SHADOW_RGBA);
}
function _clearFillPatternCache() {
this._clearCache(patternImage);
}
function _clearLinearGradientCache() {
this._clearCache(linearGradient);
}
function _clearRadialGradientCache() {
this._clearCache(radialGradient);
}
/**
* Shape constructor. Shapes are primitive objects such as rectangles,
* circles, text, lines, etc.
* @constructor
* @memberof Konva
* @augments Konva.Node
* @param {Object} config
* @param {String} [config.fill] fill color
* @param {Image} [config.fillPatternImage] fill pattern image
* @param {Number} [config.fillPatternX]
* @param {Number} [config.fillPatternY]
* @param {Object} [config.fillPatternOffset] object with x and y component
* @param {Number} [config.fillPatternOffsetX]
* @param {Number} [config.fillPatternOffsetY]
* @param {Object} [config.fillPatternScale] object with x and y component
* @param {Number} [config.fillPatternScaleX]
* @param {Number} [config.fillPatternScaleY]
* @param {Number} [config.fillPatternRotation]
* @param {String} [config.fillPatternRepeat] can be "repeat", "repeat-x", "repeat-y", or "no-repeat". The default is "no-repeat"
* @param {Object} [config.fillLinearGradientStartPoint] object with x and y component
* @param {Number} [config.fillLinearGradientStartPointX]
* @param {Number} [config.fillLinearGradientStartPointY]
* @param {Object} [config.fillLinearGradientEndPoint] object with x and y component
* @param {Number} [config.fillLinearGradientEndPointX]
* @param {Number} [config.fillLinearGradientEndPointY]
* @param {Array} [config.fillLinearGradientColorStops] array of color stops
* @param {Object} [config.fillRadialGradientStartPoint] object with x and y component
* @param {Number} [config.fillRadialGradientStartPointX]
* @param {Number} [config.fillRadialGradientStartPointY]
* @param {Object} [config.fillRadialGradientEndPoint] object with x and y component
* @param {Number} [config.fillRadialGradientEndPointX]
* @param {Number} [config.fillRadialGradientEndPointY]
* @param {Number} [config.fillRadialGradientStartRadius]
* @param {Number} [config.fillRadialGradientEndRadius]
* @param {Array} [config.fillRadialGradientColorStops] array of color stops
* @param {Boolean} [config.fillEnabled] flag which enables or disables the fill. The default value is true
* @param {String} [config.fillPriority] can be color, linear-gradient, radial-graident, or pattern. The default value is color. The fillPriority property makes it really easy to toggle between different fill types. For example, if you want to toggle between a fill color style and a fill pattern style, simply set the fill property and the fillPattern properties, and then use setFillPriority('color') to render the shape with a color fill, or use setFillPriority('pattern') to render the shape with the pattern fill configuration
* @param {String} [config.stroke] stroke color
* @param {Number} [config.strokeWidth] stroke width
* @param {Boolean} [config.fillAfterStrokeEnabled]. Should we draw fill AFTER stroke? Default is false.
* @param {Number} [config.hitStrokeWidth] size of the stroke on hit canvas. The default is "auto" - equals to strokeWidth
* @param {Boolean} [config.strokeHitEnabled] flag which enables or disables stroke hit region. The default is true
* @param {Boolean} [config.perfectDrawEnabled] flag which enables or disables using buffer canvas. The default is true
* @param {Boolean} [config.shadowForStrokeEnabled] flag which enables or disables shadow for stroke. The default is true
* @param {Boolean} [config.strokeScaleEnabled] flag which enables or disables stroke scale. The default is true
* @param {Boolean} [config.strokeEnabled] flag which enables or disables the stroke. The default value is true
* @param {String} [config.lineJoin] can be miter, round, or bevel. The default
* is miter
* @param {String} [config.lineCap] can be butt, round, or square. The default
* is butt
* @param {String} [config.shadowColor]
* @param {Number} [config.shadowBlur]
* @param {Object} [config.shadowOffset] object with x and y component
* @param {Number} [config.shadowOffsetX]
* @param {Number} [config.shadowOffsetY]
* @param {Number} [config.shadowOpacity] shadow opacity. Can be any real number
* between 0 and 1
* @param {Boolean} [config.shadowEnabled] flag which enables or disables the shadow. The default value is true
* @param {Array} [config.dash]
* @param {Boolean} [config.dashEnabled] flag which enables or disables the dashArray. The default value is true
* @param {Number} [config.x]
* @param {Number} [config.y]
* @param {Number} [config.width]
* @param {Number} [config.height]
* @param {Boolean} [config.visible]
* @param {Boolean} [config.listening] whether or not the node is listening for events
* @param {String} [config.id] unique id
* @param {String} [config.name] non-unique name
* @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1
* @param {Object} [config.scale] set scale
* @param {Number} [config.scaleX] set scale x
* @param {Number} [config.scaleY] set scale y
* @param {Number} [config.rotation] rotation in degrees
* @param {Object} [config.offset] offset from center point and rotation point
* @param {Number} [config.offsetX] set offset x
* @param {Number} [config.offsetY] set offset y
* @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop
* the entire stage by dragging any portion of the stage
* @param {Number} [config.dragDistance]
* @param {Function} [config.dragBoundFunc]
* @example
* var customShape = new Konva.Shape({
* x: 5,
* y: 10,
* fill: 'red',
* // a Konva.Canvas renderer is passed into the sceneFunc function
* sceneFunc (context, shape) {
* context.beginPath();
* context.moveTo(200, 50);
* context.lineTo(420, 80);
* context.quadraticCurveTo(300, 100, 260, 170);
* context.closePath();
* // Konva specific method
* context.fillStrokeShape(shape);
* }
*});
*/
class Shape extends Node {
constructor(config) {
super(config);
// set colorKey
let key;
while (true) {
key = Util.getRandomColor();
if (key && !(key in shapes)) {
break;
}
}
this.colorKey = key;
shapes[key] = this;
}
getContext() {
Util.warn('shape.getContext() method is deprecated. Please do not use it.');
return this.getLayer().getContext();
}
getCanvas() {
Util.warn('shape.getCanvas() method is deprecated. Please do not use it.');
return this.getLayer().getCanvas();
}
getSceneFunc() {
return this.attrs.sceneFunc || this['_sceneFunc'];
}
getHitFunc() {
return this.attrs.hitFunc || this['_hitFunc'];
}
/**
* returns whether or not a shadow will be rendered
* @method
* @name Konva.Shape#hasShadow
* @returns {Boolean}
*/
hasShadow() {
return this._getCache(HAS_SHADOW, this._hasShadow);
}
_hasShadow() {
return (this.shadowEnabled() &&
this.shadowOpacity() !== 0 &&
!!(this.shadowColor() ||
this.shadowBlur() ||
this.shadowOffsetX() ||
this.shadowOffsetY()));
}
_getFillPattern() {
return this._getCache(patternImage, this.__getFillPattern);
}
__getFillPattern() {
if (this.fillPatternImage()) {
var ctx = getDummyContext$1();
const pattern = ctx.createPattern(this.fillPatternImage(), this.fillPatternRepeat() || 'repeat');
if (pattern && pattern.setTransform) {
const tr = new Transform();
tr.translate(this.fillPatternX(), this.fillPatternY());
tr.rotate(Konva$2.getAngle(this.fillPatternRotation()));
tr.scale(this.fillPatternScaleX(), this.fillPatternScaleY());
tr.translate(-1 * this.fillPatternOffsetX(), -1 * this.fillPatternOffsetY());
const m = tr.getMatrix();
pattern.setTransform({
a: m[0],
b: m[1],
c: m[2],
d: m[3],
e: m[4],
f: m[5], // Vertical translation (moving).
});
}
return pattern;
}
}
_getLinearGradient() {
return this._getCache(linearGradient, this.__getLinearGradient);
}
__getLinearGradient() {
var colorStops = this.fillLinearGradientColorStops();
if (colorStops) {
var ctx = getDummyContext$1();
var start = this.fillLinearGradientStartPoint();
var end = this.fillLinearGradientEndPoint();
var grd = ctx.createLinearGradient(start.x, start.y, end.x, end.y);
// build color stops
for (var n = 0; n < colorStops.length; n += 2) {
grd.addColorStop(colorStops[n], colorStops[n + 1]);
}
return grd;
}
}
_getRadialGradient() {
return this._getCache(radialGradient, this.__getRadialGradient);
}
__getRadialGradient() {
var colorStops = this.fillRadialGradientColorStops();
if (colorStops) {
var ctx = getDummyContext$1();
var start = this.fillRadialGradientStartPoint();
var end = this.fillRadialGradientEndPoint();
var grd = ctx.createRadialGradient(start.x, start.y, this.fillRadialGradientStartRadius(), end.x, end.y, this.fillRadialGradientEndRadius());
// build color stops
for (var n = 0; n < colorStops.length; n += 2) {
grd.addColorStop(colorStops[n], colorStops[n + 1]);
}
return grd;
}
}
getShadowRGBA() {
return this._getCache(SHADOW_RGBA, this._getShadowRGBA);
}
_getShadowRGBA() {
if (this.hasShadow()) {
var rgba = Util.colorToRGBA(this.shadowColor());
return ('rgba(' +
rgba.r +
',' +
rgba.g +
',' +
rgba.b +
',' +
rgba.a * (this.shadowOpacity() || 1) +
')');
}
}
/**
* returns whether or not the shape will be filled
* @method
* @name Konva.Shape#hasFill
* @returns {Boolean}
*/
hasFill() {
return this._calculate('hasFill', [
'fillEnabled',
'fill',
'fillPatternImage',
'fillLinearGradientColorStops',
'fillRadialGradientColorStops',
], () => {
return (this.fillEnabled() &&
!!(this.fill() ||
this.fillPatternImage() ||
this.fillLinearGradientColorStops() ||
this.fillRadialGradientColorStops()));
});
}
/**
* returns whether or not the shape will be stroked
* @method
* @name Konva.Shape#hasStroke
* @returns {Boolean}
*/
hasStroke() {
return this._calculate('hasStroke', [
'strokeEnabled',
'strokeWidth',
'stroke',
'strokeLinearGradientColorStops',
], () => {
return (this.strokeEnabled() &&
this.strokeWidth() &&
!!(this.stroke() || this.strokeLinearGradientColorStops())
// this.getStrokeRadialGradientColorStops()
);
});
// return (
// this.strokeEnabled() &&
// this.strokeWidth() &&
// !!(this.stroke() || this.strokeLinearGradientColorStops())
// // this.getStrokeRadialGradientColorStops()
// );
}
hasHitStroke() {
const width = this.hitStrokeWidth();
// on auto just check by stroke
if (width === 'auto') {
return this.hasStroke();
}
// we should enable hit stroke if stroke is enabled
// and we have some value from width
return this.strokeEnabled() && !!width;
}
/**
* determines if point is in the shape, regardless if other shapes are on top of it. Note: because
* this method clears a temporary canvas and then redraws the shape, it performs very poorly if executed many times
* consecutively. Please use the {@link Konva.Stage#getIntersection} method if at all possible
* because it performs much better
* @method
* @name Konva.Shape#intersects
* @param {Object} point
* @param {Number} point.x
* @param {Number} point.y
* @returns {Boolean}
*/
intersects(point) {
var stage = this.getStage(), bufferHitCanvas = stage.bufferHitCanvas, p;
bufferHitCanvas.getContext().clear();
this.drawHit(bufferHitCanvas, null, true);
p = bufferHitCanvas.context.getImageData(Math.round(point.x), Math.round(point.y), 1, 1).data;
return p[3] > 0;
}
destroy() {
Node.prototype.destroy.call(this);
delete shapes[this.colorKey];
delete this.colorKey;
return this;
}
// why do we need buffer canvas?
// it give better result when a shape has
// stroke with fill and with some opacity
_useBufferCanvas(forceFill) {
// image and sprite still has "fill" as image
// so they use that method with forced fill
// it probably will be simpler, then copy/paste the code
var _a;
// buffer canvas is available only inside the stage
if (!this.getStage()) {
return false;
}
// force skip buffer canvas
const perfectDrawEnabled = (_a = this.attrs.perfectDrawEnabled) !== null && _a !== void 0 ? _a : true;
if (!perfectDrawEnabled) {
return false;
}
const hasFill = forceFill || this.hasFill();
const hasStroke = this.hasStroke();
const isTransparent = this.getAbsoluteOpacity() !== 1;
if (hasFill && hasStroke && isTransparent) {
return true;
}
const hasShadow = this.hasShadow();
const strokeForShadow = this.shadowForStrokeEnabled();
if (hasFill && hasStroke && hasShadow && strokeForShadow) {
return true;
}
return false;
}
setStrokeHitEnabled(val) {
Util.warn('strokeHitEnabled property is deprecated. Please use hitStrokeWidth instead.');
if (val) {
this.hitStrokeWidth('auto');
}
else {
this.hitStrokeWidth(0);
}
}
getStrokeHitEnabled() {
if (this.hitStrokeWidth() === 0) {
return false;
}
else {
return true;
}
}
/**
* return self rectangle (x, y, width, height) of shape.
* This method are not taken into account transformation and styles.
* @method
* @name Konva.Shape#getSelfRect
* @returns {Object} rect with {x, y, width, height} properties
* @example
*
* rect.getSelfRect(); // return {x:0, y:0, width:rect.width(), height:rect.height()}
* circle.getSelfRect(); // return {x: - circle.width() / 2, y: - circle.height() / 2, width:circle.width(), height:circle.height()}
*
*/
getSelfRect() {
var size = this.size();
return {
x: this._centroid ? -size.width / 2 : 0,
y: this._centroid ? -size.height / 2 : 0,
width: size.width,
height: size.height,
};
}
getClientRect(config = {}) {
const skipTransform = config.skipTransform;
const relativeTo = config.relativeTo;
const fillRect = this.getSelfRect();
const applyStroke = !config.skipStroke && this.hasStroke();
const strokeWidth = (applyStroke && this.strokeWidth()) || 0;
const fillAndStrokeWidth = fillRect.width + strokeWidth;
const fillAndStrokeHeight = fillRect.height + strokeWidth;
const applyShadow = !config.skipShadow && this.hasShadow();
const shadowOffsetX = applyShadow ? this.shadowOffsetX() : 0;
const shadowOffsetY = applyShadow ? this.shadowOffsetY() : 0;
const preWidth = fillAndStrokeWidth + Math.abs(shadowOffsetX);
const preHeight = fillAndStrokeHeight + Math.abs(shadowOffsetY);
const blurRadius = (applyShadow && this.shadowBlur()) || 0;
const width = preWidth + blurRadius * 2;
const height = preHeight + blurRadius * 2;
// if stroke, for example = 3
// we need to set x to 1.5, but after Math.round it will be 2
// as we have additional offset we need to increase width and height by 1 pixel
let roundingOffset = 0;
if (Math.round(strokeWidth / 2) !== strokeWidth / 2) {
roundingOffset = 1;
}
const rect = {
width: width + roundingOffset,
height: height + roundingOffset,
x: -Math.round(strokeWidth / 2 + blurRadius) +
Math.min(shadowOffsetX, 0) +
fillRect.x,
y: -Math.round(strokeWidth / 2 + blurRadius) +
Math.min(shadowOffsetY, 0) +
fillRect.y,
};
if (!skipTransform) {
return this._transformedRect(rect, relativeTo);
}
return rect;
}
drawScene(can, top) {
// basically there are 3 drawing modes
// 1 - simple drawing when nothing is cached.
// 2 - when we are caching current
// 3 - when node is cached and we need to draw it into layer
var layer = this.getLayer(), canvas = can || layer.getCanvas(), context = canvas.getContext(), cachedCanvas = this._getCanvasCache(), drawFunc = this.getSceneFunc(), hasShadow = this.hasShadow(), stage, bufferCanvas, bufferContext;
var skipBuffer = canvas.isCache;
var cachingSelf = top === this;
if (!this.isVisible() && !cachingSelf) {
return this;
}
// if node is cached we just need to draw from cache
if (cachedCanvas) {
context.save();
var m = this.getAbsoluteTransform(top).getMatrix();
context.transform(m[0], m[1], m[2], m[3], m[4], m[5]);
this._drawCachedSceneCanvas(context);
context.restore();
return this;
}
if (!drawFunc) {
return this;
}
context.save();
// if buffer canvas is needed
if (this._useBufferCanvas() && !skipBuffer) {
stage = this.getStage();
bufferCanvas = stage.bufferCanvas;
bufferContext = bufferCanvas.getContext();
bufferContext.clear();
bufferContext.save();
bufferContext._applyLineJoin(this);
// layer might be undefined if we are using cache before adding to layer
var o = this.getAbsoluteTransform(top).getMatrix();
bufferContext.transform(o[0], o[1], o[2], o[3], o[4], o[5]);
drawFunc.call(this, bufferContext, this);
bufferContext.restore();
var ratio = bufferCanvas.pixelRatio;
if (hasShadow) {
context._applyShadow(this);
}
context._applyOpacity(this);
context._applyGlobalCompositeOperation(this);
context.drawImage(bufferCanvas._canvas, 0, 0, bufferCanvas.width / ratio, bufferCanvas.height / ratio);
}
else {
context._applyLineJoin(this);
if (!cachingSelf) {
var o = this.getAbsoluteTransform(top).getMatrix();
context.transform(o[0], o[1], o[2], o[3], o[4], o[5]);
context._applyOpacity(this);
context._applyGlobalCompositeOperation(this);
}
if (hasShadow) {
context._applyShadow(this);
}
drawFunc.call(this, context, this);
}
context.restore();
return this;
}
drawHit(can, top, skipDragCheck = false) {
if (!this.shouldDrawHit(top, skipDragCheck)) {
return this;
}
var layer = this.getLayer(), canvas = can || layer.hitCanvas, context = canvas && canvas.getContext(), drawFunc = this.hitFunc() || this.sceneFunc(), cachedCanvas = this._getCanvasCache(), cachedHitCanvas = cachedCanvas && cachedCanvas.hit;
if (!this.colorKey) {
Util.warn('Looks like your canvas has a destroyed shape in it. Do not reuse shape after you destroyed it. If you want to reuse shape you should call remove() instead of destroy()');
}
if (cachedHitCanvas) {
context.save();
var m = this.getAbsoluteTransform(top).getMatrix();
context.transform(m[0], m[1], m[2], m[3], m[4], m[5]);
this._drawCachedHitCanvas(context);
context.restore();
return this;
}
if (!drawFunc) {
return this;
}
context.save();
context._applyLineJoin(this);
const selfCache = this === top;
if (!selfCache) {
var o = this.getAbsoluteTransform(top).getMatrix();
context.transform(o[0], o[1], o[2], o[3], o[4], o[5]);
}
drawFunc.call(this, context, this);
context.restore();
return this;
}
/**
* draw hit graph using the cached scene canvas
* @method
* @name Konva.Shape#drawHitFromCache
* @param {Integer} alphaThreshold alpha channel threshold that determines whether or not
* a pixel should be drawn onto the hit graph. Must be a value between 0 and 255.
* The default is 0
* @returns {Konva.Shape}
* @example
* shape.cache();
* shape.drawHitFromCache();
*/
drawHitFromCache(alphaThreshold = 0) {
var cachedCanvas = this._getCanvasCache(), sceneCanvas = this._getCachedSceneCanvas(), hitCanvas = cachedCanvas.hit, hitContext = hitCanvas.getContext(), hitWidth = hitCanvas.getWidth(), hitHeight = hitCanvas.getHeight(), hitImageData, hitData, len, rgbColorKey, i, alpha;
hitContext.clear();
hitContext.drawImage(sceneCanvas._canvas, 0, 0, hitWidth, hitHeight);
try {
hitImageData = hitContext.getImageData(0, 0, hitWidth, hitHeight);
hitData = hitImageData.data;
len = hitData.length;
rgbColorKey = Util._hexToRgb(this.colorKey);
// replace non transparent pixels with color key
for (i = 0; i < len; i += 4) {
alpha = hitData[i + 3];
if (alpha > alphaThreshold) {
hitData[i] = rgbColorKey.r;
hitData[i + 1] = rgbColorKey.g;
hitData[i + 2] = rgbColorKey.b;
hitData[i + 3] = 255;
}
else {
hitData[i + 3] = 0;
}
}
hitContext.putImageData(hitImageData, 0, 0);
}
catch (e) {
Util.error('Unable to draw hit graph from cached scene canvas. ' + e.message);
}
return this;
}
hasPointerCapture(pointerId) {
return hasPointerCapture(pointerId, this);
}
setPointerCapture(pointerId) {
setPointerCapture(pointerId, this);
}
releaseCapture(pointerId) {
releaseCapture(pointerId);
}
}
Shape.prototype._fillFunc = _fillFunc$2;
Shape.prototype._strokeFunc = _strokeFunc$2;
Shape.prototype._fillFuncHit = _fillFuncHit;
Shape.prototype._strokeFuncHit = _strokeFuncHit;
Shape.prototype._centroid = false;
Shape.prototype.nodeType = 'Shape';
_registerNode(Shape);
Shape.prototype.eventListeners = {};
Shape.prototype.on.call(Shape.prototype, 'shadowColorChange.konva shadowBlurChange.konva shadowOffsetChange.konva shadowOpacityChange.konva shadowEnabledChange.konva', _clearHasShadowCache);
Shape.prototype.on.call(Shape.prototype, 'shadowColorChange.konva shadowOpacityChange.konva shadowEnabledChange.konva', _clearGetShadowRGBACache);
Shape.prototype.on.call(Shape.prototype, 'fillPriorityChange.konva fillPatternImageChange.konva fillPatternRepeatChange.konva fillPatternScaleXChange.konva fillPatternScaleYChange.konva fillPatternOffsetXChange.konva fillPatternOffsetYChange.konva fillPatternXChange.konva fillPatternYChange.konva fillPatternRotationChange.konva', _clearFillPatternCache);
Shape.prototype.on.call(Shape.prototype, 'fillPriorityChange.konva fillLinearGradientColorStopsChange.konva fillLinearGradientStartPointXChange.konva fillLinearGradientStartPointYChange.konva fillLinearGradientEndPointXChange.konva fillLinearGradientEndPointYChange.konva', _clearLinearGradientCache);
Shape.prototype.on.call(Shape.prototype, 'fillPriorityChange.konva fillRadialGradientColorStopsChange.konva fillRadialGradientStartPointXChange.konva fillRadialGradientStartPointYChange.konva fillRadialGradientEndPointXChange.konva fillRadialGradientEndPointYChange.konva fillRadialGradientStartRadiusChange.konva fillRadialGradientEndRadiusChange.konva', _clearRadialGradientCache);
// add getters and setters
Factory.addGetterSetter(Shape, 'stroke', undefined, getStringOrGradientValidator());
/**
* get/set stroke color
* @name Konva.Shape#stroke
* @method
* @param {String} color
* @returns {String}
* @example
* // get stroke color
* var stroke = shape.stroke();
*
* // set stroke color with color string
* shape.stroke('green');
*
* // set stroke color with hex
* shape.stroke('#00ff00');
*
* // set stroke color with rgb
* shape.stroke('rgb(0,255,0)');
*
* // set stroke color with rgba and make it 50% opaque
* shape.stroke('rgba(0,255,0,0.5');
*/
Factory.addGetterSetter(Shape, 'strokeWidth', 2, getNumberValidator());
/**
* get/set stroke width
* @name Konva.Shape#strokeWidth
* @method
* @param {Number} strokeWidth
* @returns {Number}
* @example
* // get stroke width
* var strokeWidth = shape.strokeWidth();
*
* // set stroke width
* shape.strokeWidth(10);
*/
Factory.addGetterSetter(Shape, 'fillAfterStrokeEnabled', false);
/**
* get/set fillAfterStrokeEnabled property. By default Konva is drawing filling first, then stroke on top of the fill.
* In rare situations you may want a different behavior. When you have a stroke first then fill on top of it.
* Especially useful for Text objects.
* Default is false.
* @name Konva.Shape#fillAfterStrokeEnabled
* @method
* @param {Boolean} fillAfterStrokeEnabled
* @returns {Boolean}
* @example
* // get stroke width
* var fillAfterStrokeEnabled = shape.fillAfterStrokeEnabled();
*
* // set stroke width
* shape.fillAfterStrokeEnabled(true);
*/
Factory.addGetterSetter(Shape, 'hitStrokeWidth', 'auto', getNumberOrAutoValidator());
/**
* get/set stroke width for hit detection. Default value is "auto", it means it will be equals to strokeWidth
* @name Konva.Shape#hitStrokeWidth
* @method
* @param {Number} hitStrokeWidth
* @returns {Number}
* @example
* // get stroke width
* var hitStrokeWidth = shape.hitStrokeWidth();
*
* // set hit stroke width
* shape.hitStrokeWidth(20);
* // set hit stroke width always equals to scene stroke width
* shape.hitStrokeWidth('auto');
*/
Factory.addGetterSetter(Shape, 'strokeHitEnabled', true, getBooleanValidator());
/**
* **deprecated, use hitStrokeWidth instead!** get/set strokeHitEnabled property. Useful for performance optimization.
* You may set `shape.strokeHitEnabled(false)`. In this case stroke will be no draw on hit canvas, so hit area
* of shape will be decreased (by lineWidth / 2). Remember that non closed line with `strokeHitEnabled = false`
* will be not drawn on hit canvas, that is mean line will no trigger pointer events (like mouseover)
* Default value is true.
* @name Konva.Shape#strokeHitEnabled
* @method
* @param {Boolean} strokeHitEnabled
* @returns {Boolean}
* @example
* // get strokeHitEnabled
* var strokeHitEnabled = shape.strokeHitEnabled();
*
* // set strokeHitEnabled
* shape.strokeHitEnabled();
*/
Factory.addGetterSetter(Shape, 'perfectDrawEnabled', true, getBooleanValidator());
/**
* get/set perfectDrawEnabled. If a shape has fill, stroke and opacity you may set `perfectDrawEnabled` to false to improve performance.
* See http://konvajs.org/docs/performance/Disable_Perfect_Draw.html for more information.
* Default value is true
* @name Konva.Shape#perfectDrawEnabled
* @method
* @param {Boolean} perfectDrawEnabled
* @returns {Boolean}
* @example
* // get perfectDrawEnabled
* var perfectDrawEnabled = shape.perfectDrawEnabled();
*
* // set perfectDrawEnabled
* shape.perfectDrawEnabled();
*/
Factory.addGetterSetter(Shape, 'shadowForStrokeEnabled', true, getBooleanValidator());
/**
* get/set shadowForStrokeEnabled. Useful for performance optimization.
* You may set `shape.shadowForStrokeEnabled(false)`. In this case stroke will no effect shadow.
* Remember if you set `shadowForStrokeEnabled = false` for non closed line - that line will have no shadow!.
* Default value is true
* @name Konva.Shape#shadowForStrokeEnabled
* @method
* @param {Boolean} shadowForStrokeEnabled
* @returns {Boolean}
* @example
* // get shadowForStrokeEnabled
* var shadowForStrokeEnabled = shape.shadowForStrokeEnabled();
*
* // set shadowForStrokeEnabled
* shape.shadowForStrokeEnabled();
*/
Factory.addGetterSetter(Shape, 'lineJoin');
/**
* get/set line join. Can be miter, round, or bevel. The
* default is miter
* @name Konva.Shape#lineJoin
* @method
* @param {String} lineJoin
* @returns {String}
* @example
* // get line join
* var lineJoin = shape.lineJoin();
*
* // set line join
* shape.lineJoin('round');
*/
Factory.addGetterSetter(Shape, 'lineCap');
/**
* get/set line cap. Can be butt, round, or square
* @name Konva.Shape#lineCap
* @method
* @param {String} lineCap
* @returns {String}
* @example
* // get line cap
* var lineCap = shape.lineCap();
*
* // set line cap
* shape.lineCap('round');
*/
Factory.addGetterSetter(Shape, 'sceneFunc');
/**
* get/set scene draw function. That function is used to draw the shape on a canvas.
* Also that function will be used to draw hit area of the shape, in case if hitFunc is not defined.
* @name Konva.Shape#sceneFunc
* @method
* @param {Function} drawFunc drawing function
* @returns {Function}
* @example
* // get scene draw function
* var sceneFunc = shape.sceneFunc();
*
* // set scene draw function
* shape.sceneFunc(function(context, shape) {
* context.beginPath();
* context.rect(0, 0, shape.width(), shape.height());
* context.closePath();
* // important Konva method that fill and stroke shape from its properties
* // like stroke and fill
* context.fillStrokeShape(shape);
* });
*/
Factory.addGetterSetter(Shape, 'hitFunc');
/**
* get/set hit draw function. That function is used to draw custom hit area of a shape.
* @name Konva.Shape#hitFunc
* @method
* @param {Function} drawFunc drawing function
* @returns {Function}
* @example
* // get hit draw function
* var hitFunc = shape.hitFunc();
*
* // set hit draw function
* shape.hitFunc(function(context) {
* context.beginPath();
* context.rect(0, 0, shape.width(), shape.height());
* context.closePath();
* // important Konva method that fill and stroke shape from its properties
* context.fillStrokeShape(shape);
* });
*/
Factory.addGetterSetter(Shape, 'dash');
/**
* get/set dash array for stroke.
* @name Konva.Shape#dash
* @method
* @param {Array} dash
* @returns {Array}
* @example
* // apply dashed stroke that is 10px long and 5 pixels apart
* line.dash([10, 5]);
* // apply dashed stroke that is made up of alternating dashed
* // lines that are 10px long and 20px apart, and dots that have
* // a radius of 5px and are 20px apart
* line.dash([10, 20, 0.001, 20]);
*/
Factory.addGetterSetter(Shape, 'dashOffset', 0, getNumberValidator());
/**
* get/set dash offset for stroke.
* @name Konva.Shape#dash
* @method
* @param {Number} dash offset
* @returns {Number}
* @example
* // apply dashed stroke that is 10px long and 5 pixels apart with an offset of 5px
* line.dash([10, 5]);
* line.dashOffset(5);
*/
Factory.addGetterSetter(Shape, 'shadowColor', undefined, getStringValidator());
/**
* get/set shadow color
* @name Konva.Shape#shadowColor
* @method
* @param {String} color
* @returns {String}
* @example
* // get shadow color
* var shadow = shape.shadowColor();
*
* // set shadow color with color string
* shape.shadowColor('green');
*
* // set shadow color with hex
* shape.shadowColor('#00ff00');
*
* // set shadow color with rgb
* shape.shadowColor('rgb(0,255,0)');
*
* // set shadow color with rgba and make it 50% opaque
* shape.shadowColor('rgba(0,255,0,0.5');
*/
Factory.addGetterSetter(Shape, 'shadowBlur', 0, getNumberValidator());
/**
* get/set shadow blur
* @name Konva.Shape#shadowBlur
* @method
* @param {Number} blur
* @returns {Number}
* @example
* // get shadow blur
* var shadowBlur = shape.shadowBlur();
*
* // set shadow blur
* shape.shadowBlur(10);
*/
Factory.addGetterSetter(Shape, 'shadowOpacity', 1, getNumberValidator());
/**
* get/set shadow opacity. must be a value between 0 and 1
* @name Konva.Shape#shadowOpacity
* @method
* @param {Number} opacity
* @returns {Number}
* @example
* // get shadow opacity
* var shadowOpacity = shape.shadowOpacity();
*
* // set shadow opacity
* shape.shadowOpacity(0.5);
*/
Factory.addComponentsGetterSetter(Shape, 'shadowOffset', ['x', 'y']);
/**
* get/set shadow offset
* @name Konva.Shape#shadowOffset
* @method
* @param {Object} offset
* @param {Number} offset.x
* @param {Number} offset.y
* @returns {Object}
* @example
* // get shadow offset
* var shadowOffset = shape.shadowOffset();
*
* // set shadow offset
* shape.shadowOffset({
* x: 20,
* y: 10
* });
*/
Factory.addGetterSetter(Shape, 'shadowOffsetX', 0, getNumberValidator());
/**
* get/set shadow offset x
* @name Konva.Shape#shadowOffsetX
* @method
* @param {Number} x
* @returns {Number}
* @example
* // get shadow offset x
* var shadowOffsetX = shape.shadowOffsetX();
*
* // set shadow offset x
* shape.shadowOffsetX(5);
*/
Factory.addGetterSetter(Shape, 'shadowOffsetY', 0, getNumberValidator());
/**
* get/set shadow offset y
* @name Konva.Shape#shadowOffsetY
* @method
* @param {Number} y
* @returns {Number}
* @example
* // get shadow offset y
* var shadowOffsetY = shape.shadowOffsetY();
*
* // set shadow offset y
* shape.shadowOffsetY(5);
*/
Factory.addGetterSetter(Shape, 'fillPatternImage');
/**
* get/set fill pattern image
* @name Konva.Shape#fillPatternImage
* @method
* @param {Image} image object
* @returns {Image}
* @example
* // get fill pattern image
* var fillPatternImage = shape.fillPatternImage();
*
* // set fill pattern image
* var imageObj = new Image();
* imageObj.onload = function() {
* shape.fillPatternImage(imageObj);
* };
* imageObj.src = 'path/to/image/jpg';
*/
Factory.addGetterSetter(Shape, 'fill', undefined, getStringOrGradientValidator());
/**
* get/set fill color
* @name Konva.Shape#fill
* @method
* @param {String} color
* @returns {String}
* @example
* // get fill color
* var fill = shape.fill();
*
* // set fill color with color string
* shape.fill('green');
*
* // set fill color with hex
* shape.fill('#00ff00');
*
* // set fill color with rgb
* shape.fill('rgb(0,255,0)');
*
* // set fill color with rgba and make it 50% opaque
* shape.fill('rgba(0,255,0,0.5');
*
* // shape without fill
* shape.fill(null);
*/
Factory.addGetterSetter(Shape, 'fillPatternX', 0, getNumberValidator());
/**
* get/set fill pattern x
* @name Konva.Shape#fillPatternX
* @method
* @param {Number} x
* @returns {Number}
* @example
* // get fill pattern x
* var fillPatternX = shape.fillPatternX();
* // set fill pattern x
* shape.fillPatternX(20);
*/
Factory.addGetterSetter(Shape, 'fillPatternY', 0, getNumberValidator());
/**
* get/set fill pattern y
* @name Konva.Shape#fillPatternY
* @method
* @param {Number} y
* @returns {Number}
* @example
* // get fill pattern y
* var fillPatternY = shape.fillPatternY();
* // set fill pattern y
* shape.fillPatternY(20);
*/
Factory.addGetterSetter(Shape, 'fillLinearGradientColorStops');
/**
* get/set fill linear gradient color stops
* @name Konva.Shape#fillLinearGradientColorStops
* @method
* @param {Array} colorStops
* @returns {Array} colorStops
* @example
* // get fill linear gradient color stops
* var colorStops = shape.fillLinearGradientColorStops();
*
* // create a linear gradient that starts with red, changes to blue
* // halfway through, and then changes to green
* shape.fillLinearGradientColorStops(0, 'red', 0.5, 'blue', 1, 'green');
*/
Factory.addGetterSetter(Shape, 'strokeLinearGradientColorStops');
/**
* get/set stroke linear gradient color stops
* @name Konva.Shape#strokeLinearGradientColorStops
* @method
* @param {Array} colorStops
* @returns {Array} colorStops
* @example
* // get stroke linear gradient color stops
* var colorStops = shape.strokeLinearGradientColorStops();
*
* // create a linear gradient that starts with red, changes to blue
* // halfway through, and then changes to green
* shape.strokeLinearGradientColorStops([0, 'red', 0.5, 'blue', 1, 'green']);
*/
Factory.addGetterSetter(Shape, 'fillRadialGradientStartRadius', 0);
/**
* get/set fill radial gradient start radius
* @name Konva.Shape#fillRadialGradientStartRadius
* @method
* @param {Number} radius
* @returns {Number}
* @example
* // get radial gradient start radius
* var startRadius = shape.fillRadialGradientStartRadius();
*
* // set radial gradient start radius
* shape.fillRadialGradientStartRadius(0);
*/
Factory.addGetterSetter(Shape, 'fillRadialGradientEndRadius', 0);
/**
* get/set fill radial gradient end radius
* @name Konva.Shape#fillRadialGradientEndRadius
* @method
* @param {Number} radius
* @returns {Number}
* @example
* // get radial gradient end radius
* var endRadius = shape.fillRadialGradientEndRadius();
*
* // set radial gradient end radius
* shape.fillRadialGradientEndRadius(100);
*/
Factory.addGetterSetter(Shape, 'fillRadialGradientColorStops');
/**
* get/set fill radial gradient color stops
* @name Konva.Shape#fillRadialGradientColorStops
* @method
* @param {Number} colorStops
* @returns {Array}
* @example
* // get fill radial gradient color stops
* var colorStops = shape.fillRadialGradientColorStops();
*
* // create a radial gradient that starts with red, changes to blue
* // halfway through, and then changes to green
* shape.fillRadialGradientColorStops(0, 'red', 0.5, 'blue', 1, 'green');
*/
Factory.addGetterSetter(Shape, 'fillPatternRepeat', 'repeat');
/**
* get/set fill pattern repeat. Can be 'repeat', 'repeat-x', 'repeat-y', or 'no-repeat'. The default is 'repeat'
* @name Konva.Shape#fillPatternRepeat
* @method
* @param {String} repeat
* @returns {String}
* @example
* // get fill pattern repeat
* var repeat = shape.fillPatternRepeat();
*
* // repeat pattern in x direction only
* shape.fillPatternRepeat('repeat-x');
*
* // do not repeat the pattern
* shape.fillPatternRepeat('no-repeat');
*/
Factory.addGetterSetter(Shape, 'fillEnabled', true);
/**
* get/set fill enabled flag
* @name Konva.Shape#fillEnabled
* @method
* @param {Boolean} enabled
* @returns {Boolean}
* @example
* // get fill enabled flag
* var fillEnabled = shape.fillEnabled();
*
* // disable fill
* shape.fillEnabled(false);
*
* // enable fill
* shape.fillEnabled(true);
*/
Factory.addGetterSetter(Shape, 'strokeEnabled', true);
/**
* get/set stroke enabled flag
* @name Konva.Shape#strokeEnabled
* @method
* @param {Boolean} enabled
* @returns {Boolean}
* @example
* // get stroke enabled flag
* var strokeEnabled = shape.strokeEnabled();
*
* // disable stroke
* shape.strokeEnabled(false);
*
* // enable stroke
* shape.strokeEnabled(true);
*/
Factory.addGetterSetter(Shape, 'shadowEnabled', true);
/**
* get/set shadow enabled flag
* @name Konva.Shape#shadowEnabled
* @method
* @param {Boolean} enabled
* @returns {Boolean}
* @example
* // get shadow enabled flag
* var shadowEnabled = shape.shadowEnabled();
*
* // disable shadow
* shape.shadowEnabled(false);
*
* // enable shadow
* shape.shadowEnabled(true);
*/
Factory.addGetterSetter(Shape, 'dashEnabled', true);
/**
* get/set dash enabled flag
* @name Konva.Shape#dashEnabled
* @method
* @param {Boolean} enabled
* @returns {Boolean}
* @example
* // get dash enabled flag
* var dashEnabled = shape.dashEnabled();
*
* // disable dash
* shape.dashEnabled(false);
*
* // enable dash
* shape.dashEnabled(true);
*/
Factory.addGetterSetter(Shape, 'strokeScaleEnabled', true);
/**
* get/set strokeScale enabled flag
* @name Konva.Shape#strokeScaleEnabled
* @method
* @param {Boolean} enabled
* @returns {Boolean}
* @example
* // get stroke scale enabled flag
* var strokeScaleEnabled = shape.strokeScaleEnabled();
*
* // disable stroke scale
* shape.strokeScaleEnabled(false);
*
* // enable stroke scale
* shape.strokeScaleEnabled(true);
*/
Factory.addGetterSetter(Shape, 'fillPriority', 'color');
/**
* get/set fill priority. can be color, pattern, linear-gradient, or radial-gradient. The default is color.
* This is handy if you want to toggle between different fill types.
* @name Konva.Shape#fillPriority
* @method
* @param {String} priority
* @returns {String}
* @example
* // get fill priority
* var fillPriority = shape.fillPriority();
*
* // set fill priority
* shape.fillPriority('linear-gradient');
*/
Factory.addComponentsGetterSetter(Shape, 'fillPatternOffset', ['x', 'y']);
/**
* get/set fill pattern offset
* @name Konva.Shape#fillPatternOffset
* @method
* @param {Object} offset
* @param {Number} offset.x
* @param {Number} offset.y
* @returns {Object}
* @example
* // get fill pattern offset
* var patternOffset = shape.fillPatternOffset();
*
* // set fill pattern offset
* shape.fillPatternOffset({
* x: 20,
* y: 10
* });
*/
Factory.addGetterSetter(Shape, 'fillPatternOffsetX', 0, getNumberValidator());
/**
* get/set fill pattern offset x
* @name Konva.Shape#fillPatternOffsetX
* @method
* @param {Number} x
* @returns {Number}
* @example
* // get fill pattern offset x
* var patternOffsetX = shape.fillPatternOffsetX();
*
* // set fill pattern offset x
* shape.fillPatternOffsetX(20);
*/
Factory.addGetterSetter(Shape, 'fillPatternOffsetY', 0, getNumberValidator());
/**
* get/set fill pattern offset y
* @name Konva.Shape#fillPatternOffsetY
* @method
* @param {Number} y
* @returns {Number}
* @example
* // get fill pattern offset y
* var patternOffsetY = shape.fillPatternOffsetY();
*
* // set fill pattern offset y
* shape.fillPatternOffsetY(10);
*/
Factory.addComponentsGetterSetter(Shape, 'fillPatternScale', ['x', 'y']);
/**
* get/set fill pattern scale
* @name Konva.Shape#fillPatternScale
* @method
* @param {Object} scale
* @param {Number} scale.x
* @param {Number} scale.y
* @returns {Object}
* @example
* // get fill pattern scale
* var patternScale = shape.fillPatternScale();
*
* // set fill pattern scale
* shape.fillPatternScale({
* x: 2,
* y: 2
* });
*/
Factory.addGetterSetter(Shape, 'fillPatternScaleX', 1, getNumberValidator());
/**
* get/set fill pattern scale x
* @name Konva.Shape#fillPatternScaleX
* @method
* @param {Number} x
* @returns {Number}
* @example
* // get fill pattern scale x
* var patternScaleX = shape.fillPatternScaleX();
*
* // set fill pattern scale x
* shape.fillPatternScaleX(2);
*/
Factory.addGetterSetter(Shape, 'fillPatternScaleY', 1, getNumberValidator());
/**
* get/set fill pattern scale y
* @name Konva.Shape#fillPatternScaleY
* @method
* @param {Number} y
* @returns {Number}
* @example
* // get fill pattern scale y
* var patternScaleY = shape.fillPatternScaleY();
*
* // set fill pattern scale y
* shape.fillPatternScaleY(2);
*/
Factory.addComponentsGetterSetter(Shape, 'fillLinearGradientStartPoint', [
'x',
'y',
]);
/**
* get/set fill linear gradient start point
* @name Konva.Shape#fillLinearGradientStartPoint
* @method
* @param {Object} startPoint
* @param {Number} startPoint.x
* @param {Number} startPoint.y
* @returns {Object}
* @example
* // get fill linear gradient start point
* var startPoint = shape.fillLinearGradientStartPoint();
*
* // set fill linear gradient start point
* shape.fillLinearGradientStartPoint({
* x: 20,
* y: 10
* });
*/
Factory.addComponentsGetterSetter(Shape, 'strokeLinearGradientStartPoint', [
'x',
'y',
]);
/**
* get/set stroke linear gradient start point
* @name Konva.Shape#strokeLinearGradientStartPoint
* @method
* @param {Object} startPoint
* @param {Number} startPoint.x
* @param {Number} startPoint.y
* @returns {Object}
* @example
* // get stroke linear gradient start point
* var startPoint = shape.strokeLinearGradientStartPoint();
*
* // set stroke linear gradient start point
* shape.strokeLinearGradientStartPoint({
* x: 20,
* y: 10
* });
*/
Factory.addGetterSetter(Shape, 'fillLinearGradientStartPointX', 0);
/**
* get/set fill linear gradient start point x
* @name Konva.Shape#fillLinearGradientStartPointX
* @method
* @param {Number} x
* @returns {Number}
* @example
* // get fill linear gradient start point x
* var startPointX = shape.fillLinearGradientStartPointX();
*
* // set fill linear gradient start point x
* shape.fillLinearGradientStartPointX(20);
*/
Factory.addGetterSetter(Shape, 'strokeLinearGradientStartPointX', 0);
/**
* get/set stroke linear gradient start point x
* @name Konva.Shape#linearLinearGradientStartPointX
* @method
* @param {Number} x
* @returns {Number}
* @example
* // get stroke linear gradient start point x
* var startPointX = shape.strokeLinearGradientStartPointX();
*
* // set stroke linear gradient start point x
* shape.strokeLinearGradientStartPointX(20);
*/
Factory.addGetterSetter(Shape, 'fillLinearGradientStartPointY', 0);
/**
* get/set fill linear gradient start point y
* @name Konva.Shape#fillLinearGradientStartPointY
* @method
* @param {Number} y
* @returns {Number}
* @example
* // get fill linear gradient start point y
* var startPointY = shape.fillLinearGradientStartPointY();
*
* // set fill linear gradient start point y
* shape.fillLinearGradientStartPointY(20);
*/
Factory.addGetterSetter(Shape, 'strokeLinearGradientStartPointY', 0);
/**
* get/set stroke linear gradient start point y
* @name Konva.Shape#strokeLinearGradientStartPointY
* @method
* @param {Number} y
* @returns {Number}
* @example
* // get stroke linear gradient start point y
* var startPointY = shape.strokeLinearGradientStartPointY();
*
* // set stroke linear gradient start point y
* shape.strokeLinearGradientStartPointY(20);
*/
Factory.addComponentsGetterSetter(Shape, 'fillLinearGradientEndPoint', [
'x',
'y',
]);
/**
* get/set fill linear gradient end point
* @name Konva.Shape#fillLinearGradientEndPoint
* @method
* @param {Object} endPoint
* @param {Number} endPoint.x
* @param {Number} endPoint.y
* @returns {Object}
* @example
* // get fill linear gradient end point
* var endPoint = shape.fillLinearGradientEndPoint();
*
* // set fill linear gradient end point
* shape.fillLinearGradientEndPoint({
* x: 20,
* y: 10
* });
*/
Factory.addComponentsGetterSetter(Shape, 'strokeLinearGradientEndPoint', [
'x',
'y',
]);
/**
* get/set stroke linear gradient end point
* @name Konva.Shape#strokeLinearGradientEndPoint
* @method
* @param {Object} endPoint
* @param {Number} endPoint.x
* @param {Number} endPoint.y
* @returns {Object}
* @example
* // get stroke linear gradient end point
* var endPoint = shape.strokeLinearGradientEndPoint();
*
* // set stroke linear gradient end point
* shape.strokeLinearGradientEndPoint({
* x: 20,
* y: 10
* });
*/
Factory.addGetterSetter(Shape, 'fillLinearGradientEndPointX', 0);
/**
* get/set fill linear gradient end point x
* @name Konva.Shape#fillLinearGradientEndPointX
* @method
* @param {Number} x
* @returns {Number}
* @example
* // get fill linear gradient end point x
* var endPointX = shape.fillLinearGradientEndPointX();
*
* // set fill linear gradient end point x
* shape.fillLinearGradientEndPointX(20);
*/
Factory.addGetterSetter(Shape, 'strokeLinearGradientEndPointX', 0);
/**
* get/set fill linear gradient end point x
* @name Konva.Shape#strokeLinearGradientEndPointX
* @method
* @param {Number} x
* @returns {Number}
* @example
* // get stroke linear gradient end point x
* var endPointX = shape.strokeLinearGradientEndPointX();
*
* // set stroke linear gradient end point x
* shape.strokeLinearGradientEndPointX(20);
*/
Factory.addGetterSetter(Shape, 'fillLinearGradientEndPointY', 0);
/**
* get/set fill linear gradient end point y
* @name Konva.Shape#fillLinearGradientEndPointY
* @method
* @param {Number} y
* @returns {Number}
* @example
* // get fill linear gradient end point y
* var endPointY = shape.fillLinearGradientEndPointY();
*
* // set fill linear gradient end point y
* shape.fillLinearGradientEndPointY(20);
*/
Factory.addGetterSetter(Shape, 'strokeLinearGradientEndPointY', 0);
/**
* get/set stroke linear gradient end point y
* @name Konva.Shape#strokeLinearGradientEndPointY
* @method
* @param {Number} y
* @returns {Number}
* @example
* // get stroke linear gradient end point y
* var endPointY = shape.strokeLinearGradientEndPointY();
*
* // set stroke linear gradient end point y
* shape.strokeLinearGradientEndPointY(20);
*/
Factory.addComponentsGetterSetter(Shape, 'fillRadialGradientStartPoint', [
'x',
'y',
]);
/**
* get/set fill radial gradient start point
* @name Konva.Shape#fillRadialGradientStartPoint
* @method
* @param {Object} startPoint
* @param {Number} startPoint.x
* @param {Number} startPoint.y
* @returns {Object}
* @example
* // get fill radial gradient start point
* var startPoint = shape.fillRadialGradientStartPoint();
*
* // set fill radial gradient start point
* shape.fillRadialGradientStartPoint({
* x: 20,
* y: 10
* });
*/
Factory.addGetterSetter(Shape, 'fillRadialGradientStartPointX', 0);
/**
* get/set fill radial gradient start point x
* @name Konva.Shape#fillRadialGradientStartPointX
* @method
* @param {Number} x
* @returns {Number}
* @example
* // get fill radial gradient start point x
* var startPointX = shape.fillRadialGradientStartPointX();
*
* // set fill radial gradient start point x
* shape.fillRadialGradientStartPointX(20);
*/
Factory.addGetterSetter(Shape, 'fillRadialGradientStartPointY', 0);
/**
* get/set fill radial gradient start point y
* @name Konva.Shape#fillRadialGradientStartPointY
* @method
* @param {Number} y
* @returns {Number}
* @example
* // get fill radial gradient start point y
* var startPointY = shape.fillRadialGradientStartPointY();
*
* // set fill radial gradient start point y
* shape.fillRadialGradientStartPointY(20);
*/
Factory.addComponentsGetterSetter(Shape, 'fillRadialGradientEndPoint', [
'x',
'y',
]);
/**
* get/set fill radial gradient end point
* @name Konva.Shape#fillRadialGradientEndPoint
* @method
* @param {Object} endPoint
* @param {Number} endPoint.x
* @param {Number} endPoint.y
* @returns {Object}
* @example
* // get fill radial gradient end point
* var endPoint = shape.fillRadialGradientEndPoint();
*
* // set fill radial gradient end point
* shape.fillRadialGradientEndPoint({
* x: 20,
* y: 10
* });
*/
Factory.addGetterSetter(Shape, 'fillRadialGradientEndPointX', 0);
/**
* get/set fill radial gradient end point x
* @name Konva.Shape#fillRadialGradientEndPointX
* @method
* @param {Number} x
* @returns {Number}
* @example
* // get fill radial gradient end point x
* var endPointX = shape.fillRadialGradientEndPointX();
*
* // set fill radial gradient end point x
* shape.fillRadialGradientEndPointX(20);
*/
Factory.addGetterSetter(Shape, 'fillRadialGradientEndPointY', 0);
/**
* get/set fill radial gradient end point y
* @name Konva.Shape#fillRadialGradientEndPointY
* @method
* @param {Number} y
* @returns {Number}
* @example
* // get fill radial gradient end point y
* var endPointY = shape.fillRadialGradientEndPointY();
*
* // set fill radial gradient end point y
* shape.fillRadialGradientEndPointY(20);
*/
Factory.addGetterSetter(Shape, 'fillPatternRotation', 0);
/**
* get/set fill pattern rotation in degrees
* @name Konva.Shape#fillPatternRotation
* @method
* @param {Number} rotation
* @returns {Konva.Shape}
* @example
* // get fill pattern rotation
* var patternRotation = shape.fillPatternRotation();
*
* // set fill pattern rotation
* shape.fillPatternRotation(20);
*/
Factory.backCompat(Shape, {
dashArray: 'dash',
getDashArray: 'getDash',
setDashArray: 'getDash',
drawFunc: 'sceneFunc',
getDrawFunc: 'getSceneFunc',
setDrawFunc: 'setSceneFunc',
drawHitFunc: 'hitFunc',
getDrawHitFunc: 'getHitFunc',
setDrawHitFunc: 'setHitFunc',
});
// constants
var HASH = '#', BEFORE_DRAW = 'beforeDraw', DRAW = 'draw',
/*
* 2 - 3 - 4
* | |
* 1 - 0 5
* |
* 8 - 7 - 6
*/
INTERSECTION_OFFSETS = [
{ x: 0, y: 0 },
{ x: -1, y: -1 },
{ x: 1, y: -1 },
{ x: 1, y: 1 },
{ x: -1, y: 1 }, // 8
], INTERSECTION_OFFSETS_LEN = INTERSECTION_OFFSETS.length;
/**
* Layer constructor. Layers are tied to their own canvas element and are used
* to contain groups or shapes.
* @constructor
* @memberof Konva
* @augments Konva.Container
* @param {Object} config
* @param {Boolean} [config.clearBeforeDraw] set this property to false if you don't want
* to clear the canvas before each layer draw. The default value is true.
* @param {Number} [config.x]
* @param {Number} [config.y]
* @param {Number} [config.width]
* @param {Number} [config.height]
* @param {Boolean} [config.visible]
* @param {Boolean} [config.listening] whether or not the node is listening for events
* @param {String} [config.id] unique id
* @param {String} [config.name] non-unique name
* @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1
* @param {Object} [config.scale] set scale
* @param {Number} [config.scaleX] set scale x
* @param {Number} [config.scaleY] set scale y
* @param {Number} [config.rotation] rotation in degrees
* @param {Object} [config.offset] offset from center point and rotation point
* @param {Number} [config.offsetX] set offset x
* @param {Number} [config.offsetY] set offset y
* @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop
* the entire stage by dragging any portion of the stage
* @param {Number} [config.dragDistance]
* @param {Function} [config.dragBoundFunc]
* * @param {Object} [config.clip] set clip
* @param {Number} [config.clipX] set clip x
* @param {Number} [config.clipY] set clip y
* @param {Number} [config.clipWidth] set clip width
* @param {Number} [config.clipHeight] set clip height
* @param {Function} [config.clipFunc] set clip func
* @example
* var layer = new Konva.Layer();
* stage.add(layer);
* // now you can add shapes, groups into the layer
*/
class Layer extends Container {
constructor(config) {
super(config);
this.canvas = new SceneCanvas();
this.hitCanvas = new HitCanvas({
pixelRatio: 1,
});
this._waitingForDraw = false;
this.on('visibleChange.konva', this._checkVisibility);
this._checkVisibility();
this.on('imageSmoothingEnabledChange.konva', this._setSmoothEnabled);
this._setSmoothEnabled();
}
// for nodejs?
createPNGStream() {
const c = this.canvas._canvas;
return c.createPNGStream();
}
/**
* get layer canvas wrapper
* @method
* @name Konva.Layer#getCanvas
*/
getCanvas() {
return this.canvas;
}
/**
* get native canvas element
* @method
* @name Konva.Layer#getNativeCanvasElement
*/
getNativeCanvasElement() {
return this.canvas._canvas;
}
/**
* get layer hit canvas
* @method
* @name Konva.Layer#getHitCanvas
*/
getHitCanvas() {
return this.hitCanvas;
}
/**
* get layer canvas context
* @method
* @name Konva.Layer#getContext
*/
getContext() {
return this.getCanvas().getContext();
}
// TODO: deprecate this method
clear(bounds) {
this.getContext().clear(bounds);
this.getHitCanvas().getContext().clear(bounds);
return this;
}
// extend Node.prototype.setZIndex
setZIndex(index) {
super.setZIndex(index);
var stage = this.getStage();
if (stage && stage.content) {
stage.content.removeChild(this.getNativeCanvasElement());
if (index < stage.children.length - 1) {
stage.content.insertBefore(this.getNativeCanvasElement(), stage.children[index + 1].getCanvas()._canvas);
}
else {
stage.content.appendChild(this.getNativeCanvasElement());
}
}
return this;
}
moveToTop() {
Node.prototype.moveToTop.call(this);
var stage = this.getStage();
if (stage && stage.content) {
stage.content.removeChild(this.getNativeCanvasElement());
stage.content.appendChild(this.getNativeCanvasElement());
}
return true;
}
moveUp() {
var moved = Node.prototype.moveUp.call(this);
if (!moved) {
return false;
}
var stage = this.getStage();
if (!stage || !stage.content) {
return false;
}
stage.content.removeChild(this.getNativeCanvasElement());
if (this.index < stage.children.length - 1) {
stage.content.insertBefore(this.getNativeCanvasElement(), stage.children[this.index + 1].getCanvas()._canvas);
}
else {
stage.content.appendChild(this.getNativeCanvasElement());
}
return true;
}
// extend Node.prototype.moveDown
moveDown() {
if (Node.prototype.moveDown.call(this)) {
var stage = this.getStage();
if (stage) {
var children = stage.children;
if (stage.content) {
stage.content.removeChild(this.getNativeCanvasElement());
stage.content.insertBefore(this.getNativeCanvasElement(), children[this.index + 1].getCanvas()._canvas);
}
}
return true;
}
return false;
}
// extend Node.prototype.moveToBottom
moveToBottom() {
if (Node.prototype.moveToBottom.call(this)) {
var stage = this.getStage();
if (stage) {
var children = stage.children;
if (stage.content) {
stage.content.removeChild(this.getNativeCanvasElement());
stage.content.insertBefore(this.getNativeCanvasElement(), children[1].getCanvas()._canvas);
}
}
return true;
}
return false;
}
getLayer() {
return this;
}
remove() {
var _canvas = this.getNativeCanvasElement();
Node.prototype.remove.call(this);
if (_canvas && _canvas.parentNode && Util._isInDocument(_canvas)) {
_canvas.parentNode.removeChild(_canvas);
}
return this;
}
getStage() {
return this.parent;
}
setSize({ width, height }) {
this.canvas.setSize(width, height);
this.hitCanvas.setSize(width, height);
this._setSmoothEnabled();
return this;
}
_validateAdd(child) {
var type = child.getType();
if (type !== 'Group' && type !== 'Shape') {
Util.throw('You may only add groups and shapes to a layer.');
}
}
_toKonvaCanvas(config) {
config = config || {};
config.width = config.width || this.getWidth();
config.height = config.height || this.getHeight();
config.x = config.x !== undefined ? config.x : this.x();
config.y = config.y !== undefined ? config.y : this.y();
return Node.prototype._toKonvaCanvas.call(this, config);
}
_checkVisibility() {
const visible = this.visible();
if (visible) {
this.canvas._canvas.style.display = 'block';
}
else {
this.canvas._canvas.style.display = 'none';
}
}
_setSmoothEnabled() {
this.getContext()._context.imageSmoothingEnabled =
this.imageSmoothingEnabled();
}
/**
* get/set width of layer. getter return width of stage. setter doing nothing.
* if you want change width use `stage.width(value);`
* @name Konva.Layer#width
* @method
* @returns {Number}
* @example
* var width = layer.width();
*/
getWidth() {
if (this.parent) {
return this.parent.width();
}
}
setWidth() {
Util.warn('Can not change width of layer. Use "stage.width(value)" function instead.');
}
/**
* get/set height of layer.getter return height of stage. setter doing nothing.
* if you want change height use `stage.height(value);`
* @name Konva.Layer#height
* @method
* @returns {Number}
* @example
* var height = layer.height();
*/
getHeight() {
if (this.parent) {
return this.parent.height();
}
}
setHeight() {
Util.warn('Can not change height of layer. Use "stage.height(value)" function instead.');
}
/**
* batch draw. this function will not do immediate draw
* but it will schedule drawing to next tick (requestAnimFrame)
* @method
* @name Konva.Layer#batchDraw
* @return {Konva.Layer} this
*/
batchDraw() {
if (!this._waitingForDraw) {
this._waitingForDraw = true;
Util.requestAnimFrame(() => {
this.draw();
this._waitingForDraw = false;
});
}
return this;
}
/**
* get visible intersection shape. This is the preferred
* method for determining if a point intersects a shape or not
* also you may pass optional selector parameter to return ancestor of intersected shape
* @method
* @name Konva.Layer#getIntersection
* @param {Object} pos
* @param {Number} pos.x
* @param {Number} pos.y
* @returns {Konva.Node}
* @example
* var shape = layer.getIntersection({x: 50, y: 50});
*/
getIntersection(pos) {
if (!this.isListening() || !this.isVisible()) {
return null;
}
// in some cases antialiased area may be bigger than 1px
// it is possible if we will cache node, then scale it a lot
var spiralSearchDistance = 1;
var continueSearch = false;
while (true) {
for (let i = 0; i < INTERSECTION_OFFSETS_LEN; i++) {
const intersectionOffset = INTERSECTION_OFFSETS[i];
const obj = this._getIntersection({
x: pos.x + intersectionOffset.x * spiralSearchDistance,
y: pos.y + intersectionOffset.y * spiralSearchDistance,
});
const shape = obj.shape;
if (shape) {
return shape;
}
// we should continue search if we found antialiased pixel
// that means our node somewhere very close
continueSearch = !!obj.antialiased;
// stop search if found empty pixel
if (!obj.antialiased) {
break;
}
}
// if no shape, and no antialiased pixel, we should end searching
if (continueSearch) {
spiralSearchDistance += 1;
}
else {
return null;
}
}
}
_getIntersection(pos) {
const ratio = this.hitCanvas.pixelRatio;
const p = this.hitCanvas.context.getImageData(Math.round(pos.x * ratio), Math.round(pos.y * ratio), 1, 1).data;
const p3 = p[3];
// fully opaque pixel
if (p3 === 255) {
const colorKey = Util._rgbToHex(p[0], p[1], p[2]);
const shape = shapes[HASH + colorKey];
if (shape) {
return {
shape: shape,
};
}
return {
antialiased: true,
};
}
else if (p3 > 0) {
// antialiased pixel
return {
antialiased: true,
};
}
// empty pixel
return {};
}
drawScene(can, top) {
var layer = this.getLayer(), canvas = can || (layer && layer.getCanvas());
this._fire(BEFORE_DRAW, {
node: this,
});
if (this.clearBeforeDraw()) {
canvas.getContext().clear();
}
Container.prototype.drawScene.call(this, canvas, top);
this._fire(DRAW, {
node: this,
});
return this;
}
drawHit(can, top) {
var layer = this.getLayer(), canvas = can || (layer && layer.hitCanvas);
if (layer && layer.clearBeforeDraw()) {
layer.getHitCanvas().getContext().clear();
}
Container.prototype.drawHit.call(this, canvas, top);
return this;
}
/**
* enable hit graph. **DEPRECATED!** Use `layer.listening(true)` instead.
* @name Konva.Layer#enableHitGraph
* @method
* @returns {Layer}
*/
enableHitGraph() {
this.hitGraphEnabled(true);
return this;
}
/**
* disable hit graph. **DEPRECATED!** Use `layer.listening(false)` instead.
* @name Konva.Layer#disableHitGraph
* @method
* @returns {Layer}
*/
disableHitGraph() {
this.hitGraphEnabled(false);
return this;
}
setHitGraphEnabled(val) {
Util.warn('hitGraphEnabled method is deprecated. Please use layer.listening() instead.');
this.listening(val);
}
getHitGraphEnabled(val) {
Util.warn('hitGraphEnabled method is deprecated. Please use layer.listening() instead.');
return this.listening();
}
/**
* Show or hide hit canvas over the stage. May be useful for debugging custom hitFunc
* @name Konva.Layer#toggleHitCanvas
* @method
*/
toggleHitCanvas() {
if (!this.parent || !this.parent['content']) {
return;
}
var parent = this.parent;
var added = !!this.hitCanvas._canvas.parentNode;
if (added) {
parent.content.removeChild(this.hitCanvas._canvas);
}
else {
parent.content.appendChild(this.hitCanvas._canvas);
}
}
}
Layer.prototype.nodeType = 'Layer';
_registerNode(Layer);
/**
* get/set imageSmoothingEnabled flag
* For more info see https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/imageSmoothingEnabled
* @name Konva.Layer#imageSmoothingEnabled
* @method
* @param {Boolean} imageSmoothingEnabled
* @returns {Boolean}
* @example
* // get imageSmoothingEnabled flag
* var imageSmoothingEnabled = layer.imageSmoothingEnabled();
*
* layer.imageSmoothingEnabled(false);
*
* layer.imageSmoothingEnabled(true);
*/
Factory.addGetterSetter(Layer, 'imageSmoothingEnabled', true);
/**
* get/set clearBeforeDraw flag which determines if the layer is cleared or not
* before drawing
* @name Konva.Layer#clearBeforeDraw
* @method
* @param {Boolean} clearBeforeDraw
* @returns {Boolean}
* @example
* // get clearBeforeDraw flag
* var clearBeforeDraw = layer.clearBeforeDraw();
*
* // disable clear before draw
* layer.clearBeforeDraw(false);
*
* // enable clear before draw
* layer.clearBeforeDraw(true);
*/
Factory.addGetterSetter(Layer, 'clearBeforeDraw', true);
Factory.addGetterSetter(Layer, 'hitGraphEnabled', true, getBooleanValidator());
/**
* get/set hitGraphEnabled flag. **DEPRECATED!** Use `layer.listening(false)` instead.
* Disabling the hit graph will greatly increase
* draw performance because the hit graph will not be redrawn each time the layer is
* drawn. This, however, also disables mouse/touch event detection
* @name Konva.Layer#hitGraphEnabled
* @method
* @param {Boolean} enabled
* @returns {Boolean}
* @example
* // get hitGraphEnabled flag
* var hitGraphEnabled = layer.hitGraphEnabled();
*
* // disable hit graph
* layer.hitGraphEnabled(false);
*
* // enable hit graph
* layer.hitGraphEnabled(true);
*/
/**
* FastLayer constructor. **DEPRECATED!** Please use `Konva.Layer({ listening: false})` instead. Layers are tied to their own canvas element and are used
* to contain shapes only. If you don't need node nesting, mouse and touch interactions,
* or event pub/sub, you should use FastLayer instead of Layer to create your layers.
* It renders about 2x faster than normal layers.
*
* @constructor
* @memberof Konva
* @augments Konva.Layer
* * @param {Object} [config.clip] set clip
* @param {Number} [config.clipX] set clip x
* @param {Number} [config.clipY] set clip y
* @param {Number} [config.clipWidth] set clip width
* @param {Number} [config.clipHeight] set clip height
* @param {Function} [config.clipFunc] set clip func
* @example
* var layer = new Konva.FastLayer();
*/
class FastLayer extends Layer {
constructor(attrs) {
super(attrs);
this.listening(false);
Util.warn('Konva.Fast layer is deprecated. Please use "new Konva.Layer({ listening: false })" instead.');
}
}
FastLayer.prototype.nodeType = 'FastLayer';
_registerNode(FastLayer);
/**
* Group constructor. Groups are used to contain shapes or other groups.
* @constructor
* @memberof Konva
* @augments Konva.Container
* @param {Object} config
* @param {Number} [config.x]
* @param {Number} [config.y]
* @param {Number} [config.width]
* @param {Number} [config.height]
* @param {Boolean} [config.visible]
* @param {Boolean} [config.listening] whether or not the node is listening for events
* @param {String} [config.id] unique id
* @param {String} [config.name] non-unique name
* @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1
* @param {Object} [config.scale] set scale
* @param {Number} [config.scaleX] set scale x
* @param {Number} [config.scaleY] set scale y
* @param {Number} [config.rotation] rotation in degrees
* @param {Object} [config.offset] offset from center point and rotation point
* @param {Number} [config.offsetX] set offset x
* @param {Number} [config.offsetY] set offset y
* @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop
* the entire stage by dragging any portion of the stage
* @param {Number} [config.dragDistance]
* @param {Function} [config.dragBoundFunc]
* * @param {Object} [config.clip] set clip
* @param {Number} [config.clipX] set clip x
* @param {Number} [config.clipY] set clip y
* @param {Number} [config.clipWidth] set clip width
* @param {Number} [config.clipHeight] set clip height
* @param {Function} [config.clipFunc] set clip func
* @example
* var group = new Konva.Group();
*/
class Group extends Container {
_validateAdd(child) {
var type = child.getType();
if (type !== 'Group' && type !== 'Shape') {
Util.throw('You may only add groups and shapes to groups.');
}
}
}
Group.prototype.nodeType = 'Group';
_registerNode(Group);
var now = (function () {
if (glob.performance && glob.performance.now) {
return function () {
return glob.performance.now();
};
}
return function () {
return new Date().getTime();
};
})();
/**
* Animation constructor.
* @constructor
* @memberof Konva
* @param {AnimationFn} func function executed on each animation frame. The function is passed a frame object, which contains
* timeDiff, lastTime, time, and frameRate properties. The timeDiff property is the number of milliseconds that have passed
* since the last animation frame. The time property is the time in milliseconds that elapsed from the moment the animation started
* to the current animation frame. The lastTime property is a `time` value from the previous frame. The frameRate property is the current frame rate in frames / second.
* Return false from function, if you don't need to redraw layer/layers on some frames.
* @param {Konva.Layer|Array} [layers] layer(s) to be redrawn on each animation frame. Can be a layer, an array of layers, or null.
* Not specifying a node will result in no redraw.
* @example
* // move a node to the right at 50 pixels / second
* var velocity = 50;
*
* var anim = new Konva.Animation(function(frame) {
* var dist = velocity * (frame.timeDiff / 1000);
* node.move({x: dist, y: 0});
* }, layer);
*
* anim.start();
*/
class Animation {
constructor(func, layers) {
this.id = Animation.animIdCounter++;
this.frame = {
time: 0,
timeDiff: 0,
lastTime: now(),
frameRate: 0,
};
this.func = func;
this.setLayers(layers);
}
/**
* set layers to be redrawn on each animation frame
* @method
* @name Konva.Animation#setLayers
* @param {Konva.Layer|Array} [layers] layer(s) to be redrawn. Can be a layer, an array of layers, or null. Not specifying a node will result in no redraw.
* @return {Konva.Animation} this
*/
setLayers(layers) {
var lays = [];
// if passing in no layers
if (!layers) {
lays = [];
}
else if (layers.length > 0) {
// if passing in an array of Layers
// NOTE: layers could be an array. for simplicity, I'm just inspecting
// the length property to check for both cases
lays = layers;
}
else {
// if passing in a Layer
lays = [layers];
}
this.layers = lays;
return this;
}
/**
* get layers
* @method
* @name Konva.Animation#getLayers
* @return {Array} Array of Konva.Layer
*/
getLayers() {
return this.layers;
}
/**
* add layer. Returns true if the layer was added, and false if it was not
* @method
* @name Konva.Animation#addLayer
* @param {Konva.Layer} layer to add
* @return {Bool} true if layer is added to animation, otherwise false
*/
addLayer(layer) {
var layers = this.layers, len = layers.length, n;
// don't add the layer if it already exists
for (n = 0; n < len; n++) {
if (layers[n]._id === layer._id) {
return false;
}
}
this.layers.push(layer);
return true;
}
/**
* determine if animation is running or not. returns true or false
* @method
* @name Konva.Animation#isRunning
* @return {Bool} is animation running?
*/
isRunning() {
var a = Animation, animations = a.animations, len = animations.length, n;
for (n = 0; n < len; n++) {
if (animations[n].id === this.id) {
return true;
}
}
return false;
}
/**
* start animation
* @method
* @name Konva.Animation#start
* @return {Konva.Animation} this
*/
start() {
this.stop();
this.frame.timeDiff = 0;
this.frame.lastTime = now();
Animation._addAnimation(this);
return this;
}
/**
* stop animation
* @method
* @name Konva.Animation#stop
* @return {Konva.Animation} this
*/
stop() {
Animation._removeAnimation(this);
return this;
}
_updateFrameObject(time) {
this.frame.timeDiff = time - this.frame.lastTime;
this.frame.lastTime = time;
this.frame.time += this.frame.timeDiff;
this.frame.frameRate = 1000 / this.frame.timeDiff;
}
static _addAnimation(anim) {
this.animations.push(anim);
this._handleAnimation();
}
static _removeAnimation(anim) {
var id = anim.id, animations = this.animations, len = animations.length, n;
for (n = 0; n < len; n++) {
if (animations[n].id === id) {
this.animations.splice(n, 1);
break;
}
}
}
static _runFrames() {
var layerHash = {}, animations = this.animations, anim, layers, func, n, i, layersLen, layer, key, needRedraw;
/*
* loop through all animations and execute animation
* function. if the animation object has specified node,
* we can add the node to the nodes hash to eliminate
* drawing the same node multiple times. The node property
* can be the stage itself or a layer
*/
/*
* WARNING: don't cache animations.length because it could change while
* the for loop is running, causing a JS error
*/
for (n = 0; n < animations.length; n++) {
anim = animations[n];
layers = anim.layers;
func = anim.func;
anim._updateFrameObject(now());
layersLen = layers.length;
// if animation object has a function, execute it
if (func) {
// allow anim bypassing drawing
needRedraw = func.call(anim, anim.frame) !== false;
}
else {
needRedraw = true;
}
if (!needRedraw) {
continue;
}
for (i = 0; i < layersLen; i++) {
layer = layers[i];
if (layer._id !== undefined) {
layerHash[layer._id] = layer;
}
}
}
for (key in layerHash) {
if (!layerHash.hasOwnProperty(key)) {
continue;
}
layerHash[key].batchDraw();
}
}
static _animationLoop() {
var Anim = Animation;
if (Anim.animations.length) {
Anim._runFrames();
Util.requestAnimFrame(Anim._animationLoop);
}
else {
Anim.animRunning = false;
}
}
static _handleAnimation() {
if (!this.animRunning) {
this.animRunning = true;
Util.requestAnimFrame(this._animationLoop);
}
}
}
Animation.animations = [];
Animation.animIdCounter = 0;
Animation.animRunning = false;
var blacklist = {
node: 1,
duration: 1,
easing: 1,
onFinish: 1,
yoyo: 1,
}, PAUSED = 1, PLAYING = 2, REVERSING = 3, idCounter = 0, colorAttrs = ['fill', 'stroke', 'shadowColor'];
class TweenEngine {
constructor(prop, propFunc, func, begin, finish, duration, yoyo) {
this.prop = prop;
this.propFunc = propFunc;
this.begin = begin;
this._pos = begin;
this.duration = duration;
this._change = 0;
this.prevPos = 0;
this.yoyo = yoyo;
this._time = 0;
this._position = 0;
this._startTime = 0;
this._finish = 0;
this.func = func;
this._change = finish - this.begin;
this.pause();
}
fire(str) {
var handler = this[str];
if (handler) {
handler();
}
}
setTime(t) {
if (t > this.duration) {
if (this.yoyo) {
this._time = this.duration;
this.reverse();
}
else {
this.finish();
}
}
else if (t < 0) {
if (this.yoyo) {
this._time = 0;
this.play();
}
else {
this.reset();
}
}
else {
this._time = t;
this.update();
}
}
getTime() {
return this._time;
}
setPosition(p) {
this.prevPos = this._pos;
this.propFunc(p);
this._pos = p;
}
getPosition(t) {
if (t === undefined) {
t = this._time;
}
return this.func(t, this.begin, this._change, this.duration);
}
play() {
this.state = PLAYING;
this._startTime = this.getTimer() - this._time;
this.onEnterFrame();
this.fire('onPlay');
}
reverse() {
this.state = REVERSING;
this._time = this.duration - this._time;
this._startTime = this.getTimer() - this._time;
this.onEnterFrame();
this.fire('onReverse');
}
seek(t) {
this.pause();
this._time = t;
this.update();
this.fire('onSeek');
}
reset() {
this.pause();
this._time = 0;
this.update();
this.fire('onReset');
}
finish() {
this.pause();
this._time = this.duration;
this.update();
this.fire('onFinish');
}
update() {
this.setPosition(this.getPosition(this._time));
this.fire('onUpdate');
}
onEnterFrame() {
var t = this.getTimer() - this._startTime;
if (this.state === PLAYING) {
this.setTime(t);
}
else if (this.state === REVERSING) {
this.setTime(this.duration - t);
}
}
pause() {
this.state = PAUSED;
this.fire('onPause');
}
getTimer() {
return new Date().getTime();
}
}
/**
* Tween constructor. Tweens enable you to animate a node between the current state and a new state.
* You can play, pause, reverse, seek, reset, and finish tweens. By default, tweens are animated using
* a linear easing. For more tweening options, check out {@link Konva.Easings}
* @constructor
* @memberof Konva
* @example
* // instantiate new tween which fully rotates a node in 1 second
* var tween = new Konva.Tween({
* // list of tween specific properties
* node: node,
* duration: 1,
* easing: Konva.Easings.EaseInOut,
* onUpdate: () => console.log('node attrs updated')
* onFinish: () => console.log('finished'),
* // set new values for any attributes of a passed node
* rotation: 360,
* fill: 'red'
* });
*
* // play tween
* tween.play();
*
* // pause tween
* tween.pause();
*/
class Tween {
constructor(config) {
var that = this, node = config.node, nodeId = node._id, duration, easing = config.easing || Easings.Linear, yoyo = !!config.yoyo, key;
if (typeof config.duration === 'undefined') {
duration = 0.3;
}
else if (config.duration === 0) {
// zero is bad value for duration
duration = 0.001;
}
else {
duration = config.duration;
}
this.node = node;
this._id = idCounter++;
var layers = node.getLayer() ||
(node instanceof Konva$2['Stage'] ? node.getLayers() : null);
if (!layers) {
Util.error('Tween constructor have `node` that is not in a layer. Please add node into layer first.');
}
this.anim = new Animation(function () {
that.tween.onEnterFrame();
}, layers);
this.tween = new TweenEngine(key, function (i) {
that._tweenFunc(i);
}, easing, 0, 1, duration * 1000, yoyo);
this._addListeners();
// init attrs map
if (!Tween.attrs[nodeId]) {
Tween.attrs[nodeId] = {};
}
if (!Tween.attrs[nodeId][this._id]) {
Tween.attrs[nodeId][this._id] = {};
}
// init tweens map
if (!Tween.tweens[nodeId]) {
Tween.tweens[nodeId] = {};
}
for (key in config) {
if (blacklist[key] === undefined) {
this._addAttr(key, config[key]);
}
}
this.reset();
// callbacks
this.onFinish = config.onFinish;
this.onReset = config.onReset;
this.onUpdate = config.onUpdate;
}
_addAttr(key, end) {
var node = this.node, nodeId = node._id, start, diff, tweenId, n, len, trueEnd, trueStart, endRGBA;
// remove conflict from tween map if it exists
tweenId = Tween.tweens[nodeId][key];
if (tweenId) {
delete Tween.attrs[nodeId][tweenId][key];
}
// add to tween map
start = node.getAttr(key);
if (Util._isArray(end)) {
diff = [];
len = Math.max(end.length, start.length);
if (key === 'points' && end.length !== start.length) {
// before tweening points we need to make sure that start.length === end.length
// Util._prepareArrayForTween thinking that end.length > start.length
if (end.length > start.length) {
// so in this case we will increase number of starting points
trueStart = start;
start = Util._prepareArrayForTween(start, end, node.closed());
}
else {
// in this case we will increase number of eding points
trueEnd = end;
end = Util._prepareArrayForTween(end, start, node.closed());
}
}
if (key.indexOf('fill') === 0) {
for (n = 0; n < len; n++) {
if (n % 2 === 0) {
diff.push(end[n] - start[n]);
}
else {
var startRGBA = Util.colorToRGBA(start[n]);
endRGBA = Util.colorToRGBA(end[n]);
start[n] = startRGBA;
diff.push({
r: endRGBA.r - startRGBA.r,
g: endRGBA.g - startRGBA.g,
b: endRGBA.b - startRGBA.b,
a: endRGBA.a - startRGBA.a,
});
}
}
}
else {
for (n = 0; n < len; n++) {
diff.push(end[n] - start[n]);
}
}
}
else if (colorAttrs.indexOf(key) !== -1) {
start = Util.colorToRGBA(start);
endRGBA = Util.colorToRGBA(end);
diff = {
r: endRGBA.r - start.r,
g: endRGBA.g - start.g,
b: endRGBA.b - start.b,
a: endRGBA.a - start.a,
};
}
else {
diff = end - start;
}
Tween.attrs[nodeId][this._id][key] = {
start: start,
diff: diff,
end: end,
trueEnd: trueEnd,
trueStart: trueStart,
};
Tween.tweens[nodeId][key] = this._id;
}
_tweenFunc(i) {
var node = this.node, attrs = Tween.attrs[node._id][this._id], key, attr, start, diff, newVal, n, len, end;
for (key in attrs) {
attr = attrs[key];
start = attr.start;
diff = attr.diff;
end = attr.end;
if (Util._isArray(start)) {
newVal = [];
len = Math.max(start.length, end.length);
if (key.indexOf('fill') === 0) {
for (n = 0; n < len; n++) {
if (n % 2 === 0) {
newVal.push((start[n] || 0) + diff[n] * i);
}
else {
newVal.push('rgba(' +
Math.round(start[n].r + diff[n].r * i) +
',' +
Math.round(start[n].g + diff[n].g * i) +
',' +
Math.round(start[n].b + diff[n].b * i) +
',' +
(start[n].a + diff[n].a * i) +
')');
}
}
}
else {
for (n = 0; n < len; n++) {
newVal.push((start[n] || 0) + diff[n] * i);
}
}
}
else if (colorAttrs.indexOf(key) !== -1) {
newVal =
'rgba(' +
Math.round(start.r + diff.r * i) +
',' +
Math.round(start.g + diff.g * i) +
',' +
Math.round(start.b + diff.b * i) +
',' +
(start.a + diff.a * i) +
')';
}
else {
newVal = start + diff * i;
}
node.setAttr(key, newVal);
}
}
_addListeners() {
// start listeners
this.tween.onPlay = () => {
this.anim.start();
};
this.tween.onReverse = () => {
this.anim.start();
};
// stop listeners
this.tween.onPause = () => {
this.anim.stop();
};
this.tween.onFinish = () => {
var node = this.node;
// after tweening points of line we need to set original end
var attrs = Tween.attrs[node._id][this._id];
if (attrs.points && attrs.points.trueEnd) {
node.setAttr('points', attrs.points.trueEnd);
}
if (this.onFinish) {
this.onFinish.call(this);
}
};
this.tween.onReset = () => {
var node = this.node;
// after tweening points of line we need to set original start
var attrs = Tween.attrs[node._id][this._id];
if (attrs.points && attrs.points.trueStart) {
node.points(attrs.points.trueStart);
}
if (this.onReset) {
this.onReset();
}
};
this.tween.onUpdate = () => {
if (this.onUpdate) {
this.onUpdate.call(this);
}
};
}
/**
* play
* @method
* @name Konva.Tween#play
* @returns {Tween}
*/
play() {
this.tween.play();
return this;
}
/**
* reverse
* @method
* @name Konva.Tween#reverse
* @returns {Tween}
*/
reverse() {
this.tween.reverse();
return this;
}
/**
* reset
* @method
* @name Konva.Tween#reset
* @returns {Tween}
*/
reset() {
this.tween.reset();
return this;
}
/**
* seek
* @method
* @name Konva.Tween#seek(
* @param {Integer} t time in seconds between 0 and the duration
* @returns {Tween}
*/
seek(t) {
this.tween.seek(t * 1000);
return this;
}
/**
* pause
* @method
* @name Konva.Tween#pause
* @returns {Tween}
*/
pause() {
this.tween.pause();
return this;
}
/**
* finish
* @method
* @name Konva.Tween#finish
* @returns {Tween}
*/
finish() {
this.tween.finish();
return this;
}
/**
* destroy
* @method
* @name Konva.Tween#destroy
*/
destroy() {
var nodeId = this.node._id, thisId = this._id, attrs = Tween.tweens[nodeId], key;
this.pause();
for (key in attrs) {
delete Tween.tweens[nodeId][key];
}
delete Tween.attrs[nodeId][thisId];
}
}
Tween.attrs = {};
Tween.tweens = {};
/**
* Tween node properties. Shorter usage of {@link Konva.Tween} object.
*
* @method Konva.Node#to
* @param {Object} [params] tween params
* @example
*
* circle.to({
* x : 50,
* duration : 0.5,
* onUpdate: () => console.log('props updated'),
* onFinish: () => console.log('finished'),
* });
*/
Node.prototype.to = function (params) {
var onFinish = params.onFinish;
params.node = this;
params.onFinish = function () {
this.destroy();
if (onFinish) {
onFinish();
}
};
var tween = new Tween(params);
tween.play();
};
/*
* These eases were ported from an Adobe Flash tweening library to JavaScript
* by Xaric
*/
/**
* @namespace Easings
* @memberof Konva
*/
const Easings = {
/**
* back ease in
* @function
* @memberof Konva.Easings
*/
BackEaseIn(t, b, c, d) {
var s = 1.70158;
return c * (t /= d) * t * ((s + 1) * t - s) + b;
},
/**
* back ease out
* @function
* @memberof Konva.Easings
*/
BackEaseOut(t, b, c, d) {
var s = 1.70158;
return c * ((t = t / d - 1) * t * ((s + 1) * t + s) + 1) + b;
},
/**
* back ease in out
* @function
* @memberof Konva.Easings
*/
BackEaseInOut(t, b, c, d) {
var s = 1.70158;
if ((t /= d / 2) < 1) {
return (c / 2) * (t * t * (((s *= 1.525) + 1) * t - s)) + b;
}
return (c / 2) * ((t -= 2) * t * (((s *= 1.525) + 1) * t + s) + 2) + b;
},
/**
* elastic ease in
* @function
* @memberof Konva.Easings
*/
ElasticEaseIn(t, b, c, d, a, p) {
// added s = 0
var s = 0;
if (t === 0) {
return b;
}
if ((t /= d) === 1) {
return b + c;
}
if (!p) {
p = d * 0.3;
}
if (!a || a < Math.abs(c)) {
a = c;
s = p / 4;
}
else {
s = (p / (2 * Math.PI)) * Math.asin(c / a);
}
return (-(a *
Math.pow(2, 10 * (t -= 1)) *
Math.sin(((t * d - s) * (2 * Math.PI)) / p)) + b);
},
/**
* elastic ease out
* @function
* @memberof Konva.Easings
*/
ElasticEaseOut(t, b, c, d, a, p) {
// added s = 0
var s = 0;
if (t === 0) {
return b;
}
if ((t /= d) === 1) {
return b + c;
}
if (!p) {
p = d * 0.3;
}
if (!a || a < Math.abs(c)) {
a = c;
s = p / 4;
}
else {
s = (p / (2 * Math.PI)) * Math.asin(c / a);
}
return (a * Math.pow(2, -10 * t) * Math.sin(((t * d - s) * (2 * Math.PI)) / p) +
c +
b);
},
/**
* elastic ease in out
* @function
* @memberof Konva.Easings
*/
ElasticEaseInOut(t, b, c, d, a, p) {
// added s = 0
var s = 0;
if (t === 0) {
return b;
}
if ((t /= d / 2) === 2) {
return b + c;
}
if (!p) {
p = d * (0.3 * 1.5);
}
if (!a || a < Math.abs(c)) {
a = c;
s = p / 4;
}
else {
s = (p / (2 * Math.PI)) * Math.asin(c / a);
}
if (t < 1) {
return (-0.5 *
(a *
Math.pow(2, 10 * (t -= 1)) *
Math.sin(((t * d - s) * (2 * Math.PI)) / p)) +
b);
}
return (a *
Math.pow(2, -10 * (t -= 1)) *
Math.sin(((t * d - s) * (2 * Math.PI)) / p) *
0.5 +
c +
b);
},
/**
* bounce ease out
* @function
* @memberof Konva.Easings
*/
BounceEaseOut(t, b, c, d) {
if ((t /= d) < 1 / 2.75) {
return c * (7.5625 * t * t) + b;
}
else if (t < 2 / 2.75) {
return c * (7.5625 * (t -= 1.5 / 2.75) * t + 0.75) + b;
}
else if (t < 2.5 / 2.75) {
return c * (7.5625 * (t -= 2.25 / 2.75) * t + 0.9375) + b;
}
else {
return c * (7.5625 * (t -= 2.625 / 2.75) * t + 0.984375) + b;
}
},
/**
* bounce ease in
* @function
* @memberof Konva.Easings
*/
BounceEaseIn(t, b, c, d) {
return c - Easings.BounceEaseOut(d - t, 0, c, d) + b;
},
/**
* bounce ease in out
* @function
* @memberof Konva.Easings
*/
BounceEaseInOut(t, b, c, d) {
if (t < d / 2) {
return Easings.BounceEaseIn(t * 2, 0, c, d) * 0.5 + b;
}
else {
return Easings.BounceEaseOut(t * 2 - d, 0, c, d) * 0.5 + c * 0.5 + b;
}
},
/**
* ease in
* @function
* @memberof Konva.Easings
*/
EaseIn(t, b, c, d) {
return c * (t /= d) * t + b;
},
/**
* ease out
* @function
* @memberof Konva.Easings
*/
EaseOut(t, b, c, d) {
return -c * (t /= d) * (t - 2) + b;
},
/**
* ease in out
* @function
* @memberof Konva.Easings
*/
EaseInOut(t, b, c, d) {
if ((t /= d / 2) < 1) {
return (c / 2) * t * t + b;
}
return (-c / 2) * (--t * (t - 2) - 1) + b;
},
/**
* strong ease in
* @function
* @memberof Konva.Easings
*/
StrongEaseIn(t, b, c, d) {
return c * (t /= d) * t * t * t * t + b;
},
/**
* strong ease out
* @function
* @memberof Konva.Easings
*/
StrongEaseOut(t, b, c, d) {
return c * ((t = t / d - 1) * t * t * t * t + 1) + b;
},
/**
* strong ease in out
* @function
* @memberof Konva.Easings
*/
StrongEaseInOut(t, b, c, d) {
if ((t /= d / 2) < 1) {
return (c / 2) * t * t * t * t * t + b;
}
return (c / 2) * ((t -= 2) * t * t * t * t + 2) + b;
},
/**
* linear
* @function
* @memberof Konva.Easings
*/
Linear(t, b, c, d) {
return (c * t) / d + b;
},
};
// what is core parts of Konva?
const Konva$1 = Util._assign(Konva$2, {
Util,
Transform,
Node,
Container,
Stage,
stages,
Layer,
FastLayer,
Group,
DD,
Shape,
shapes,
Animation,
Tween,
Easings,
Context,
Canvas,
});
/**
* Arc constructor
* @constructor
* @memberof Konva
* @augments Konva.Shape
* @param {Object} config
* @param {Number} config.angle in degrees
* @param {Number} config.innerRadius
* @param {Number} config.outerRadius
* @param {Boolean} [config.clockwise]
* @param {String} [config.fill] fill color
* @param {Image} [config.fillPatternImage] fill pattern image
* @param {Number} [config.fillPatternX]
* @param {Number} [config.fillPatternY]
* @param {Object} [config.fillPatternOffset] object with x and y component
* @param {Number} [config.fillPatternOffsetX]
* @param {Number} [config.fillPatternOffsetY]
* @param {Object} [config.fillPatternScale] object with x and y component
* @param {Number} [config.fillPatternScaleX]
* @param {Number} [config.fillPatternScaleY]
* @param {Number} [config.fillPatternRotation]
* @param {String} [config.fillPatternRepeat] can be "repeat", "repeat-x", "repeat-y", or "no-repeat". The default is "no-repeat"
* @param {Object} [config.fillLinearGradientStartPoint] object with x and y component
* @param {Number} [config.fillLinearGradientStartPointX]
* @param {Number} [config.fillLinearGradientStartPointY]
* @param {Object} [config.fillLinearGradientEndPoint] object with x and y component
* @param {Number} [config.fillLinearGradientEndPointX]
* @param {Number} [config.fillLinearGradientEndPointY]
* @param {Array} [config.fillLinearGradientColorStops] array of color stops
* @param {Object} [config.fillRadialGradientStartPoint] object with x and y component
* @param {Number} [config.fillRadialGradientStartPointX]
* @param {Number} [config.fillRadialGradientStartPointY]
* @param {Object} [config.fillRadialGradientEndPoint] object with x and y component
* @param {Number} [config.fillRadialGradientEndPointX]
* @param {Number} [config.fillRadialGradientEndPointY]
* @param {Number} [config.fillRadialGradientStartRadius]
* @param {Number} [config.fillRadialGradientEndRadius]
* @param {Array} [config.fillRadialGradientColorStops] array of color stops
* @param {Boolean} [config.fillEnabled] flag which enables or disables the fill. The default value is true
* @param {String} [config.fillPriority] can be color, linear-gradient, radial-graident, or pattern. The default value is color. The fillPriority property makes it really easy to toggle between different fill types. For example, if you want to toggle between a fill color style and a fill pattern style, simply set the fill property and the fillPattern properties, and then use setFillPriority('color') to render the shape with a color fill, or use setFillPriority('pattern') to render the shape with the pattern fill configuration
* @param {String} [config.stroke] stroke color
* @param {Number} [config.strokeWidth] stroke width
* @param {Boolean} [config.fillAfterStrokeEnabled]. Should we draw fill AFTER stroke? Default is false.
* @param {Number} [config.hitStrokeWidth] size of the stroke on hit canvas. The default is "auto" - equals to strokeWidth
* @param {Boolean} [config.strokeHitEnabled] flag which enables or disables stroke hit region. The default is true
* @param {Boolean} [config.perfectDrawEnabled] flag which enables or disables using buffer canvas. The default is true
* @param {Boolean} [config.shadowForStrokeEnabled] flag which enables or disables shadow for stroke. The default is true
* @param {Boolean} [config.strokeScaleEnabled] flag which enables or disables stroke scale. The default is true
* @param {Boolean} [config.strokeEnabled] flag which enables or disables the stroke. The default value is true
* @param {String} [config.lineJoin] can be miter, round, or bevel. The default
* is miter
* @param {String} [config.lineCap] can be butt, round, or square. The default
* is butt
* @param {String} [config.shadowColor]
* @param {Number} [config.shadowBlur]
* @param {Object} [config.shadowOffset] object with x and y component
* @param {Number} [config.shadowOffsetX]
* @param {Number} [config.shadowOffsetY]
* @param {Number} [config.shadowOpacity] shadow opacity. Can be any real number
* between 0 and 1
* @param {Boolean} [config.shadowEnabled] flag which enables or disables the shadow. The default value is true
* @param {Array} [config.dash]
* @param {Boolean} [config.dashEnabled] flag which enables or disables the dashArray. The default value is true
* @param {Number} [config.x]
* @param {Number} [config.y]
* @param {Number} [config.width]
* @param {Number} [config.height]
* @param {Boolean} [config.visible]
* @param {Boolean} [config.listening] whether or not the node is listening for events
* @param {String} [config.id] unique id
* @param {String} [config.name] non-unique name
* @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1
* @param {Object} [config.scale] set scale
* @param {Number} [config.scaleX] set scale x
* @param {Number} [config.scaleY] set scale y
* @param {Number} [config.rotation] rotation in degrees
* @param {Object} [config.offset] offset from center point and rotation point
* @param {Number} [config.offsetX] set offset x
* @param {Number} [config.offsetY] set offset y
* @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop
* the entire stage by dragging any portion of the stage
* @param {Number} [config.dragDistance]
* @param {Function} [config.dragBoundFunc]
* @example
* // draw a Arc that's pointing downwards
* var arc = new Konva.Arc({
* innerRadius: 40,
* outerRadius: 80,
* fill: 'red',
* stroke: 'black'
* strokeWidth: 5,
* angle: 60,
* rotationDeg: -120
* });
*/
class Arc extends Shape {
_sceneFunc(context) {
var angle = Konva$2.getAngle(this.angle()), clockwise = this.clockwise();
context.beginPath();
context.arc(0, 0, this.outerRadius(), 0, angle, clockwise);
context.arc(0, 0, this.innerRadius(), angle, 0, !clockwise);
context.closePath();
context.fillStrokeShape(this);
}
getWidth() {
return this.outerRadius() * 2;
}
getHeight() {
return this.outerRadius() * 2;
}
setWidth(width) {
this.outerRadius(width / 2);
}
setHeight(height) {
this.outerRadius(height / 2);
}
getSelfRect() {
const radius = this.outerRadius();
const DEG_TO_RAD = Math.PI / 180;
const angle = this.angle() * DEG_TO_RAD;
const inc = 1 * DEG_TO_RAD;
let end = angle + inc;
if (this.clockwise()) {
end = 360;
}
const xs = [];
const ys = [];
for (let i = 0; i < end; i += inc) {
xs.push(Math.cos(i));
ys.push(Math.sin(i));
}
const minX = Math.round(radius * Math.min(...xs));
const maxX = Math.round(radius * Math.max(...xs));
const minY = Math.round(radius * Math.min(...ys));
const maxY = Math.round(radius * Math.max(...ys));
return {
x: minX || 0,
y: minY || 0,
width: maxX - minX,
height: maxY - minY
};
}
}
Arc.prototype._centroid = true;
Arc.prototype.className = 'Arc';
Arc.prototype._attrsAffectingSize = ['innerRadius', 'outerRadius'];
_registerNode(Arc);
// add getters setters
Factory.addGetterSetter(Arc, 'innerRadius', 0, getNumberValidator());
/**
* get/set innerRadius
* @name Konva.Arc#innerRadius
* @method
* @param {Number} innerRadius
* @returns {Number}
* @example
* // get inner radius
* var innerRadius = arc.innerRadius();
*
* // set inner radius
* arc.innerRadius(20);
*/
Factory.addGetterSetter(Arc, 'outerRadius', 0, getNumberValidator());
/**
* get/set outerRadius
* @name Konva.Arc#outerRadius
* @method
* @param {Number} outerRadius
* @returns {Number}
* @example
* // get outer radius
* var outerRadius = arc.outerRadius();
*
* // set outer radius
* arc.outerRadius(20);
*/
Factory.addGetterSetter(Arc, 'angle', 0, getNumberValidator());
/**
* get/set angle in degrees
* @name Konva.Arc#angle
* @method
* @param {Number} angle
* @returns {Number}
* @example
* // get angle
* var angle = arc.angle();
*
* // set angle
* arc.angle(20);
*/
Factory.addGetterSetter(Arc, 'clockwise', false, getBooleanValidator());
/**
* get/set clockwise flag
* @name Konva.Arc#clockwise
* @method
* @param {Boolean} clockwise
* @returns {Boolean}
* @example
* // get clockwise flag
* var clockwise = arc.clockwise();
*
* // draw arc counter-clockwise
* arc.clockwise(false);
*
* // draw arc clockwise
* arc.clockwise(true);
*/
function getControlPoints(x0, y0, x1, y1, x2, y2, t) {
var d01 = Math.sqrt(Math.pow(x1 - x0, 2) + Math.pow(y1 - y0, 2)), d12 = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2)), fa = (t * d01) / (d01 + d12), fb = (t * d12) / (d01 + d12), p1x = x1 - fa * (x2 - x0), p1y = y1 - fa * (y2 - y0), p2x = x1 + fb * (x2 - x0), p2y = y1 + fb * (y2 - y0);
return [p1x, p1y, p2x, p2y];
}
function expandPoints(p, tension) {
var len = p.length, allPoints = [], n, cp;
for (n = 2; n < len - 2; n += 2) {
cp = getControlPoints(p[n - 2], p[n - 1], p[n], p[n + 1], p[n + 2], p[n + 3], tension);
if (isNaN(cp[0])) {
continue;
}
allPoints.push(cp[0]);
allPoints.push(cp[1]);
allPoints.push(p[n]);
allPoints.push(p[n + 1]);
allPoints.push(cp[2]);
allPoints.push(cp[3]);
}
return allPoints;
}
/**
* Line constructor. Lines are defined by an array of points and
* a tension
* @constructor
* @memberof Konva
* @augments Konva.Shape
* @param {Object} config
* @param {Array} config.points Flat array of points coordinates. You should define them as [x1, y1, x2, y2, x3, y3].
* @param {Number} [config.tension] Higher values will result in a more curvy line. A value of 0 will result in no interpolation.
* The default is 0
* @param {Boolean} [config.closed] defines whether or not the line shape is closed, creating a polygon or blob
* @param {Boolean} [config.bezier] if no tension is provided but bezier=true, we draw the line as a bezier using the passed points
* @param {String} [config.fill] fill color
* @param {Image} [config.fillPatternImage] fill pattern image
* @param {Number} [config.fillPatternX]
* @param {Number} [config.fillPatternY]
* @param {Object} [config.fillPatternOffset] object with x and y component
* @param {Number} [config.fillPatternOffsetX]
* @param {Number} [config.fillPatternOffsetY]
* @param {Object} [config.fillPatternScale] object with x and y component
* @param {Number} [config.fillPatternScaleX]
* @param {Number} [config.fillPatternScaleY]
* @param {Number} [config.fillPatternRotation]
* @param {String} [config.fillPatternRepeat] can be "repeat", "repeat-x", "repeat-y", or "no-repeat". The default is "no-repeat"
* @param {Object} [config.fillLinearGradientStartPoint] object with x and y component
* @param {Number} [config.fillLinearGradientStartPointX]
* @param {Number} [config.fillLinearGradientStartPointY]
* @param {Object} [config.fillLinearGradientEndPoint] object with x and y component
* @param {Number} [config.fillLinearGradientEndPointX]
* @param {Number} [config.fillLinearGradientEndPointY]
* @param {Array} [config.fillLinearGradientColorStops] array of color stops
* @param {Object} [config.fillRadialGradientStartPoint] object with x and y component
* @param {Number} [config.fillRadialGradientStartPointX]
* @param {Number} [config.fillRadialGradientStartPointY]
* @param {Object} [config.fillRadialGradientEndPoint] object with x and y component
* @param {Number} [config.fillRadialGradientEndPointX]
* @param {Number} [config.fillRadialGradientEndPointY]
* @param {Number} [config.fillRadialGradientStartRadius]
* @param {Number} [config.fillRadialGradientEndRadius]
* @param {Array} [config.fillRadialGradientColorStops] array of color stops
* @param {Boolean} [config.fillEnabled] flag which enables or disables the fill. The default value is true
* @param {String} [config.fillPriority] can be color, linear-gradient, radial-graident, or pattern. The default value is color. The fillPriority property makes it really easy to toggle between different fill types. For example, if you want to toggle between a fill color style and a fill pattern style, simply set the fill property and the fillPattern properties, and then use setFillPriority('color') to render the shape with a color fill, or use setFillPriority('pattern') to render the shape with the pattern fill configuration
* @param {String} [config.stroke] stroke color
* @param {Number} [config.strokeWidth] stroke width
* @param {Boolean} [config.fillAfterStrokeEnabled]. Should we draw fill AFTER stroke? Default is false.
* @param {Number} [config.hitStrokeWidth] size of the stroke on hit canvas. The default is "auto" - equals to strokeWidth
* @param {Boolean} [config.strokeHitEnabled] flag which enables or disables stroke hit region. The default is true
* @param {Boolean} [config.perfectDrawEnabled] flag which enables or disables using buffer canvas. The default is true
* @param {Boolean} [config.shadowForStrokeEnabled] flag which enables or disables shadow for stroke. The default is true
* @param {Boolean} [config.strokeScaleEnabled] flag which enables or disables stroke scale. The default is true
* @param {Boolean} [config.strokeEnabled] flag which enables or disables the stroke. The default value is true
* @param {String} [config.lineJoin] can be miter, round, or bevel. The default
* is miter
* @param {String} [config.lineCap] can be butt, round, or square. The default
* is butt
* @param {String} [config.shadowColor]
* @param {Number} [config.shadowBlur]
* @param {Object} [config.shadowOffset] object with x and y component
* @param {Number} [config.shadowOffsetX]
* @param {Number} [config.shadowOffsetY]
* @param {Number} [config.shadowOpacity] shadow opacity. Can be any real number
* between 0 and 1
* @param {Boolean} [config.shadowEnabled] flag which enables or disables the shadow. The default value is true
* @param {Array} [config.dash]
* @param {Boolean} [config.dashEnabled] flag which enables or disables the dashArray. The default value is true
* @param {Number} [config.x]
* @param {Number} [config.y]
* @param {Number} [config.width]
* @param {Number} [config.height]
* @param {Boolean} [config.visible]
* @param {Boolean} [config.listening] whether or not the node is listening for events
* @param {String} [config.id] unique id
* @param {String} [config.name] non-unique name
* @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1
* @param {Object} [config.scale] set scale
* @param {Number} [config.scaleX] set scale x
* @param {Number} [config.scaleY] set scale y
* @param {Number} [config.rotation] rotation in degrees
* @param {Object} [config.offset] offset from center point and rotation point
* @param {Number} [config.offsetX] set offset x
* @param {Number} [config.offsetY] set offset y
* @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop
* the entire stage by dragging any portion of the stage
* @param {Number} [config.dragDistance]
* @param {Function} [config.dragBoundFunc]
* @example
* var line = new Konva.Line({
* x: 100,
* y: 50,
* points: [73, 70, 340, 23, 450, 60, 500, 20],
* stroke: 'red',
* tension: 1
* });
*/
class Line extends Shape {
constructor(config) {
super(config);
this.on('pointsChange.konva tensionChange.konva closedChange.konva bezierChange.konva', function () {
this._clearCache('tensionPoints');
});
}
_sceneFunc(context) {
var points = this.points(), length = points.length, tension = this.tension(), closed = this.closed(), bezier = this.bezier(), tp, len, n;
if (!length) {
return;
}
context.beginPath();
context.moveTo(points[0], points[1]);
// tension
if (tension !== 0 && length > 4) {
tp = this.getTensionPoints();
len = tp.length;
n = closed ? 0 : 4;
if (!closed) {
context.quadraticCurveTo(tp[0], tp[1], tp[2], tp[3]);
}
while (n < len - 2) {
context.bezierCurveTo(tp[n++], tp[n++], tp[n++], tp[n++], tp[n++], tp[n++]);
}
if (!closed) {
context.quadraticCurveTo(tp[len - 2], tp[len - 1], points[length - 2], points[length - 1]);
}
}
else if (bezier) {
// no tension but bezier
n = 2;
while (n < length) {
context.bezierCurveTo(points[n++], points[n++], points[n++], points[n++], points[n++], points[n++]);
}
}
else {
// no tension
for (n = 2; n < length; n += 2) {
context.lineTo(points[n], points[n + 1]);
}
}
// closed e.g. polygons and blobs
if (closed) {
context.closePath();
context.fillStrokeShape(this);
}
else {
// open e.g. lines and splines
context.strokeShape(this);
}
}
getTensionPoints() {
return this._getCache('tensionPoints', this._getTensionPoints);
}
_getTensionPoints() {
if (this.closed()) {
return this._getTensionPointsClosed();
}
else {
return expandPoints(this.points(), this.tension());
}
}
_getTensionPointsClosed() {
var p = this.points(), len = p.length, tension = this.tension(), firstControlPoints = getControlPoints(p[len - 2], p[len - 1], p[0], p[1], p[2], p[3], tension), lastControlPoints = getControlPoints(p[len - 4], p[len - 3], p[len - 2], p[len - 1], p[0], p[1], tension), middle = expandPoints(p, tension), tp = [firstControlPoints[2], firstControlPoints[3]]
.concat(middle)
.concat([
lastControlPoints[0],
lastControlPoints[1],
p[len - 2],
p[len - 1],
lastControlPoints[2],
lastControlPoints[3],
firstControlPoints[0],
firstControlPoints[1],
p[0],
p[1],
]);
return tp;
}
getWidth() {
return this.getSelfRect().width;
}
getHeight() {
return this.getSelfRect().height;
}
// overload size detection
getSelfRect() {
var points = this.points();
if (points.length < 4) {
return {
x: points[0] || 0,
y: points[1] || 0,
width: 0,
height: 0,
};
}
if (this.tension() !== 0) {
points = [
points[0],
points[1],
...this._getTensionPoints(),
points[points.length - 2],
points[points.length - 1],
];
}
else {
points = this.points();
}
var minX = points[0];
var maxX = points[0];
var minY = points[1];
var maxY = points[1];
var x, y;
for (var i = 0; i < points.length / 2; i++) {
x = points[i * 2];
y = points[i * 2 + 1];
minX = Math.min(minX, x);
maxX = Math.max(maxX, x);
minY = Math.min(minY, y);
maxY = Math.max(maxY, y);
}
return {
x: minX,
y: minY,
width: maxX - minX,
height: maxY - minY,
};
}
}
Line.prototype.className = 'Line';
Line.prototype._attrsAffectingSize = ['points', 'bezier', 'tension'];
_registerNode(Line);
// add getters setters
Factory.addGetterSetter(Line, 'closed', false);
/**
* get/set closed flag. The default is false
* @name Konva.Line#closed
* @method
* @param {Boolean} closed
* @returns {Boolean}
* @example
* // get closed flag
* var closed = line.closed();
*
* // close the shape
* line.closed(true);
*
* // open the shape
* line.closed(false);
*/
Factory.addGetterSetter(Line, 'bezier', false);
/**
* get/set bezier flag. The default is false
* @name Konva.Line#bezier
* @method
* @param {Boolean} bezier
* @returns {Boolean}
* @example
* // get whether the line is a bezier
* var isBezier = line.bezier();
*
* // set whether the line is a bezier
* line.bezier(true);
*/
Factory.addGetterSetter(Line, 'tension', 0, getNumberValidator());
/**
* get/set tension
* @name Konva.Line#tension
* @method
* @param {Number} tension Higher values will result in a more curvy line. A value of 0 will result in no interpolation. The default is 0
* @returns {Number}
* @example
* // get tension
* var tension = line.tension();
*
* // set tension
* line.tension(3);
*/
Factory.addGetterSetter(Line, 'points', [], getNumberArrayValidator());
/**
* get/set points array. Points is a flat array [x1, y1, x2, y2]. It is flat for performance reasons.
* @name Konva.Line#points
* @method
* @param {Array} points
* @returns {Array}
* @example
* // get points
* var points = line.points();
*
* // set points
* line.points([10, 20, 30, 40, 50, 60]);
*
* // push a new point
* line.points(line.points().concat([70, 80]));
*/
/**
* Path constructor.
* @author Jason Follas
* @constructor
* @memberof Konva
* @augments Konva.Shape
* @param {Object} config
* @param {String} config.data SVG data string
* @param {String} [config.fill] fill color
* @param {Image} [config.fillPatternImage] fill pattern image
* @param {Number} [config.fillPatternX]
* @param {Number} [config.fillPatternY]
* @param {Object} [config.fillPatternOffset] object with x and y component
* @param {Number} [config.fillPatternOffsetX]
* @param {Number} [config.fillPatternOffsetY]
* @param {Object} [config.fillPatternScale] object with x and y component
* @param {Number} [config.fillPatternScaleX]
* @param {Number} [config.fillPatternScaleY]
* @param {Number} [config.fillPatternRotation]
* @param {String} [config.fillPatternRepeat] can be "repeat", "repeat-x", "repeat-y", or "no-repeat". The default is "no-repeat"
* @param {Object} [config.fillLinearGradientStartPoint] object with x and y component
* @param {Number} [config.fillLinearGradientStartPointX]
* @param {Number} [config.fillLinearGradientStartPointY]
* @param {Object} [config.fillLinearGradientEndPoint] object with x and y component
* @param {Number} [config.fillLinearGradientEndPointX]
* @param {Number} [config.fillLinearGradientEndPointY]
* @param {Array} [config.fillLinearGradientColorStops] array of color stops
* @param {Object} [config.fillRadialGradientStartPoint] object with x and y component
* @param {Number} [config.fillRadialGradientStartPointX]
* @param {Number} [config.fillRadialGradientStartPointY]
* @param {Object} [config.fillRadialGradientEndPoint] object with x and y component
* @param {Number} [config.fillRadialGradientEndPointX]
* @param {Number} [config.fillRadialGradientEndPointY]
* @param {Number} [config.fillRadialGradientStartRadius]
* @param {Number} [config.fillRadialGradientEndRadius]
* @param {Array} [config.fillRadialGradientColorStops] array of color stops
* @param {Boolean} [config.fillEnabled] flag which enables or disables the fill. The default value is true
* @param {String} [config.fillPriority] can be color, linear-gradient, radial-graident, or pattern. The default value is color. The fillPriority property makes it really easy to toggle between different fill types. For example, if you want to toggle between a fill color style and a fill pattern style, simply set the fill property and the fillPattern properties, and then use setFillPriority('color') to render the shape with a color fill, or use setFillPriority('pattern') to render the shape with the pattern fill configuration
* @param {String} [config.stroke] stroke color
* @param {Number} [config.strokeWidth] stroke width
* @param {Boolean} [config.fillAfterStrokeEnabled]. Should we draw fill AFTER stroke? Default is false.
* @param {Number} [config.hitStrokeWidth] size of the stroke on hit canvas. The default is "auto" - equals to strokeWidth
* @param {Boolean} [config.strokeHitEnabled] flag which enables or disables stroke hit region. The default is true
* @param {Boolean} [config.perfectDrawEnabled] flag which enables or disables using buffer canvas. The default is true
* @param {Boolean} [config.shadowForStrokeEnabled] flag which enables or disables shadow for stroke. The default is true
* @param {Boolean} [config.strokeScaleEnabled] flag which enables or disables stroke scale. The default is true
* @param {Boolean} [config.strokeEnabled] flag which enables or disables the stroke. The default value is true
* @param {String} [config.lineJoin] can be miter, round, or bevel. The default
* is miter
* @param {String} [config.lineCap] can be butt, round, or square. The default
* is butt
* @param {String} [config.shadowColor]
* @param {Number} [config.shadowBlur]
* @param {Object} [config.shadowOffset] object with x and y component
* @param {Number} [config.shadowOffsetX]
* @param {Number} [config.shadowOffsetY]
* @param {Number} [config.shadowOpacity] shadow opacity. Can be any real number
* between 0 and 1
* @param {Boolean} [config.shadowEnabled] flag which enables or disables the shadow. The default value is true
* @param {Array} [config.dash]
* @param {Boolean} [config.dashEnabled] flag which enables or disables the dashArray. The default value is true
* @param {Number} [config.x]
* @param {Number} [config.y]
* @param {Number} [config.width]
* @param {Number} [config.height]
* @param {Boolean} [config.visible]
* @param {Boolean} [config.listening] whether or not the node is listening for events
* @param {String} [config.id] unique id
* @param {String} [config.name] non-unique name
* @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1
* @param {Object} [config.scale] set scale
* @param {Number} [config.scaleX] set scale x
* @param {Number} [config.scaleY] set scale y
* @param {Number} [config.rotation] rotation in degrees
* @param {Object} [config.offset] offset from center point and rotation point
* @param {Number} [config.offsetX] set offset x
* @param {Number} [config.offsetY] set offset y
* @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop
* the entire stage by dragging any portion of the stage
* @param {Number} [config.dragDistance]
* @param {Function} [config.dragBoundFunc]
* @example
* var path = new Konva.Path({
* x: 240,
* y: 40,
* data: 'M12.582,9.551C3.251,16.237,0.921,29.021,7.08,38.564l-2.36,1.689l4.893,2.262l4.893,2.262l-0.568-5.36l-0.567-5.359l-2.365,1.694c-4.657-7.375-2.83-17.185,4.352-22.33c7.451-5.338,17.817-3.625,23.156,3.824c5.337,7.449,3.625,17.813-3.821,23.152l2.857,3.988c9.617-6.893,11.827-20.277,4.935-29.896C35.591,4.87,22.204,2.658,12.582,9.551z',
* fill: 'green',
* scaleX: 2,
* scaleY: 2
* });
*/
class Path extends Shape {
constructor(config) {
super(config);
this.dataArray = [];
this.pathLength = 0;
this.dataArray = Path.parsePathData(this.data());
this.pathLength = 0;
for (var i = 0; i < this.dataArray.length; ++i) {
this.pathLength += this.dataArray[i].pathLength;
}
this.on('dataChange.konva', function () {
this.dataArray = Path.parsePathData(this.data());
this.pathLength = 0;
for (var i = 0; i < this.dataArray.length; ++i) {
this.pathLength += this.dataArray[i].pathLength;
}
});
}
_sceneFunc(context) {
var ca = this.dataArray;
// context position
context.beginPath();
var isClosed = false;
for (var n = 0; n < ca.length; n++) {
var c = ca[n].command;
var p = ca[n].points;
switch (c) {
case 'L':
context.lineTo(p[0], p[1]);
break;
case 'M':
context.moveTo(p[0], p[1]);
break;
case 'C':
context.bezierCurveTo(p[0], p[1], p[2], p[3], p[4], p[5]);
break;
case 'Q':
context.quadraticCurveTo(p[0], p[1], p[2], p[3]);
break;
case 'A':
var cx = p[0], cy = p[1], rx = p[2], ry = p[3], theta = p[4], dTheta = p[5], psi = p[6], fs = p[7];
var r = rx > ry ? rx : ry;
var scaleX = rx > ry ? 1 : rx / ry;
var scaleY = rx > ry ? ry / rx : 1;
context.translate(cx, cy);
context.rotate(psi);
context.scale(scaleX, scaleY);
context.arc(0, 0, r, theta, theta + dTheta, 1 - fs);
context.scale(1 / scaleX, 1 / scaleY);
context.rotate(-psi);
context.translate(-cx, -cy);
break;
case 'z':
isClosed = true;
context.closePath();
break;
}
}
if (!isClosed && !this.hasFill()) {
context.strokeShape(this);
}
else {
context.fillStrokeShape(this);
}
}
getSelfRect() {
var points = [];
this.dataArray.forEach(function (data) {
if (data.command === 'A') {
// Approximates by breaking curve into line segments
var start = data.points[4];
// 4 = theta
var dTheta = data.points[5];
// 5 = dTheta
var end = data.points[4] + dTheta;
var inc = Math.PI / 180.0;
// 1 degree resolution
if (Math.abs(start - end) < inc) {
inc = Math.abs(start - end);
}
if (dTheta < 0) {
// clockwise
for (let t = start - inc; t > end; t -= inc) {
const point = Path.getPointOnEllipticalArc(data.points[0], data.points[1], data.points[2], data.points[3], t, 0);
points.push(point.x, point.y);
}
}
else {
// counter-clockwise
for (let t = start + inc; t < end; t += inc) {
const point = Path.getPointOnEllipticalArc(data.points[0], data.points[1], data.points[2], data.points[3], t, 0);
points.push(point.x, point.y);
}
}
}
else if (data.command === 'C') {
// Approximates by breaking curve into 100 line segments
for (let t = 0.0; t <= 1; t += 0.01) {
const point = Path.getPointOnCubicBezier(t, data.start.x, data.start.y, data.points[0], data.points[1], data.points[2], data.points[3], data.points[4], data.points[5]);
points.push(point.x, point.y);
}
}
else {
// TODO: how can we calculate bezier curves better?
points = points.concat(data.points);
}
});
var minX = points[0];
var maxX = points[0];
var minY = points[1];
var maxY = points[1];
var x, y;
for (var i = 0; i < points.length / 2; i++) {
x = points[i * 2];
y = points[i * 2 + 1];
// skip bad values
if (!isNaN(x)) {
minX = Math.min(minX, x);
maxX = Math.max(maxX, x);
}
if (!isNaN(y)) {
minY = Math.min(minY, y);
maxY = Math.max(maxY, y);
}
}
return {
x: Math.round(minX),
y: Math.round(minY),
width: Math.round(maxX - minX),
height: Math.round(maxY - minY),
};
}
/**
* Return length of the path.
* @method
* @name Konva.Path#getLength
* @returns {Number} length
* @example
* var length = path.getLength();
*/
getLength() {
return this.pathLength;
}
/**
* Get point on path at specific length of the path
* @method
* @name Konva.Path#getPointAtLength
* @param {Number} length length
* @returns {Object} point {x,y} point
* @example
* var point = path.getPointAtLength(10);
*/
getPointAtLength(length) {
var point, i = 0, ii = this.dataArray.length;
if (!ii) {
return null;
}
while (i < ii && length > this.dataArray[i].pathLength) {
length -= this.dataArray[i].pathLength;
++i;
}
if (i === ii) {
point = this.dataArray[i - 1].points.slice(-2);
return {
x: point[0],
y: point[1],
};
}
if (length < 0.01) {
point = this.dataArray[i].points.slice(0, 2);
return {
x: point[0],
y: point[1],
};
}
var cp = this.dataArray[i];
var p = cp.points;
switch (cp.command) {
case 'L':
return Path.getPointOnLine(length, cp.start.x, cp.start.y, p[0], p[1]);
case 'C':
return Path.getPointOnCubicBezier(length / cp.pathLength, cp.start.x, cp.start.y, p[0], p[1], p[2], p[3], p[4], p[5]);
case 'Q':
return Path.getPointOnQuadraticBezier(length / cp.pathLength, cp.start.x, cp.start.y, p[0], p[1], p[2], p[3]);
case 'A':
var cx = p[0], cy = p[1], rx = p[2], ry = p[3], theta = p[4], dTheta = p[5], psi = p[6];
theta += (dTheta * length) / cp.pathLength;
return Path.getPointOnEllipticalArc(cx, cy, rx, ry, theta, psi);
}
return null;
}
static getLineLength(x1, y1, x2, y2) {
return Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
}
static getPointOnLine(dist, P1x, P1y, P2x, P2y, fromX, fromY) {
if (fromX === undefined) {
fromX = P1x;
}
if (fromY === undefined) {
fromY = P1y;
}
var m = (P2y - P1y) / (P2x - P1x + 0.00000001);
var run = Math.sqrt((dist * dist) / (1 + m * m));
if (P2x < P1x) {
run *= -1;
}
var rise = m * run;
var pt;
if (P2x === P1x) {
// vertical line
pt = {
x: fromX,
y: fromY + rise,
};
}
else if ((fromY - P1y) / (fromX - P1x + 0.00000001) === m) {
pt = {
x: fromX + run,
y: fromY + rise,
};
}
else {
var ix, iy;
var len = this.getLineLength(P1x, P1y, P2x, P2y);
// if (len < 0.00000001) {
// return {
// x: P1x,
// y: P1y,
// };
// }
var u = (fromX - P1x) * (P2x - P1x) + (fromY - P1y) * (P2y - P1y);
u = u / (len * len);
ix = P1x + u * (P2x - P1x);
iy = P1y + u * (P2y - P1y);
var pRise = this.getLineLength(fromX, fromY, ix, iy);
var pRun = Math.sqrt(dist * dist - pRise * pRise);
run = Math.sqrt((pRun * pRun) / (1 + m * m));
if (P2x < P1x) {
run *= -1;
}
rise = m * run;
pt = {
x: ix + run,
y: iy + rise,
};
}
return pt;
}
static getPointOnCubicBezier(pct, P1x, P1y, P2x, P2y, P3x, P3y, P4x, P4y) {
function CB1(t) {
return t * t * t;
}
function CB2(t) {
return 3 * t * t * (1 - t);
}
function CB3(t) {
return 3 * t * (1 - t) * (1 - t);
}
function CB4(t) {
return (1 - t) * (1 - t) * (1 - t);
}
var x = P4x * CB1(pct) + P3x * CB2(pct) + P2x * CB3(pct) + P1x * CB4(pct);
var y = P4y * CB1(pct) + P3y * CB2(pct) + P2y * CB3(pct) + P1y * CB4(pct);
return {
x: x,
y: y,
};
}
static getPointOnQuadraticBezier(pct, P1x, P1y, P2x, P2y, P3x, P3y) {
function QB1(t) {
return t * t;
}
function QB2(t) {
return 2 * t * (1 - t);
}
function QB3(t) {
return (1 - t) * (1 - t);
}
var x = P3x * QB1(pct) + P2x * QB2(pct) + P1x * QB3(pct);
var y = P3y * QB1(pct) + P2y * QB2(pct) + P1y * QB3(pct);
return {
x: x,
y: y,
};
}
static getPointOnEllipticalArc(cx, cy, rx, ry, theta, psi) {
var cosPsi = Math.cos(psi), sinPsi = Math.sin(psi);
var pt = {
x: rx * Math.cos(theta),
y: ry * Math.sin(theta),
};
return {
x: cx + (pt.x * cosPsi - pt.y * sinPsi),
y: cy + (pt.x * sinPsi + pt.y * cosPsi),
};
}
/*
* get parsed data array from the data
* string. V, v, H, h, and l data are converted to
* L data for the purpose of high performance Path
* rendering
*/
static parsePathData(data) {
// Path Data Segment must begin with a moveTo
//m (x y)+ Relative moveTo (subsequent points are treated as lineTo)
//M (x y)+ Absolute moveTo (subsequent points are treated as lineTo)
//l (x y)+ Relative lineTo
//L (x y)+ Absolute LineTo
//h (x)+ Relative horizontal lineTo
//H (x)+ Absolute horizontal lineTo
//v (y)+ Relative vertical lineTo
//V (y)+ Absolute vertical lineTo
//z (closepath)
//Z (closepath)
//c (x1 y1 x2 y2 x y)+ Relative Bezier curve
//C (x1 y1 x2 y2 x y)+ Absolute Bezier curve
//q (x1 y1 x y)+ Relative Quadratic Bezier
//Q (x1 y1 x y)+ Absolute Quadratic Bezier
//t (x y)+ Shorthand/Smooth Relative Quadratic Bezier
//T (x y)+ Shorthand/Smooth Absolute Quadratic Bezier
//s (x2 y2 x y)+ Shorthand/Smooth Relative Bezier curve
//S (x2 y2 x y)+ Shorthand/Smooth Absolute Bezier curve
//a (rx ry x-axis-rotation large-arc-flag sweep-flag x y)+ Relative Elliptical Arc
//A (rx ry x-axis-rotation large-arc-flag sweep-flag x y)+ Absolute Elliptical Arc
// return early if data is not defined
if (!data) {
return [];
}
// command string
var cs = data;
// command chars
var cc = [
'm',
'M',
'l',
'L',
'v',
'V',
'h',
'H',
'z',
'Z',
'c',
'C',
'q',
'Q',
't',
'T',
's',
'S',
'a',
'A',
];
// convert white spaces to commas
cs = cs.replace(new RegExp(' ', 'g'), ',');
// create pipes so that we can split the data
for (var n = 0; n < cc.length; n++) {
cs = cs.replace(new RegExp(cc[n], 'g'), '|' + cc[n]);
}
// create array
var arr = cs.split('|');
var ca = [];
var coords = [];
// init context point
var cpx = 0;
var cpy = 0;
var re = /([-+]?((\d+\.\d+)|((\d+)|(\.\d+)))(?:e[-+]?\d+)?)/gi;
var match;
for (n = 1; n < arr.length; n++) {
var str = arr[n];
var c = str.charAt(0);
str = str.slice(1);
coords.length = 0;
while ((match = re.exec(str))) {
coords.push(match[0]);
}
// while ((match = re.exec(str))) {
// coords.push(match[0]);
// }
var p = [];
for (var j = 0, jlen = coords.length; j < jlen; j++) {
// extra case for merged flags
if (coords[j] === '00') {
p.push(0, 0);
continue;
}
var parsed = parseFloat(coords[j]);
if (!isNaN(parsed)) {
p.push(parsed);
}
else {
p.push(0);
}
}
while (p.length > 0) {
if (isNaN(p[0])) {
// case for a trailing comma before next command
break;
}
var cmd = null;
var points = [];
var startX = cpx, startY = cpy;
// Move var from within the switch to up here (jshint)
var prevCmd, ctlPtx, ctlPty; // Ss, Tt
var rx, ry, psi, fa, fs, x1, y1; // Aa
// convert l, H, h, V, and v to L
switch (c) {
// Note: Keep the lineTo's above the moveTo's in this switch
case 'l':
cpx += p.shift();
cpy += p.shift();
cmd = 'L';
points.push(cpx, cpy);
break;
case 'L':
cpx = p.shift();
cpy = p.shift();
points.push(cpx, cpy);
break;
// Note: lineTo handlers need to be above this point
case 'm':
var dx = p.shift();
var dy = p.shift();
cpx += dx;
cpy += dy;
cmd = 'M';
// After closing the path move the current position
// to the the first point of the path (if any).
if (ca.length > 2 && ca[ca.length - 1].command === 'z') {
for (var idx = ca.length - 2; idx >= 0; idx--) {
if (ca[idx].command === 'M') {
cpx = ca[idx].points[0] + dx;
cpy = ca[idx].points[1] + dy;
break;
}
}
}
points.push(cpx, cpy);
c = 'l';
// subsequent points are treated as relative lineTo
break;
case 'M':
cpx = p.shift();
cpy = p.shift();
cmd = 'M';
points.push(cpx, cpy);
c = 'L';
// subsequent points are treated as absolute lineTo
break;
case 'h':
cpx += p.shift();
cmd = 'L';
points.push(cpx, cpy);
break;
case 'H':
cpx = p.shift();
cmd = 'L';
points.push(cpx, cpy);
break;
case 'v':
cpy += p.shift();
cmd = 'L';
points.push(cpx, cpy);
break;
case 'V':
cpy = p.shift();
cmd = 'L';
points.push(cpx, cpy);
break;
case 'C':
points.push(p.shift(), p.shift(), p.shift(), p.shift());
cpx = p.shift();
cpy = p.shift();
points.push(cpx, cpy);
break;
case 'c':
points.push(cpx + p.shift(), cpy + p.shift(), cpx + p.shift(), cpy + p.shift());
cpx += p.shift();
cpy += p.shift();
cmd = 'C';
points.push(cpx, cpy);
break;
case 'S':
ctlPtx = cpx;
ctlPty = cpy;
prevCmd = ca[ca.length - 1];
if (prevCmd.command === 'C') {
ctlPtx = cpx + (cpx - prevCmd.points[2]);
ctlPty = cpy + (cpy - prevCmd.points[3]);
}
points.push(ctlPtx, ctlPty, p.shift(), p.shift());
cpx = p.shift();
cpy = p.shift();
cmd = 'C';
points.push(cpx, cpy);
break;
case 's':
ctlPtx = cpx;
ctlPty = cpy;
prevCmd = ca[ca.length - 1];
if (prevCmd.command === 'C') {
ctlPtx = cpx + (cpx - prevCmd.points[2]);
ctlPty = cpy + (cpy - prevCmd.points[3]);
}
points.push(ctlPtx, ctlPty, cpx + p.shift(), cpy + p.shift());
cpx += p.shift();
cpy += p.shift();
cmd = 'C';
points.push(cpx, cpy);
break;
case 'Q':
points.push(p.shift(), p.shift());
cpx = p.shift();
cpy = p.shift();
points.push(cpx, cpy);
break;
case 'q':
points.push(cpx + p.shift(), cpy + p.shift());
cpx += p.shift();
cpy += p.shift();
cmd = 'Q';
points.push(cpx, cpy);
break;
case 'T':
ctlPtx = cpx;
ctlPty = cpy;
prevCmd = ca[ca.length - 1];
if (prevCmd.command === 'Q') {
ctlPtx = cpx + (cpx - prevCmd.points[0]);
ctlPty = cpy + (cpy - prevCmd.points[1]);
}
cpx = p.shift();
cpy = p.shift();
cmd = 'Q';
points.push(ctlPtx, ctlPty, cpx, cpy);
break;
case 't':
ctlPtx = cpx;
ctlPty = cpy;
prevCmd = ca[ca.length - 1];
if (prevCmd.command === 'Q') {
ctlPtx = cpx + (cpx - prevCmd.points[0]);
ctlPty = cpy + (cpy - prevCmd.points[1]);
}
cpx += p.shift();
cpy += p.shift();
cmd = 'Q';
points.push(ctlPtx, ctlPty, cpx, cpy);
break;
case 'A':
rx = p.shift();
ry = p.shift();
psi = p.shift();
fa = p.shift();
fs = p.shift();
x1 = cpx;
y1 = cpy;
cpx = p.shift();
cpy = p.shift();
cmd = 'A';
points = this.convertEndpointToCenterParameterization(x1, y1, cpx, cpy, fa, fs, rx, ry, psi);
break;
case 'a':
rx = p.shift();
ry = p.shift();
psi = p.shift();
fa = p.shift();
fs = p.shift();
x1 = cpx;
y1 = cpy;
cpx += p.shift();
cpy += p.shift();
cmd = 'A';
points = this.convertEndpointToCenterParameterization(x1, y1, cpx, cpy, fa, fs, rx, ry, psi);
break;
}
ca.push({
command: cmd || c,
points: points,
start: {
x: startX,
y: startY,
},
pathLength: this.calcLength(startX, startY, cmd || c, points),
});
}
if (c === 'z' || c === 'Z') {
ca.push({
command: 'z',
points: [],
start: undefined,
pathLength: 0,
});
}
}
return ca;
}
static calcLength(x, y, cmd, points) {
var len, p1, p2, t;
var path = Path;
switch (cmd) {
case 'L':
return path.getLineLength(x, y, points[0], points[1]);
case 'C':
// Approximates by breaking curve into 100 line segments
len = 0.0;
p1 = path.getPointOnCubicBezier(0, x, y, points[0], points[1], points[2], points[3], points[4], points[5]);
for (t = 0.01; t <= 1; t += 0.01) {
p2 = path.getPointOnCubicBezier(t, x, y, points[0], points[1], points[2], points[3], points[4], points[5]);
len += path.getLineLength(p1.x, p1.y, p2.x, p2.y);
p1 = p2;
}
return len;
case 'Q':
// Approximates by breaking curve into 100 line segments
len = 0.0;
p1 = path.getPointOnQuadraticBezier(0, x, y, points[0], points[1], points[2], points[3]);
for (t = 0.01; t <= 1; t += 0.01) {
p2 = path.getPointOnQuadraticBezier(t, x, y, points[0], points[1], points[2], points[3]);
len += path.getLineLength(p1.x, p1.y, p2.x, p2.y);
p1 = p2;
}
return len;
case 'A':
// Approximates by breaking curve into line segments
len = 0.0;
var start = points[4];
// 4 = theta
var dTheta = points[5];
// 5 = dTheta
var end = points[4] + dTheta;
var inc = Math.PI / 180.0;
// 1 degree resolution
if (Math.abs(start - end) < inc) {
inc = Math.abs(start - end);
}
// Note: for purpose of calculating arc length, not going to worry about rotating X-axis by angle psi
p1 = path.getPointOnEllipticalArc(points[0], points[1], points[2], points[3], start, 0);
if (dTheta < 0) {
// clockwise
for (t = start - inc; t > end; t -= inc) {
p2 = path.getPointOnEllipticalArc(points[0], points[1], points[2], points[3], t, 0);
len += path.getLineLength(p1.x, p1.y, p2.x, p2.y);
p1 = p2;
}
}
else {
// counter-clockwise
for (t = start + inc; t < end; t += inc) {
p2 = path.getPointOnEllipticalArc(points[0], points[1], points[2], points[3], t, 0);
len += path.getLineLength(p1.x, p1.y, p2.x, p2.y);
p1 = p2;
}
}
p2 = path.getPointOnEllipticalArc(points[0], points[1], points[2], points[3], end, 0);
len += path.getLineLength(p1.x, p1.y, p2.x, p2.y);
return len;
}
return 0;
}
static convertEndpointToCenterParameterization(x1, y1, x2, y2, fa, fs, rx, ry, psiDeg) {
// Derived from: http://www.w3.org/TR/SVG/implnote.html#ArcImplementationNotes
var psi = psiDeg * (Math.PI / 180.0);
var xp = (Math.cos(psi) * (x1 - x2)) / 2.0 + (Math.sin(psi) * (y1 - y2)) / 2.0;
var yp = (-1 * Math.sin(psi) * (x1 - x2)) / 2.0 +
(Math.cos(psi) * (y1 - y2)) / 2.0;
var lambda = (xp * xp) / (rx * rx) + (yp * yp) / (ry * ry);
if (lambda > 1) {
rx *= Math.sqrt(lambda);
ry *= Math.sqrt(lambda);
}
var f = Math.sqrt((rx * rx * (ry * ry) - rx * rx * (yp * yp) - ry * ry * (xp * xp)) /
(rx * rx * (yp * yp) + ry * ry * (xp * xp)));
if (fa === fs) {
f *= -1;
}
if (isNaN(f)) {
f = 0;
}
var cxp = (f * rx * yp) / ry;
var cyp = (f * -ry * xp) / rx;
var cx = (x1 + x2) / 2.0 + Math.cos(psi) * cxp - Math.sin(psi) * cyp;
var cy = (y1 + y2) / 2.0 + Math.sin(psi) * cxp + Math.cos(psi) * cyp;
var vMag = function (v) {
return Math.sqrt(v[0] * v[0] + v[1] * v[1]);
};
var vRatio = function (u, v) {
return (u[0] * v[0] + u[1] * v[1]) / (vMag(u) * vMag(v));
};
var vAngle = function (u, v) {
return (u[0] * v[1] < u[1] * v[0] ? -1 : 1) * Math.acos(vRatio(u, v));
};
var theta = vAngle([1, 0], [(xp - cxp) / rx, (yp - cyp) / ry]);
var u = [(xp - cxp) / rx, (yp - cyp) / ry];
var v = [(-1 * xp - cxp) / rx, (-1 * yp - cyp) / ry];
var dTheta = vAngle(u, v);
if (vRatio(u, v) <= -1) {
dTheta = Math.PI;
}
if (vRatio(u, v) >= 1) {
dTheta = 0;
}
if (fs === 0 && dTheta > 0) {
dTheta = dTheta - 2 * Math.PI;
}
if (fs === 1 && dTheta < 0) {
dTheta = dTheta + 2 * Math.PI;
}
return [cx, cy, rx, ry, theta, dTheta, psi, fs];
}
}
Path.prototype.className = 'Path';
Path.prototype._attrsAffectingSize = ['data'];
_registerNode(Path);
/**
* get/set SVG path data string. This method
* also automatically parses the data string
* into a data array. Currently supported SVG data:
* M, m, L, l, H, h, V, v, Q, q, T, t, C, c, S, s, A, a, Z, z
* @name Konva.Path#data
* @method
* @param {String} data svg path string
* @returns {String}
* @example
* // get data
* var data = path.data();
*
* // set data
* path.data('M200,100h100v50z');
*/
Factory.addGetterSetter(Path, 'data');
/**
* Arrow constructor
* @constructor
* @memberof Konva
* @augments Konva.Line
* @param {Object} config
* @param {Array} config.points Flat array of points coordinates. You should define them as [x1, y1, x2, y2, x3, y3].
* @param {Number} [config.tension] Higher values will result in a more curvy line. A value of 0 will result in no interpolation.
* The default is 0
* @param {Number} config.pointerLength Arrow pointer length. Default value is 10.
* @param {Number} config.pointerWidth Arrow pointer width. Default value is 10.
* @param {Boolean} config.pointerAtBeginning Do we need to draw pointer on beginning position?. Default false.
* @param {Boolean} config.pointerAtEnding Do we need to draw pointer on ending position?. Default true.
* @param {String} [config.fill] fill color
* @param {Image} [config.fillPatternImage] fill pattern image
* @param {Number} [config.fillPatternX]
* @param {Number} [config.fillPatternY]
* @param {Object} [config.fillPatternOffset] object with x and y component
* @param {Number} [config.fillPatternOffsetX]
* @param {Number} [config.fillPatternOffsetY]
* @param {Object} [config.fillPatternScale] object with x and y component
* @param {Number} [config.fillPatternScaleX]
* @param {Number} [config.fillPatternScaleY]
* @param {Number} [config.fillPatternRotation]
* @param {String} [config.fillPatternRepeat] can be "repeat", "repeat-x", "repeat-y", or "no-repeat". The default is "no-repeat"
* @param {Object} [config.fillLinearGradientStartPoint] object with x and y component
* @param {Number} [config.fillLinearGradientStartPointX]
* @param {Number} [config.fillLinearGradientStartPointY]
* @param {Object} [config.fillLinearGradientEndPoint] object with x and y component
* @param {Number} [config.fillLinearGradientEndPointX]
* @param {Number} [config.fillLinearGradientEndPointY]
* @param {Array} [config.fillLinearGradientColorStops] array of color stops
* @param {Object} [config.fillRadialGradientStartPoint] object with x and y component
* @param {Number} [config.fillRadialGradientStartPointX]
* @param {Number} [config.fillRadialGradientStartPointY]
* @param {Object} [config.fillRadialGradientEndPoint] object with x and y component
* @param {Number} [config.fillRadialGradientEndPointX]
* @param {Number} [config.fillRadialGradientEndPointY]
* @param {Number} [config.fillRadialGradientStartRadius]
* @param {Number} [config.fillRadialGradientEndRadius]
* @param {Array} [config.fillRadialGradientColorStops] array of color stops
* @param {Boolean} [config.fillEnabled] flag which enables or disables the fill. The default value is true
* @param {String} [config.fillPriority] can be color, linear-gradient, radial-graident, or pattern. The default value is color. The fillPriority property makes it really easy to toggle between different fill types. For example, if you want to toggle between a fill color style and a fill pattern style, simply set the fill property and the fillPattern properties, and then use setFillPriority('color') to render the shape with a color fill, or use setFillPriority('pattern') to render the shape with the pattern fill configuration
* @param {String} [config.stroke] stroke color
* @param {Number} [config.strokeWidth] stroke width
* @param {Boolean} [config.fillAfterStrokeEnabled]. Should we draw fill AFTER stroke? Default is false.
* @param {Number} [config.hitStrokeWidth] size of the stroke on hit canvas. The default is "auto" - equals to strokeWidth
* @param {Boolean} [config.strokeHitEnabled] flag which enables or disables stroke hit region. The default is true
* @param {Boolean} [config.perfectDrawEnabled] flag which enables or disables using buffer canvas. The default is true
* @param {Boolean} [config.shadowForStrokeEnabled] flag which enables or disables shadow for stroke. The default is true
* @param {Boolean} [config.strokeScaleEnabled] flag which enables or disables stroke scale. The default is true
* @param {Boolean} [config.strokeEnabled] flag which enables or disables the stroke. The default value is true
* @param {String} [config.lineJoin] can be miter, round, or bevel. The default
* is miter
* @param {String} [config.lineCap] can be butt, round, or square. The default
* is butt
* @param {String} [config.shadowColor]
* @param {Number} [config.shadowBlur]
* @param {Object} [config.shadowOffset] object with x and y component
* @param {Number} [config.shadowOffsetX]
* @param {Number} [config.shadowOffsetY]
* @param {Number} [config.shadowOpacity] shadow opacity. Can be any real number
* between 0 and 1
* @param {Boolean} [config.shadowEnabled] flag which enables or disables the shadow. The default value is true
* @param {Array} [config.dash]
* @param {Boolean} [config.dashEnabled] flag which enables or disables the dashArray. The default value is true
* @param {Number} [config.x]
* @param {Number} [config.y]
* @param {Number} [config.width]
* @param {Number} [config.height]
* @param {Boolean} [config.visible]
* @param {Boolean} [config.listening] whether or not the node is listening for events
* @param {String} [config.id] unique id
* @param {String} [config.name] non-unique name
* @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1
* @param {Object} [config.scale] set scale
* @param {Number} [config.scaleX] set scale x
* @param {Number} [config.scaleY] set scale y
* @param {Number} [config.rotation] rotation in degrees
* @param {Object} [config.offset] offset from center point and rotation point
* @param {Number} [config.offsetX] set offset x
* @param {Number} [config.offsetY] set offset y
* @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop
* the entire stage by dragging any portion of the stage
* @param {Number} [config.dragDistance]
* @param {Function} [config.dragBoundFunc]
* @example
* var line = new Konva.Line({
* points: [73, 70, 340, 23, 450, 60, 500, 20],
* stroke: 'red',
* tension: 1,
* pointerLength : 10,
* pointerWidth : 12
* });
*/
class Arrow extends Line {
_sceneFunc(ctx) {
super._sceneFunc(ctx);
var PI2 = Math.PI * 2;
var points = this.points();
var tp = points;
var fromTension = this.tension() !== 0 && points.length > 4;
if (fromTension) {
tp = this.getTensionPoints();
}
var length = this.pointerLength();
var n = points.length;
var dx, dy;
if (fromTension) {
const lp = [
tp[tp.length - 4],
tp[tp.length - 3],
tp[tp.length - 2],
tp[tp.length - 1],
points[n - 2],
points[n - 1],
];
const lastLength = Path.calcLength(tp[tp.length - 4], tp[tp.length - 3], 'C', lp);
const previous = Path.getPointOnQuadraticBezier(Math.min(1, 1 - length / lastLength), lp[0], lp[1], lp[2], lp[3], lp[4], lp[5]);
dx = points[n - 2] - previous.x;
dy = points[n - 1] - previous.y;
}
else {
dx = points[n - 2] - points[n - 4];
dy = points[n - 1] - points[n - 3];
}
var radians = (Math.atan2(dy, dx) + PI2) % PI2;
var width = this.pointerWidth();
if (this.pointerAtEnding()) {
ctx.save();
ctx.beginPath();
ctx.translate(points[n - 2], points[n - 1]);
ctx.rotate(radians);
ctx.moveTo(0, 0);
ctx.lineTo(-length, width / 2);
ctx.lineTo(-length, -width / 2);
ctx.closePath();
ctx.restore();
this.__fillStroke(ctx);
}
if (this.pointerAtBeginning()) {
ctx.save();
ctx.beginPath();
ctx.translate(points[0], points[1]);
if (fromTension) {
dx = (tp[0] + tp[2]) / 2 - points[0];
dy = (tp[1] + tp[3]) / 2 - points[1];
}
else {
dx = points[2] - points[0];
dy = points[3] - points[1];
}
ctx.rotate((Math.atan2(-dy, -dx) + PI2) % PI2);
ctx.moveTo(0, 0);
ctx.lineTo(-length, width / 2);
ctx.lineTo(-length, -width / 2);
ctx.closePath();
ctx.restore();
this.__fillStroke(ctx);
}
}
__fillStroke(ctx) {
// here is a tricky part
// we need to disable dash for arrow pointers
var isDashEnabled = this.dashEnabled();
if (isDashEnabled) {
// manually disable dash for head
// it is better not to use setter here,
// because it will trigger attr change event
this.attrs.dashEnabled = false;
ctx.setLineDash([]);
}
ctx.fillStrokeShape(this);
// restore old value
if (isDashEnabled) {
this.attrs.dashEnabled = true;
}
}
getSelfRect() {
const lineRect = super.getSelfRect();
const offset = this.pointerWidth() / 2;
return {
x: lineRect.x - offset,
y: lineRect.y - offset,
width: lineRect.width + offset * 2,
height: lineRect.height + offset * 2,
};
}
}
Arrow.prototype.className = 'Arrow';
_registerNode(Arrow);
/**
* get/set pointerLength
* @name Konva.Arrow#pointerLength
* @method
* @param {Number} Length of pointer of arrow. The default is 10.
* @returns {Number}
* @example
* // get length
* var pointerLength = line.pointerLength();
*
* // set length
* line.pointerLength(15);
*/
Factory.addGetterSetter(Arrow, 'pointerLength', 10, getNumberValidator());
/**
* get/set pointerWidth
* @name Konva.Arrow#pointerWidth
* @method
* @param {Number} Width of pointer of arrow.
* The default is 10.
* @returns {Number}
* @example
* // get width
* var pointerWidth = line.pointerWidth();
*
* // set width
* line.pointerWidth(15);
*/
Factory.addGetterSetter(Arrow, 'pointerWidth', 10, getNumberValidator());
/**
* get/set pointerAtBeginning
* @name Konva.Arrow#pointerAtBeginning
* @method
* @param {Number} Should pointer displayed at beginning of arrow. The default is false.
* @returns {Boolean}
* @example
* // get value
* var pointerAtBeginning = line.pointerAtBeginning();
*
* // set value
* line.pointerAtBeginning(true);
*/
Factory.addGetterSetter(Arrow, 'pointerAtBeginning', false);
/**
* get/set pointerAtEnding
* @name Konva.Arrow#pointerAtEnding
* @method
* @param {Number} Should pointer displayed at ending of arrow. The default is true.
* @returns {Boolean}
* @example
* // get value
* var pointerAtEnding = line.pointerAtEnding();
*
* // set value
* line.pointerAtEnding(false);
*/
Factory.addGetterSetter(Arrow, 'pointerAtEnding', true);
/**
* Circle constructor
* @constructor
* @memberof Konva
* @augments Konva.Shape
* @param {Object} config
* @param {Number} config.radius
* @param {String} [config.fill] fill color
* @param {Image} [config.fillPatternImage] fill pattern image
* @param {Number} [config.fillPatternX]
* @param {Number} [config.fillPatternY]
* @param {Object} [config.fillPatternOffset] object with x and y component
* @param {Number} [config.fillPatternOffsetX]
* @param {Number} [config.fillPatternOffsetY]
* @param {Object} [config.fillPatternScale] object with x and y component
* @param {Number} [config.fillPatternScaleX]
* @param {Number} [config.fillPatternScaleY]
* @param {Number} [config.fillPatternRotation]
* @param {String} [config.fillPatternRepeat] can be "repeat", "repeat-x", "repeat-y", or "no-repeat". The default is "no-repeat"
* @param {Object} [config.fillLinearGradientStartPoint] object with x and y component
* @param {Number} [config.fillLinearGradientStartPointX]
* @param {Number} [config.fillLinearGradientStartPointY]
* @param {Object} [config.fillLinearGradientEndPoint] object with x and y component
* @param {Number} [config.fillLinearGradientEndPointX]
* @param {Number} [config.fillLinearGradientEndPointY]
* @param {Array} [config.fillLinearGradientColorStops] array of color stops
* @param {Object} [config.fillRadialGradientStartPoint] object with x and y component
* @param {Number} [config.fillRadialGradientStartPointX]
* @param {Number} [config.fillRadialGradientStartPointY]
* @param {Object} [config.fillRadialGradientEndPoint] object with x and y component
* @param {Number} [config.fillRadialGradientEndPointX]
* @param {Number} [config.fillRadialGradientEndPointY]
* @param {Number} [config.fillRadialGradientStartRadius]
* @param {Number} [config.fillRadialGradientEndRadius]
* @param {Array} [config.fillRadialGradientColorStops] array of color stops
* @param {Boolean} [config.fillEnabled] flag which enables or disables the fill. The default value is true
* @param {String} [config.fillPriority] can be color, linear-gradient, radial-graident, or pattern. The default value is color. The fillPriority property makes it really easy to toggle between different fill types. For example, if you want to toggle between a fill color style and a fill pattern style, simply set the fill property and the fillPattern properties, and then use setFillPriority('color') to render the shape with a color fill, or use setFillPriority('pattern') to render the shape with the pattern fill configuration
* @param {String} [config.stroke] stroke color
* @param {Number} [config.strokeWidth] stroke width
* @param {Boolean} [config.fillAfterStrokeEnabled]. Should we draw fill AFTER stroke? Default is false.
* @param {Number} [config.hitStrokeWidth] size of the stroke on hit canvas. The default is "auto" - equals to strokeWidth
* @param {Boolean} [config.strokeHitEnabled] flag which enables or disables stroke hit region. The default is true
* @param {Boolean} [config.perfectDrawEnabled] flag which enables or disables using buffer canvas. The default is true
* @param {Boolean} [config.shadowForStrokeEnabled] flag which enables or disables shadow for stroke. The default is true
* @param {Boolean} [config.strokeScaleEnabled] flag which enables or disables stroke scale. The default is true
* @param {Boolean} [config.strokeEnabled] flag which enables or disables the stroke. The default value is true
* @param {String} [config.lineJoin] can be miter, round, or bevel. The default
* is miter
* @param {String} [config.lineCap] can be butt, round, or square. The default
* is butt
* @param {String} [config.shadowColor]
* @param {Number} [config.shadowBlur]
* @param {Object} [config.shadowOffset] object with x and y component
* @param {Number} [config.shadowOffsetX]
* @param {Number} [config.shadowOffsetY]
* @param {Number} [config.shadowOpacity] shadow opacity. Can be any real number
* between 0 and 1
* @param {Boolean} [config.shadowEnabled] flag which enables or disables the shadow. The default value is true
* @param {Array} [config.dash]
* @param {Boolean} [config.dashEnabled] flag which enables or disables the dashArray. The default value is true
* @param {Number} [config.x]
* @param {Number} [config.y]
* @param {Number} [config.width]
* @param {Number} [config.height]
* @param {Boolean} [config.visible]
* @param {Boolean} [config.listening] whether or not the node is listening for events
* @param {String} [config.id] unique id
* @param {String} [config.name] non-unique name
* @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1
* @param {Object} [config.scale] set scale
* @param {Number} [config.scaleX] set scale x
* @param {Number} [config.scaleY] set scale y
* @param {Number} [config.rotation] rotation in degrees
* @param {Object} [config.offset] offset from center point and rotation point
* @param {Number} [config.offsetX] set offset x
* @param {Number} [config.offsetY] set offset y
* @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop
* the entire stage by dragging any portion of the stage
* @param {Number} [config.dragDistance]
* @param {Function} [config.dragBoundFunc]
* @example
* // create circle
* var circle = new Konva.Circle({
* radius: 40,
* fill: 'red',
* stroke: 'black',
* strokeWidth: 5
* });
*/
class Circle extends Shape {
_sceneFunc(context) {
context.beginPath();
context.arc(0, 0, this.attrs.radius || 0, 0, Math.PI * 2, false);
context.closePath();
context.fillStrokeShape(this);
}
getWidth() {
return this.radius() * 2;
}
getHeight() {
return this.radius() * 2;
}
setWidth(width) {
if (this.radius() !== width / 2) {
this.radius(width / 2);
}
}
setHeight(height) {
if (this.radius() !== height / 2) {
this.radius(height / 2);
}
}
}
Circle.prototype._centroid = true;
Circle.prototype.className = 'Circle';
Circle.prototype._attrsAffectingSize = ['radius'];
_registerNode(Circle);
/**
* get/set radius
* @name Konva.Circle#radius
* @method
* @param {Number} radius
* @returns {Number}
* @example
* // get radius
* var radius = circle.radius();
*
* // set radius
* circle.radius(10);
*/
Factory.addGetterSetter(Circle, 'radius', 0, getNumberValidator());
/**
* Ellipse constructor
* @constructor
* @memberof Konva
* @augments Konva.Shape
* @param {Object} config
* @param {Object} config.radius defines x and y radius
* @param {String} [config.fill] fill color
* @param {Image} [config.fillPatternImage] fill pattern image
* @param {Number} [config.fillPatternX]
* @param {Number} [config.fillPatternY]
* @param {Object} [config.fillPatternOffset] object with x and y component
* @param {Number} [config.fillPatternOffsetX]
* @param {Number} [config.fillPatternOffsetY]
* @param {Object} [config.fillPatternScale] object with x and y component
* @param {Number} [config.fillPatternScaleX]
* @param {Number} [config.fillPatternScaleY]
* @param {Number} [config.fillPatternRotation]
* @param {String} [config.fillPatternRepeat] can be "repeat", "repeat-x", "repeat-y", or "no-repeat". The default is "no-repeat"
* @param {Object} [config.fillLinearGradientStartPoint] object with x and y component
* @param {Number} [config.fillLinearGradientStartPointX]
* @param {Number} [config.fillLinearGradientStartPointY]
* @param {Object} [config.fillLinearGradientEndPoint] object with x and y component
* @param {Number} [config.fillLinearGradientEndPointX]
* @param {Number} [config.fillLinearGradientEndPointY]
* @param {Array} [config.fillLinearGradientColorStops] array of color stops
* @param {Object} [config.fillRadialGradientStartPoint] object with x and y component
* @param {Number} [config.fillRadialGradientStartPointX]
* @param {Number} [config.fillRadialGradientStartPointY]
* @param {Object} [config.fillRadialGradientEndPoint] object with x and y component
* @param {Number} [config.fillRadialGradientEndPointX]
* @param {Number} [config.fillRadialGradientEndPointY]
* @param {Number} [config.fillRadialGradientStartRadius]
* @param {Number} [config.fillRadialGradientEndRadius]
* @param {Array} [config.fillRadialGradientColorStops] array of color stops
* @param {Boolean} [config.fillEnabled] flag which enables or disables the fill. The default value is true
* @param {String} [config.fillPriority] can be color, linear-gradient, radial-graident, or pattern. The default value is color. The fillPriority property makes it really easy to toggle between different fill types. For example, if you want to toggle between a fill color style and a fill pattern style, simply set the fill property and the fillPattern properties, and then use setFillPriority('color') to render the shape with a color fill, or use setFillPriority('pattern') to render the shape with the pattern fill configuration
* @param {String} [config.stroke] stroke color
* @param {Number} [config.strokeWidth] stroke width
* @param {Boolean} [config.fillAfterStrokeEnabled]. Should we draw fill AFTER stroke? Default is false.
* @param {Number} [config.hitStrokeWidth] size of the stroke on hit canvas. The default is "auto" - equals to strokeWidth
* @param {Boolean} [config.strokeHitEnabled] flag which enables or disables stroke hit region. The default is true
* @param {Boolean} [config.perfectDrawEnabled] flag which enables or disables using buffer canvas. The default is true
* @param {Boolean} [config.shadowForStrokeEnabled] flag which enables or disables shadow for stroke. The default is true
* @param {Boolean} [config.strokeScaleEnabled] flag which enables or disables stroke scale. The default is true
* @param {Boolean} [config.strokeEnabled] flag which enables or disables the stroke. The default value is true
* @param {String} [config.lineJoin] can be miter, round, or bevel. The default
* is miter
* @param {String} [config.lineCap] can be butt, round, or square. The default
* is butt
* @param {String} [config.shadowColor]
* @param {Number} [config.shadowBlur]
* @param {Object} [config.shadowOffset] object with x and y component
* @param {Number} [config.shadowOffsetX]
* @param {Number} [config.shadowOffsetY]
* @param {Number} [config.shadowOpacity] shadow opacity. Can be any real number
* between 0 and 1
* @param {Boolean} [config.shadowEnabled] flag which enables or disables the shadow. The default value is true
* @param {Array} [config.dash]
* @param {Boolean} [config.dashEnabled] flag which enables or disables the dashArray. The default value is true
* @param {Number} [config.x]
* @param {Number} [config.y]
* @param {Number} [config.width]
* @param {Number} [config.height]
* @param {Boolean} [config.visible]
* @param {Boolean} [config.listening] whether or not the node is listening for events
* @param {String} [config.id] unique id
* @param {String} [config.name] non-unique name
* @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1
* @param {Object} [config.scale] set scale
* @param {Number} [config.scaleX] set scale x
* @param {Number} [config.scaleY] set scale y
* @param {Number} [config.rotation] rotation in degrees
* @param {Object} [config.offset] offset from center point and rotation point
* @param {Number} [config.offsetX] set offset x
* @param {Number} [config.offsetY] set offset y
* @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop
* the entire stage by dragging any portion of the stage
* @param {Number} [config.dragDistance]
* @param {Function} [config.dragBoundFunc]
* @example
* var ellipse = new Konva.Ellipse({
* radius : {
* x : 50,
* y : 50
* },
* fill: 'red'
* });
*/
class Ellipse extends Shape {
_sceneFunc(context) {
var rx = this.radiusX(), ry = this.radiusY();
context.beginPath();
context.save();
if (rx !== ry) {
context.scale(1, ry / rx);
}
context.arc(0, 0, rx, 0, Math.PI * 2, false);
context.restore();
context.closePath();
context.fillStrokeShape(this);
}
getWidth() {
return this.radiusX() * 2;
}
getHeight() {
return this.radiusY() * 2;
}
setWidth(width) {
this.radiusX(width / 2);
}
setHeight(height) {
this.radiusY(height / 2);
}
}
Ellipse.prototype.className = 'Ellipse';
Ellipse.prototype._centroid = true;
Ellipse.prototype._attrsAffectingSize = ['radiusX', 'radiusY'];
_registerNode(Ellipse);
// add getters setters
Factory.addComponentsGetterSetter(Ellipse, 'radius', ['x', 'y']);
/**
* get/set radius
* @name Konva.Ellipse#radius
* @method
* @param {Object} radius
* @param {Number} radius.x
* @param {Number} radius.y
* @returns {Object}
* @example
* // get radius
* var radius = ellipse.radius();
*
* // set radius
* ellipse.radius({
* x: 200,
* y: 100
* });
*/
Factory.addGetterSetter(Ellipse, 'radiusX', 0, getNumberValidator());
/**
* get/set radius x
* @name Konva.Ellipse#radiusX
* @method
* @param {Number} x
* @returns {Number}
* @example
* // get radius x
* var radiusX = ellipse.radiusX();
*
* // set radius x
* ellipse.radiusX(200);
*/
Factory.addGetterSetter(Ellipse, 'radiusY', 0, getNumberValidator());
/**
* get/set radius y
* @name Konva.Ellipse#radiusY
* @method
* @param {Number} y
* @returns {Number}
* @example
* // get radius y
* var radiusY = ellipse.radiusY();
*
* // set radius y
* ellipse.radiusY(200);
*/
/**
* Image constructor
* @constructor
* @memberof Konva
* @augments Konva.Shape
* @param {Object} config
* @param {Image} config.image
* @param {Object} [config.crop]
* @param {String} [config.fill] fill color
* @param {Image} [config.fillPatternImage] fill pattern image
* @param {Number} [config.fillPatternX]
* @param {Number} [config.fillPatternY]
* @param {Object} [config.fillPatternOffset] object with x and y component
* @param {Number} [config.fillPatternOffsetX]
* @param {Number} [config.fillPatternOffsetY]
* @param {Object} [config.fillPatternScale] object with x and y component
* @param {Number} [config.fillPatternScaleX]
* @param {Number} [config.fillPatternScaleY]
* @param {Number} [config.fillPatternRotation]
* @param {String} [config.fillPatternRepeat] can be "repeat", "repeat-x", "repeat-y", or "no-repeat". The default is "no-repeat"
* @param {Object} [config.fillLinearGradientStartPoint] object with x and y component
* @param {Number} [config.fillLinearGradientStartPointX]
* @param {Number} [config.fillLinearGradientStartPointY]
* @param {Object} [config.fillLinearGradientEndPoint] object with x and y component
* @param {Number} [config.fillLinearGradientEndPointX]
* @param {Number} [config.fillLinearGradientEndPointY]
* @param {Array} [config.fillLinearGradientColorStops] array of color stops
* @param {Object} [config.fillRadialGradientStartPoint] object with x and y component
* @param {Number} [config.fillRadialGradientStartPointX]
* @param {Number} [config.fillRadialGradientStartPointY]
* @param {Object} [config.fillRadialGradientEndPoint] object with x and y component
* @param {Number} [config.fillRadialGradientEndPointX]
* @param {Number} [config.fillRadialGradientEndPointY]
* @param {Number} [config.fillRadialGradientStartRadius]
* @param {Number} [config.fillRadialGradientEndRadius]
* @param {Array} [config.fillRadialGradientColorStops] array of color stops
* @param {Boolean} [config.fillEnabled] flag which enables or disables the fill. The default value is true
* @param {String} [config.fillPriority] can be color, linear-gradient, radial-graident, or pattern. The default value is color. The fillPriority property makes it really easy to toggle between different fill types. For example, if you want to toggle between a fill color style and a fill pattern style, simply set the fill property and the fillPattern properties, and then use setFillPriority('color') to render the shape with a color fill, or use setFillPriority('pattern') to render the shape with the pattern fill configuration
* @param {String} [config.stroke] stroke color
* @param {Number} [config.strokeWidth] stroke width
* @param {Boolean} [config.fillAfterStrokeEnabled]. Should we draw fill AFTER stroke? Default is false.
* @param {Number} [config.hitStrokeWidth] size of the stroke on hit canvas. The default is "auto" - equals to strokeWidth
* @param {Boolean} [config.strokeHitEnabled] flag which enables or disables stroke hit region. The default is true
* @param {Boolean} [config.perfectDrawEnabled] flag which enables or disables using buffer canvas. The default is true
* @param {Boolean} [config.shadowForStrokeEnabled] flag which enables or disables shadow for stroke. The default is true
* @param {Boolean} [config.strokeScaleEnabled] flag which enables or disables stroke scale. The default is true
* @param {Boolean} [config.strokeEnabled] flag which enables or disables the stroke. The default value is true
* @param {String} [config.lineJoin] can be miter, round, or bevel. The default
* is miter
* @param {String} [config.lineCap] can be butt, round, or square. The default
* is butt
* @param {String} [config.shadowColor]
* @param {Number} [config.shadowBlur]
* @param {Object} [config.shadowOffset] object with x and y component
* @param {Number} [config.shadowOffsetX]
* @param {Number} [config.shadowOffsetY]
* @param {Number} [config.shadowOpacity] shadow opacity. Can be any real number
* between 0 and 1
* @param {Boolean} [config.shadowEnabled] flag which enables or disables the shadow. The default value is true
* @param {Array} [config.dash]
* @param {Boolean} [config.dashEnabled] flag which enables or disables the dashArray. The default value is true
* @param {Number} [config.x]
* @param {Number} [config.y]
* @param {Number} [config.width]
* @param {Number} [config.height]
* @param {Boolean} [config.visible]
* @param {Boolean} [config.listening] whether or not the node is listening for events
* @param {String} [config.id] unique id
* @param {String} [config.name] non-unique name
* @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1
* @param {Object} [config.scale] set scale
* @param {Number} [config.scaleX] set scale x
* @param {Number} [config.scaleY] set scale y
* @param {Number} [config.rotation] rotation in degrees
* @param {Object} [config.offset] offset from center point and rotation point
* @param {Number} [config.offsetX] set offset x
* @param {Number} [config.offsetY] set offset y
* @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop
* the entire stage by dragging any portion of the stage
* @param {Number} [config.dragDistance]
* @param {Function} [config.dragBoundFunc]
* @example
* var imageObj = new Image();
* imageObj.onload = function() {
* var image = new Konva.Image({
* x: 200,
* y: 50,
* image: imageObj,
* width: 100,
* height: 100
* });
* };
* imageObj.src = '/path/to/image.jpg'
*/
class Image extends Shape {
constructor(attrs) {
super(attrs);
this.on('imageChange.konva', () => {
this._setImageLoad();
});
this._setImageLoad();
}
_setImageLoad() {
const image = this.image();
// check is image is already loaded
if (image && image.complete) {
return;
}
// check is video is already loaded
if (image && image.readyState === 4) {
return;
}
if (image && image['addEventListener']) {
image['addEventListener']('load', () => {
this._requestDraw();
});
}
}
_useBufferCanvas() {
return super._useBufferCanvas(true);
}
_sceneFunc(context) {
const width = this.getWidth();
const height = this.getHeight();
const image = this.attrs.image;
let params;
if (image) {
const cropWidth = this.attrs.cropWidth;
const cropHeight = this.attrs.cropHeight;
if (cropWidth && cropHeight) {
params = [
image,
this.cropX(),
this.cropY(),
cropWidth,
cropHeight,
0,
0,
width,
height,
];
}
else {
params = [image, 0, 0, width, height];
}
}
if (this.hasFill() || this.hasStroke()) {
context.beginPath();
context.rect(0, 0, width, height);
context.closePath();
context.fillStrokeShape(this);
}
if (image) {
context.drawImage.apply(context, params);
}
}
_hitFunc(context) {
var width = this.width(), height = this.height();
context.beginPath();
context.rect(0, 0, width, height);
context.closePath();
context.fillStrokeShape(this);
}
getWidth() {
var _a, _b;
return (_a = this.attrs.width) !== null && _a !== void 0 ? _a : (_b = this.image()) === null || _b === void 0 ? void 0 : _b.width;
}
getHeight() {
var _a, _b;
return (_a = this.attrs.height) !== null && _a !== void 0 ? _a : (_b = this.image()) === null || _b === void 0 ? void 0 : _b.height;
}
/**
* load image from given url and create `Konva.Image` instance
* @method
* @memberof Konva.Image
* @param {String} url image source
* @param {Function} callback with Konva.Image instance as first argument
* @example
* Konva.Image.fromURL(imageURL, function(image){
* // image is Konva.Image instance
* layer.add(image);
* layer.draw();
* });
*/
static fromURL(url, callback) {
var img = Util.createImageElement();
img.onload = function () {
var image = new Image({
image: img,
});
callback(image);
};
img.crossOrigin = 'Anonymous';
img.src = url;
}
}
Image.prototype.className = 'Image';
_registerNode(Image);
/**
* get/set image source. It can be image, canvas or video element
* @name Konva.Image#image
* @method
* @param {Object} image source
* @returns {Object}
* @example
* // get value
* var image = shape.image();
*
* // set value
* shape.image(img);
*/
Factory.addGetterSetter(Image, 'image');
Factory.addComponentsGetterSetter(Image, 'crop', ['x', 'y', 'width', 'height']);
/**
* get/set crop
* @method
* @name Konva.Image#crop
* @param {Object} crop
* @param {Number} crop.x
* @param {Number} crop.y
* @param {Number} crop.width
* @param {Number} crop.height
* @returns {Object}
* @example
* // get crop
* var crop = image.crop();
*
* // set crop
* image.crop({
* x: 20,
* y: 20,
* width: 20,
* height: 20
* });
*/
Factory.addGetterSetter(Image, 'cropX', 0, getNumberValidator());
/**
* get/set crop x
* @method
* @name Konva.Image#cropX
* @param {Number} x
* @returns {Number}
* @example
* // get crop x
* var cropX = image.cropX();
*
* // set crop x
* image.cropX(20);
*/
Factory.addGetterSetter(Image, 'cropY', 0, getNumberValidator());
/**
* get/set crop y
* @name Konva.Image#cropY
* @method
* @param {Number} y
* @returns {Number}
* @example
* // get crop y
* var cropY = image.cropY();
*
* // set crop y
* image.cropY(20);
*/
Factory.addGetterSetter(Image, 'cropWidth', 0, getNumberValidator());
/**
* get/set crop width
* @name Konva.Image#cropWidth
* @method
* @param {Number} width
* @returns {Number}
* @example
* // get crop width
* var cropWidth = image.cropWidth();
*
* // set crop width
* image.cropWidth(20);
*/
Factory.addGetterSetter(Image, 'cropHeight', 0, getNumberValidator());
/**
* get/set crop height
* @name Konva.Image#cropHeight
* @method
* @param {Number} height
* @returns {Number}
* @example
* // get crop height
* var cropHeight = image.cropHeight();
*
* // set crop height
* image.cropHeight(20);
*/
// constants
var ATTR_CHANGE_LIST$2 = [
'fontFamily',
'fontSize',
'fontStyle',
'padding',
'lineHeight',
'text',
'width',
'height',
], CHANGE_KONVA$1 = 'Change.konva', NONE$1 = 'none', UP = 'up', RIGHT$1 = 'right', DOWN = 'down', LEFT$1 = 'left',
// cached variables
attrChangeListLen$1 = ATTR_CHANGE_LIST$2.length;
/**
* Label constructor. Labels are groups that contain a Text and Tag shape
* @constructor
* @memberof Konva
* @param {Object} config
* @param {Number} [config.x]
* @param {Number} [config.y]
* @param {Number} [config.width]
* @param {Number} [config.height]
* @param {Boolean} [config.visible]
* @param {Boolean} [config.listening] whether or not the node is listening for events
* @param {String} [config.id] unique id
* @param {String} [config.name] non-unique name
* @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1
* @param {Object} [config.scale] set scale
* @param {Number} [config.scaleX] set scale x
* @param {Number} [config.scaleY] set scale y
* @param {Number} [config.rotation] rotation in degrees
* @param {Object} [config.offset] offset from center point and rotation point
* @param {Number} [config.offsetX] set offset x
* @param {Number} [config.offsetY] set offset y
* @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop
* the entire stage by dragging any portion of the stage
* @param {Number} [config.dragDistance]
* @param {Function} [config.dragBoundFunc]
* @example
* // create label
* var label = new Konva.Label({
* x: 100,
* y: 100,
* draggable: true
* });
*
* // add a tag to the label
* label.add(new Konva.Tag({
* fill: '#bbb',
* stroke: '#333',
* shadowColor: 'black',
* shadowBlur: 10,
* shadowOffset: [10, 10],
* shadowOpacity: 0.2,
* lineJoin: 'round',
* pointerDirection: 'up',
* pointerWidth: 20,
* pointerHeight: 20,
* cornerRadius: 5
* }));
*
* // add text to the label
* label.add(new Konva.Text({
* text: 'Hello World!',
* fontSize: 50,
* lineHeight: 1.2,
* padding: 10,
* fill: 'green'
* }));
*/
class Label extends Group {
constructor(config) {
super(config);
this.on('add.konva', function (evt) {
this._addListeners(evt.child);
this._sync();
});
}
/**
* get Text shape for the label. You need to access the Text shape in order to update
* the text properties
* @name Konva.Label#getText
* @method
* @example
* label.getText().fill('red')
*/
getText() {
return this.find('Text')[0];
}
/**
* get Tag shape for the label. You need to access the Tag shape in order to update
* the pointer properties and the corner radius
* @name Konva.Label#getTag
* @method
*/
getTag() {
return this.find('Tag')[0];
}
_addListeners(text) {
var that = this, n;
var func = function () {
that._sync();
};
// update text data for certain attr changes
for (n = 0; n < attrChangeListLen$1; n++) {
text.on(ATTR_CHANGE_LIST$2[n] + CHANGE_KONVA$1, func);
}
}
getWidth() {
return this.getText().width();
}
getHeight() {
return this.getText().height();
}
_sync() {
var text = this.getText(), tag = this.getTag(), width, height, pointerDirection, pointerWidth, x, y, pointerHeight;
if (text && tag) {
width = text.width();
height = text.height();
pointerDirection = tag.pointerDirection();
pointerWidth = tag.pointerWidth();
pointerHeight = tag.pointerHeight();
x = 0;
y = 0;
switch (pointerDirection) {
case UP:
x = width / 2;
y = -1 * pointerHeight;
break;
case RIGHT$1:
x = width + pointerWidth;
y = height / 2;
break;
case DOWN:
x = width / 2;
y = height + pointerHeight;
break;
case LEFT$1:
x = -1 * pointerWidth;
y = height / 2;
break;
}
tag.setAttrs({
x: -1 * x,
y: -1 * y,
width: width,
height: height,
});
text.setAttrs({
x: -1 * x,
y: -1 * y,
});
}
}
}
Label.prototype.className = 'Label';
_registerNode(Label);
/**
* Tag constructor. A Tag can be configured
* to have a pointer element that points up, right, down, or left
* @constructor
* @memberof Konva
* @param {Object} config
* @param {String} [config.pointerDirection] can be up, right, down, left, or none; the default
* is none. When a pointer is present, the positioning of the label is relative to the tip of the pointer.
* @param {Number} [config.pointerWidth]
* @param {Number} [config.pointerHeight]
* @param {Number} [config.cornerRadius]
*/
class Tag extends Shape {
_sceneFunc(context) {
var width = this.width(), height = this.height(), pointerDirection = this.pointerDirection(), pointerWidth = this.pointerWidth(), pointerHeight = this.pointerHeight(), cornerRadius = this.cornerRadius();
let topLeft = 0;
let topRight = 0;
let bottomLeft = 0;
let bottomRight = 0;
if (typeof cornerRadius === 'number') {
topLeft = topRight = bottomLeft = bottomRight = Math.min(cornerRadius, width / 2, height / 2);
}
else {
topLeft = Math.min(cornerRadius[0] || 0, width / 2, height / 2);
topRight = Math.min(cornerRadius[1] || 0, width / 2, height / 2);
bottomRight = Math.min(cornerRadius[2] || 0, width / 2, height / 2);
bottomLeft = Math.min(cornerRadius[3] || 0, width / 2, height / 2);
}
context.beginPath();
context.moveTo(topLeft, 0);
if (pointerDirection === UP) {
context.lineTo((width - pointerWidth) / 2, 0);
context.lineTo(width / 2, -1 * pointerHeight);
context.lineTo((width + pointerWidth) / 2, 0);
}
context.lineTo(width - topRight, 0);
context.arc(width - topRight, topRight, topRight, (Math.PI * 3) / 2, 0, false);
if (pointerDirection === RIGHT$1) {
context.lineTo(width, (height - pointerHeight) / 2);
context.lineTo(width + pointerWidth, height / 2);
context.lineTo(width, (height + pointerHeight) / 2);
}
context.lineTo(width, height - bottomRight);
context.arc(width - bottomRight, height - bottomRight, bottomRight, 0, Math.PI / 2, false);
if (pointerDirection === DOWN) {
context.lineTo((width + pointerWidth) / 2, height);
context.lineTo(width / 2, height + pointerHeight);
context.lineTo((width - pointerWidth) / 2, height);
}
context.lineTo(bottomLeft, height);
context.arc(bottomLeft, height - bottomLeft, bottomLeft, Math.PI / 2, Math.PI, false);
if (pointerDirection === LEFT$1) {
context.lineTo(0, (height + pointerHeight) / 2);
context.lineTo(-1 * pointerWidth, height / 2);
context.lineTo(0, (height - pointerHeight) / 2);
}
context.lineTo(0, topLeft);
context.arc(topLeft, topLeft, topLeft, Math.PI, (Math.PI * 3) / 2, false);
context.closePath();
context.fillStrokeShape(this);
}
getSelfRect() {
var x = 0, y = 0, pointerWidth = this.pointerWidth(), pointerHeight = this.pointerHeight(), direction = this.pointerDirection(), width = this.width(), height = this.height();
if (direction === UP) {
y -= pointerHeight;
height += pointerHeight;
}
else if (direction === DOWN) {
height += pointerHeight;
}
else if (direction === LEFT$1) {
// ARGH!!! I have no idea why should I used magic 1.5!!!!!!!!!
x -= pointerWidth * 1.5;
width += pointerWidth;
}
else if (direction === RIGHT$1) {
width += pointerWidth * 1.5;
}
return {
x: x,
y: y,
width: width,
height: height,
};
}
}
Tag.prototype.className = 'Tag';
_registerNode(Tag);
/**
* get/set pointer direction
* @name Konva.Tag#pointerDirection
* @method
* @param {String} pointerDirection can be up, right, down, left, or none. The default is none.
* @returns {String}
* @example
* tag.pointerDirection('right');
*/
Factory.addGetterSetter(Tag, 'pointerDirection', NONE$1);
/**
* get/set pointer width
* @name Konva.Tag#pointerWidth
* @method
* @param {Number} pointerWidth
* @returns {Number}
* @example
* tag.pointerWidth(20);
*/
Factory.addGetterSetter(Tag, 'pointerWidth', 0, getNumberValidator());
/**
* get/set pointer height
* @method
* @name Konva.Tag#pointerHeight
* @param {Number} pointerHeight
* @returns {Number}
* @example
* tag.pointerHeight(20);
*/
Factory.addGetterSetter(Tag, 'pointerHeight', 0, getNumberValidator());
/**
* get/set cornerRadius
* @name Konva.Tag#cornerRadius
* @method
* @param {Number} cornerRadius
* @returns {Number}
* @example
* tag.cornerRadius(20);
*
* // set different corner radius values
* // top-left, top-right, bottom-right, bottom-left
* tag.cornerRadius([0, 10, 20, 30]);
*/
Factory.addGetterSetter(Tag, 'cornerRadius', 0, getNumberOrArrayOfNumbersValidator(4));
/**
* Rect constructor
* @constructor
* @memberof Konva
* @augments Konva.Shape
* @param {Object} config
* @param {Number} [config.cornerRadius]
* @param {String} [config.fill] fill color
* @param {Image} [config.fillPatternImage] fill pattern image
* @param {Number} [config.fillPatternX]
* @param {Number} [config.fillPatternY]
* @param {Object} [config.fillPatternOffset] object with x and y component
* @param {Number} [config.fillPatternOffsetX]
* @param {Number} [config.fillPatternOffsetY]
* @param {Object} [config.fillPatternScale] object with x and y component
* @param {Number} [config.fillPatternScaleX]
* @param {Number} [config.fillPatternScaleY]
* @param {Number} [config.fillPatternRotation]
* @param {String} [config.fillPatternRepeat] can be "repeat", "repeat-x", "repeat-y", or "no-repeat". The default is "no-repeat"
* @param {Object} [config.fillLinearGradientStartPoint] object with x and y component
* @param {Number} [config.fillLinearGradientStartPointX]
* @param {Number} [config.fillLinearGradientStartPointY]
* @param {Object} [config.fillLinearGradientEndPoint] object with x and y component
* @param {Number} [config.fillLinearGradientEndPointX]
* @param {Number} [config.fillLinearGradientEndPointY]
* @param {Array} [config.fillLinearGradientColorStops] array of color stops
* @param {Object} [config.fillRadialGradientStartPoint] object with x and y component
* @param {Number} [config.fillRadialGradientStartPointX]
* @param {Number} [config.fillRadialGradientStartPointY]
* @param {Object} [config.fillRadialGradientEndPoint] object with x and y component
* @param {Number} [config.fillRadialGradientEndPointX]
* @param {Number} [config.fillRadialGradientEndPointY]
* @param {Number} [config.fillRadialGradientStartRadius]
* @param {Number} [config.fillRadialGradientEndRadius]
* @param {Array} [config.fillRadialGradientColorStops] array of color stops
* @param {Boolean} [config.fillEnabled] flag which enables or disables the fill. The default value is true
* @param {String} [config.fillPriority] can be color, linear-gradient, radial-graident, or pattern. The default value is color. The fillPriority property makes it really easy to toggle between different fill types. For example, if you want to toggle between a fill color style and a fill pattern style, simply set the fill property and the fillPattern properties, and then use setFillPriority('color') to render the shape with a color fill, or use setFillPriority('pattern') to render the shape with the pattern fill configuration
* @param {String} [config.stroke] stroke color
* @param {Number} [config.strokeWidth] stroke width
* @param {Boolean} [config.fillAfterStrokeEnabled]. Should we draw fill AFTER stroke? Default is false.
* @param {Number} [config.hitStrokeWidth] size of the stroke on hit canvas. The default is "auto" - equals to strokeWidth
* @param {Boolean} [config.strokeHitEnabled] flag which enables or disables stroke hit region. The default is true
* @param {Boolean} [config.perfectDrawEnabled] flag which enables or disables using buffer canvas. The default is true
* @param {Boolean} [config.shadowForStrokeEnabled] flag which enables or disables shadow for stroke. The default is true
* @param {Boolean} [config.strokeScaleEnabled] flag which enables or disables stroke scale. The default is true
* @param {Boolean} [config.strokeEnabled] flag which enables or disables the stroke. The default value is true
* @param {String} [config.lineJoin] can be miter, round, or bevel. The default
* is miter
* @param {String} [config.lineCap] can be butt, round, or square. The default
* is butt
* @param {String} [config.shadowColor]
* @param {Number} [config.shadowBlur]
* @param {Object} [config.shadowOffset] object with x and y component
* @param {Number} [config.shadowOffsetX]
* @param {Number} [config.shadowOffsetY]
* @param {Number} [config.shadowOpacity] shadow opacity. Can be any real number
* between 0 and 1
* @param {Boolean} [config.shadowEnabled] flag which enables or disables the shadow. The default value is true
* @param {Array} [config.dash]
* @param {Boolean} [config.dashEnabled] flag which enables or disables the dashArray. The default value is true
* @param {Number} [config.x]
* @param {Number} [config.y]
* @param {Number} [config.width]
* @param {Number} [config.height]
* @param {Boolean} [config.visible]
* @param {Boolean} [config.listening] whether or not the node is listening for events
* @param {String} [config.id] unique id
* @param {String} [config.name] non-unique name
* @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1
* @param {Object} [config.scale] set scale
* @param {Number} [config.scaleX] set scale x
* @param {Number} [config.scaleY] set scale y
* @param {Number} [config.rotation] rotation in degrees
* @param {Object} [config.offset] offset from center point and rotation point
* @param {Number} [config.offsetX] set offset x
* @param {Number} [config.offsetY] set offset y
* @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop
* the entire stage by dragging any portion of the stage
* @param {Number} [config.dragDistance]
* @param {Function} [config.dragBoundFunc]
* @example
* var rect = new Konva.Rect({
* width: 100,
* height: 50,
* fill: 'red',
* stroke: 'black',
* strokeWidth: 5
* });
*/
class Rect extends Shape {
_sceneFunc(context) {
var cornerRadius = this.cornerRadius(), width = this.width(), height = this.height();
context.beginPath();
if (!cornerRadius) {
// simple rect - don't bother doing all that complicated maths stuff.
context.rect(0, 0, width, height);
}
else {
let topLeft = 0;
let topRight = 0;
let bottomLeft = 0;
let bottomRight = 0;
if (typeof cornerRadius === 'number') {
topLeft = topRight = bottomLeft = bottomRight = Math.min(cornerRadius, width / 2, height / 2);
}
else {
topLeft = Math.min(cornerRadius[0] || 0, width / 2, height / 2);
topRight = Math.min(cornerRadius[1] || 0, width / 2, height / 2);
bottomRight = Math.min(cornerRadius[2] || 0, width / 2, height / 2);
bottomLeft = Math.min(cornerRadius[3] || 0, width / 2, height / 2);
}
context.moveTo(topLeft, 0);
context.lineTo(width - topRight, 0);
context.arc(width - topRight, topRight, topRight, (Math.PI * 3) / 2, 0, false);
context.lineTo(width, height - bottomRight);
context.arc(width - bottomRight, height - bottomRight, bottomRight, 0, Math.PI / 2, false);
context.lineTo(bottomLeft, height);
context.arc(bottomLeft, height - bottomLeft, bottomLeft, Math.PI / 2, Math.PI, false);
context.lineTo(0, topLeft);
context.arc(topLeft, topLeft, topLeft, Math.PI, (Math.PI * 3) / 2, false);
}
context.closePath();
context.fillStrokeShape(this);
}
}
Rect.prototype.className = 'Rect';
_registerNode(Rect);
/**
* get/set corner radius
* @method
* @name Konva.Rect#cornerRadius
* @param {Number} cornerRadius
* @returns {Number}
* @example
* // get corner radius
* var cornerRadius = rect.cornerRadius();
*
* // set corner radius
* rect.cornerRadius(10);
*
* // set different corner radius values
* // top-left, top-right, bottom-right, bottom-left
* rect.cornerRadius([0, 10, 20, 30]);
*/
Factory.addGetterSetter(Rect, 'cornerRadius', 0, getNumberOrArrayOfNumbersValidator(4));
/**
* RegularPolygon constructor. Examples include triangles, squares, pentagons, hexagons, etc.
* @constructor
* @memberof Konva
* @augments Konva.Shape
* @param {Object} config
* @param {Number} config.sides
* @param {Number} config.radius
* @param {String} [config.fill] fill color
* @param {Image} [config.fillPatternImage] fill pattern image
* @param {Number} [config.fillPatternX]
* @param {Number} [config.fillPatternY]
* @param {Object} [config.fillPatternOffset] object with x and y component
* @param {Number} [config.fillPatternOffsetX]
* @param {Number} [config.fillPatternOffsetY]
* @param {Object} [config.fillPatternScale] object with x and y component
* @param {Number} [config.fillPatternScaleX]
* @param {Number} [config.fillPatternScaleY]
* @param {Number} [config.fillPatternRotation]
* @param {String} [config.fillPatternRepeat] can be "repeat", "repeat-x", "repeat-y", or "no-repeat". The default is "no-repeat"
* @param {Object} [config.fillLinearGradientStartPoint] object with x and y component
* @param {Number} [config.fillLinearGradientStartPointX]
* @param {Number} [config.fillLinearGradientStartPointY]
* @param {Object} [config.fillLinearGradientEndPoint] object with x and y component
* @param {Number} [config.fillLinearGradientEndPointX]
* @param {Number} [config.fillLinearGradientEndPointY]
* @param {Array} [config.fillLinearGradientColorStops] array of color stops
* @param {Object} [config.fillRadialGradientStartPoint] object with x and y component
* @param {Number} [config.fillRadialGradientStartPointX]
* @param {Number} [config.fillRadialGradientStartPointY]
* @param {Object} [config.fillRadialGradientEndPoint] object with x and y component
* @param {Number} [config.fillRadialGradientEndPointX]
* @param {Number} [config.fillRadialGradientEndPointY]
* @param {Number} [config.fillRadialGradientStartRadius]
* @param {Number} [config.fillRadialGradientEndRadius]
* @param {Array} [config.fillRadialGradientColorStops] array of color stops
* @param {Boolean} [config.fillEnabled] flag which enables or disables the fill. The default value is true
* @param {String} [config.fillPriority] can be color, linear-gradient, radial-graident, or pattern. The default value is color. The fillPriority property makes it really easy to toggle between different fill types. For example, if you want to toggle between a fill color style and a fill pattern style, simply set the fill property and the fillPattern properties, and then use setFillPriority('color') to render the shape with a color fill, or use setFillPriority('pattern') to render the shape with the pattern fill configuration
* @param {String} [config.stroke] stroke color
* @param {Number} [config.strokeWidth] stroke width
* @param {Boolean} [config.fillAfterStrokeEnabled]. Should we draw fill AFTER stroke? Default is false.
* @param {Number} [config.hitStrokeWidth] size of the stroke on hit canvas. The default is "auto" - equals to strokeWidth
* @param {Boolean} [config.strokeHitEnabled] flag which enables or disables stroke hit region. The default is true
* @param {Boolean} [config.perfectDrawEnabled] flag which enables or disables using buffer canvas. The default is true
* @param {Boolean} [config.shadowForStrokeEnabled] flag which enables or disables shadow for stroke. The default is true
* @param {Boolean} [config.strokeScaleEnabled] flag which enables or disables stroke scale. The default is true
* @param {Boolean} [config.strokeEnabled] flag which enables or disables the stroke. The default value is true
* @param {String} [config.lineJoin] can be miter, round, or bevel. The default
* is miter
* @param {String} [config.lineCap] can be butt, round, or square. The default
* is butt
* @param {String} [config.shadowColor]
* @param {Number} [config.shadowBlur]
* @param {Object} [config.shadowOffset] object with x and y component
* @param {Number} [config.shadowOffsetX]
* @param {Number} [config.shadowOffsetY]
* @param {Number} [config.shadowOpacity] shadow opacity. Can be any real number
* between 0 and 1
* @param {Boolean} [config.shadowEnabled] flag which enables or disables the shadow. The default value is true
* @param {Array} [config.dash]
* @param {Boolean} [config.dashEnabled] flag which enables or disables the dashArray. The default value is true
* @param {Number} [config.x]
* @param {Number} [config.y]
* @param {Number} [config.width]
* @param {Number} [config.height]
* @param {Boolean} [config.visible]
* @param {Boolean} [config.listening] whether or not the node is listening for events
* @param {String} [config.id] unique id
* @param {String} [config.name] non-unique name
* @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1
* @param {Object} [config.scale] set scale
* @param {Number} [config.scaleX] set scale x
* @param {Number} [config.scaleY] set scale y
* @param {Number} [config.rotation] rotation in degrees
* @param {Object} [config.offset] offset from center point and rotation point
* @param {Number} [config.offsetX] set offset x
* @param {Number} [config.offsetY] set offset y
* @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop
* the entire stage by dragging any portion of the stage
* @param {Number} [config.dragDistance]
* @param {Function} [config.dragBoundFunc]
* @example
* var hexagon = new Konva.RegularPolygon({
* x: 100,
* y: 200,
* sides: 6,
* radius: 70,
* fill: 'red',
* stroke: 'black',
* strokeWidth: 4
* });
*/
class RegularPolygon extends Shape {
_sceneFunc(context) {
const points = this._getPoints();
context.beginPath();
context.moveTo(points[0].x, points[0].y);
for (var n = 1; n < points.length; n++) {
context.lineTo(points[n].x, points[n].y);
}
context.closePath();
context.fillStrokeShape(this);
}
_getPoints() {
const sides = this.attrs.sides;
const radius = this.attrs.radius || 0;
const points = [];
for (var n = 0; n < sides; n++) {
points.push({
x: radius * Math.sin((n * 2 * Math.PI) / sides),
y: -1 * radius * Math.cos((n * 2 * Math.PI) / sides),
});
}
return points;
}
getSelfRect() {
const points = this._getPoints();
var minX = points[0].x;
var maxX = points[0].y;
var minY = points[0].x;
var maxY = points[0].y;
points.forEach((point) => {
minX = Math.min(minX, point.x);
maxX = Math.max(maxX, point.x);
minY = Math.min(minY, point.y);
maxY = Math.max(maxY, point.y);
});
return {
x: minX,
y: minY,
width: maxX - minX,
height: maxY - minY,
};
}
getWidth() {
return this.radius() * 2;
}
getHeight() {
return this.radius() * 2;
}
setWidth(width) {
this.radius(width / 2);
}
setHeight(height) {
this.radius(height / 2);
}
}
RegularPolygon.prototype.className = 'RegularPolygon';
RegularPolygon.prototype._centroid = true;
RegularPolygon.prototype._attrsAffectingSize = ['radius'];
_registerNode(RegularPolygon);
/**
* get/set radius
* @method
* @name Konva.RegularPolygon#radius
* @param {Number} radius
* @returns {Number}
* @example
* // get radius
* var radius = shape.radius();
*
* // set radius
* shape.radius(10);
*/
Factory.addGetterSetter(RegularPolygon, 'radius', 0, getNumberValidator());
/**
* get/set sides
* @method
* @name Konva.RegularPolygon#sides
* @param {Number} sides
* @returns {Number}
* @example
* // get sides
* var sides = shape.sides();
*
* // set sides
* shape.sides(10);
*/
Factory.addGetterSetter(RegularPolygon, 'sides', 0, getNumberValidator());
var PIx2 = Math.PI * 2;
/**
* Ring constructor
* @constructor
* @augments Konva.Shape
* @memberof Konva
* @param {Object} config
* @param {Number} config.innerRadius
* @param {Number} config.outerRadius
* @param {Boolean} [config.clockwise]
* @param {String} [config.fill] fill color
* @param {Image} [config.fillPatternImage] fill pattern image
* @param {Number} [config.fillPatternX]
* @param {Number} [config.fillPatternY]
* @param {Object} [config.fillPatternOffset] object with x and y component
* @param {Number} [config.fillPatternOffsetX]
* @param {Number} [config.fillPatternOffsetY]
* @param {Object} [config.fillPatternScale] object with x and y component
* @param {Number} [config.fillPatternScaleX]
* @param {Number} [config.fillPatternScaleY]
* @param {Number} [config.fillPatternRotation]
* @param {String} [config.fillPatternRepeat] can be "repeat", "repeat-x", "repeat-y", or "no-repeat". The default is "no-repeat"
* @param {Object} [config.fillLinearGradientStartPoint] object with x and y component
* @param {Number} [config.fillLinearGradientStartPointX]
* @param {Number} [config.fillLinearGradientStartPointY]
* @param {Object} [config.fillLinearGradientEndPoint] object with x and y component
* @param {Number} [config.fillLinearGradientEndPointX]
* @param {Number} [config.fillLinearGradientEndPointY]
* @param {Array} [config.fillLinearGradientColorStops] array of color stops
* @param {Object} [config.fillRadialGradientStartPoint] object with x and y component
* @param {Number} [config.fillRadialGradientStartPointX]
* @param {Number} [config.fillRadialGradientStartPointY]
* @param {Object} [config.fillRadialGradientEndPoint] object with x and y component
* @param {Number} [config.fillRadialGradientEndPointX]
* @param {Number} [config.fillRadialGradientEndPointY]
* @param {Number} [config.fillRadialGradientStartRadius]
* @param {Number} [config.fillRadialGradientEndRadius]
* @param {Array} [config.fillRadialGradientColorStops] array of color stops
* @param {Boolean} [config.fillEnabled] flag which enables or disables the fill. The default value is true
* @param {String} [config.fillPriority] can be color, linear-gradient, radial-graident, or pattern. The default value is color. The fillPriority property makes it really easy to toggle between different fill types. For example, if you want to toggle between a fill color style and a fill pattern style, simply set the fill property and the fillPattern properties, and then use setFillPriority('color') to render the shape with a color fill, or use setFillPriority('pattern') to render the shape with the pattern fill configuration
* @param {String} [config.stroke] stroke color
* @param {Number} [config.strokeWidth] stroke width
* @param {Boolean} [config.fillAfterStrokeEnabled]. Should we draw fill AFTER stroke? Default is false.
* @param {Number} [config.hitStrokeWidth] size of the stroke on hit canvas. The default is "auto" - equals to strokeWidth
* @param {Boolean} [config.strokeHitEnabled] flag which enables or disables stroke hit region. The default is true
* @param {Boolean} [config.perfectDrawEnabled] flag which enables or disables using buffer canvas. The default is true
* @param {Boolean} [config.shadowForStrokeEnabled] flag which enables or disables shadow for stroke. The default is true
* @param {Boolean} [config.strokeScaleEnabled] flag which enables or disables stroke scale. The default is true
* @param {Boolean} [config.strokeEnabled] flag which enables or disables the stroke. The default value is true
* @param {String} [config.lineJoin] can be miter, round, or bevel. The default
* is miter
* @param {String} [config.lineCap] can be butt, round, or square. The default
* is butt
* @param {String} [config.shadowColor]
* @param {Number} [config.shadowBlur]
* @param {Object} [config.shadowOffset] object with x and y component
* @param {Number} [config.shadowOffsetX]
* @param {Number} [config.shadowOffsetY]
* @param {Number} [config.shadowOpacity] shadow opacity. Can be any real number
* between 0 and 1
* @param {Boolean} [config.shadowEnabled] flag which enables or disables the shadow. The default value is true
* @param {Array} [config.dash]
* @param {Boolean} [config.dashEnabled] flag which enables or disables the dashArray. The default value is true
* @param {Number} [config.x]
* @param {Number} [config.y]
* @param {Number} [config.width]
* @param {Number} [config.height]
* @param {Boolean} [config.visible]
* @param {Boolean} [config.listening] whether or not the node is listening for events
* @param {String} [config.id] unique id
* @param {String} [config.name] non-unique name
* @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1
* @param {Object} [config.scale] set scale
* @param {Number} [config.scaleX] set scale x
* @param {Number} [config.scaleY] set scale y
* @param {Number} [config.rotation] rotation in degrees
* @param {Object} [config.offset] offset from center point and rotation point
* @param {Number} [config.offsetX] set offset x
* @param {Number} [config.offsetY] set offset y
* @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop
* the entire stage by dragging any portion of the stage
* @param {Number} [config.dragDistance]
* @param {Function} [config.dragBoundFunc]
* @example
* var ring = new Konva.Ring({
* innerRadius: 40,
* outerRadius: 80,
* fill: 'red',
* stroke: 'black',
* strokeWidth: 5
* });
*/
class Ring extends Shape {
_sceneFunc(context) {
context.beginPath();
context.arc(0, 0, this.innerRadius(), 0, PIx2, false);
context.moveTo(this.outerRadius(), 0);
context.arc(0, 0, this.outerRadius(), PIx2, 0, true);
context.closePath();
context.fillStrokeShape(this);
}
getWidth() {
return this.outerRadius() * 2;
}
getHeight() {
return this.outerRadius() * 2;
}
setWidth(width) {
this.outerRadius(width / 2);
}
setHeight(height) {
this.outerRadius(height / 2);
}
}
Ring.prototype.className = 'Ring';
Ring.prototype._centroid = true;
Ring.prototype._attrsAffectingSize = ['innerRadius', 'outerRadius'];
_registerNode(Ring);
/**
* get/set innerRadius
* @method
* @name Konva.Ring#innerRadius
* @param {Number} innerRadius
* @returns {Number}
* @example
* // get inner radius
* var innerRadius = ring.innerRadius();
*
* // set inner radius
* ring.innerRadius(20);
*/
Factory.addGetterSetter(Ring, 'innerRadius', 0, getNumberValidator());
/**
* get/set outerRadius
* @name Konva.Ring#outerRadius
* @method
* @param {Number} outerRadius
* @returns {Number}
* @example
* // get outer radius
* var outerRadius = ring.outerRadius();
*
* // set outer radius
* ring.outerRadius(20);
*/
Factory.addGetterSetter(Ring, 'outerRadius', 0, getNumberValidator());
/**
* Sprite constructor
* @constructor
* @memberof Konva
* @augments Konva.Shape
* @param {Object} config
* @param {String} config.animation animation key
* @param {Object} config.animations animation map
* @param {Integer} [config.frameIndex] animation frame index
* @param {Image} config.image image object
* @param {Integer} [config.frameRate] animation frame rate
* @param {String} [config.fill] fill color
* @param {Image} [config.fillPatternImage] fill pattern image
* @param {Number} [config.fillPatternX]
* @param {Number} [config.fillPatternY]
* @param {Object} [config.fillPatternOffset] object with x and y component
* @param {Number} [config.fillPatternOffsetX]
* @param {Number} [config.fillPatternOffsetY]
* @param {Object} [config.fillPatternScale] object with x and y component
* @param {Number} [config.fillPatternScaleX]
* @param {Number} [config.fillPatternScaleY]
* @param {Number} [config.fillPatternRotation]
* @param {String} [config.fillPatternRepeat] can be "repeat", "repeat-x", "repeat-y", or "no-repeat". The default is "no-repeat"
* @param {Object} [config.fillLinearGradientStartPoint] object with x and y component
* @param {Number} [config.fillLinearGradientStartPointX]
* @param {Number} [config.fillLinearGradientStartPointY]
* @param {Object} [config.fillLinearGradientEndPoint] object with x and y component
* @param {Number} [config.fillLinearGradientEndPointX]
* @param {Number} [config.fillLinearGradientEndPointY]
* @param {Array} [config.fillLinearGradientColorStops] array of color stops
* @param {Object} [config.fillRadialGradientStartPoint] object with x and y component
* @param {Number} [config.fillRadialGradientStartPointX]
* @param {Number} [config.fillRadialGradientStartPointY]
* @param {Object} [config.fillRadialGradientEndPoint] object with x and y component
* @param {Number} [config.fillRadialGradientEndPointX]
* @param {Number} [config.fillRadialGradientEndPointY]
* @param {Number} [config.fillRadialGradientStartRadius]
* @param {Number} [config.fillRadialGradientEndRadius]
* @param {Array} [config.fillRadialGradientColorStops] array of color stops
* @param {Boolean} [config.fillEnabled] flag which enables or disables the fill. The default value is true
* @param {String} [config.fillPriority] can be color, linear-gradient, radial-graident, or pattern. The default value is color. The fillPriority property makes it really easy to toggle between different fill types. For example, if you want to toggle between a fill color style and a fill pattern style, simply set the fill property and the fillPattern properties, and then use setFillPriority('color') to render the shape with a color fill, or use setFillPriority('pattern') to render the shape with the pattern fill configuration
* @param {String} [config.stroke] stroke color
* @param {Number} [config.strokeWidth] stroke width
* @param {Boolean} [config.fillAfterStrokeEnabled]. Should we draw fill AFTER stroke? Default is false.
* @param {Number} [config.hitStrokeWidth] size of the stroke on hit canvas. The default is "auto" - equals to strokeWidth
* @param {Boolean} [config.strokeHitEnabled] flag which enables or disables stroke hit region. The default is true
* @param {Boolean} [config.perfectDrawEnabled] flag which enables or disables using buffer canvas. The default is true
* @param {Boolean} [config.shadowForStrokeEnabled] flag which enables or disables shadow for stroke. The default is true
* @param {Boolean} [config.strokeScaleEnabled] flag which enables or disables stroke scale. The default is true
* @param {Boolean} [config.strokeEnabled] flag which enables or disables the stroke. The default value is true
* @param {String} [config.lineJoin] can be miter, round, or bevel. The default
* is miter
* @param {String} [config.lineCap] can be butt, round, or square. The default
* is butt
* @param {String} [config.shadowColor]
* @param {Number} [config.shadowBlur]
* @param {Object} [config.shadowOffset] object with x and y component
* @param {Number} [config.shadowOffsetX]
* @param {Number} [config.shadowOffsetY]
* @param {Number} [config.shadowOpacity] shadow opacity. Can be any real number
* between 0 and 1
* @param {Boolean} [config.shadowEnabled] flag which enables or disables the shadow. The default value is true
* @param {Array} [config.dash]
* @param {Boolean} [config.dashEnabled] flag which enables or disables the dashArray. The default value is true
* @param {Number} [config.x]
* @param {Number} [config.y]
* @param {Number} [config.width]
* @param {Number} [config.height]
* @param {Boolean} [config.visible]
* @param {Boolean} [config.listening] whether or not the node is listening for events
* @param {String} [config.id] unique id
* @param {String} [config.name] non-unique name
* @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1
* @param {Object} [config.scale] set scale
* @param {Number} [config.scaleX] set scale x
* @param {Number} [config.scaleY] set scale y
* @param {Number} [config.rotation] rotation in degrees
* @param {Object} [config.offset] offset from center point and rotation point
* @param {Number} [config.offsetX] set offset x
* @param {Number} [config.offsetY] set offset y
* @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop
* the entire stage by dragging any portion of the stage
* @param {Number} [config.dragDistance]
* @param {Function} [config.dragBoundFunc]
* @example
* var imageObj = new Image();
* imageObj.onload = function() {
* var sprite = new Konva.Sprite({
* x: 200,
* y: 100,
* image: imageObj,
* animation: 'standing',
* animations: {
* standing: [
* // x, y, width, height (6 frames)
* 0, 0, 49, 109,
* 52, 0, 49, 109,
* 105, 0, 49, 109,
* 158, 0, 49, 109,
* 210, 0, 49, 109,
* 262, 0, 49, 109
* ],
* kicking: [
* // x, y, width, height (6 frames)
* 0, 109, 45, 98,
* 45, 109, 45, 98,
* 95, 109, 63, 98,
* 156, 109, 70, 98,
* 229, 109, 60, 98,
* 287, 109, 41, 98
* ]
* },
* frameRate: 7,
* frameIndex: 0
* });
* };
* imageObj.src = '/path/to/image.jpg'
*/
class Sprite extends Shape {
constructor(config) {
super(config);
this._updated = true;
this.anim = new Animation(() => {
// if we don't need to redraw layer we should return false
var updated = this._updated;
this._updated = false;
return updated;
});
this.on('animationChange.konva', function () {
// reset index when animation changes
this.frameIndex(0);
});
this.on('frameIndexChange.konva', function () {
this._updated = true;
});
// smooth change for frameRate
this.on('frameRateChange.konva', function () {
if (!this.anim.isRunning()) {
return;
}
clearInterval(this.interval);
this._setInterval();
});
}
_sceneFunc(context) {
var anim = this.animation(), index = this.frameIndex(), ix4 = index * 4, set = this.animations()[anim], offsets = this.frameOffsets(), x = set[ix4 + 0], y = set[ix4 + 1], width = set[ix4 + 2], height = set[ix4 + 3], image = this.image();
if (this.hasFill() || this.hasStroke()) {
context.beginPath();
context.rect(0, 0, width, height);
context.closePath();
context.fillStrokeShape(this);
}
if (image) {
if (offsets) {
var offset = offsets[anim], ix2 = index * 2;
context.drawImage(image, x, y, width, height, offset[ix2 + 0], offset[ix2 + 1], width, height);
}
else {
context.drawImage(image, x, y, width, height, 0, 0, width, height);
}
}
}
_hitFunc(context) {
var anim = this.animation(), index = this.frameIndex(), ix4 = index * 4, set = this.animations()[anim], offsets = this.frameOffsets(), width = set[ix4 + 2], height = set[ix4 + 3];
context.beginPath();
if (offsets) {
var offset = offsets[anim];
var ix2 = index * 2;
context.rect(offset[ix2 + 0], offset[ix2 + 1], width, height);
}
else {
context.rect(0, 0, width, height);
}
context.closePath();
context.fillShape(this);
}
_useBufferCanvas() {
return super._useBufferCanvas(true);
}
_setInterval() {
var that = this;
this.interval = setInterval(function () {
that._updateIndex();
}, 1000 / this.frameRate());
}
/**
* start sprite animation
* @method
* @name Konva.Sprite#start
*/
start() {
if (this.isRunning()) {
return;
}
var layer = this.getLayer();
/*
* animation object has no executable function because
* the updates are done with a fixed FPS with the setInterval
* below. The anim object only needs the layer reference for
* redraw
*/
this.anim.setLayers(layer);
this._setInterval();
this.anim.start();
}
/**
* stop sprite animation
* @method
* @name Konva.Sprite#stop
*/
stop() {
this.anim.stop();
clearInterval(this.interval);
}
/**
* determine if animation of sprite is running or not. returns true or false
* @method
* @name Konva.Sprite#isRunning
* @returns {Boolean}
*/
isRunning() {
return this.anim.isRunning();
}
_updateIndex() {
var index = this.frameIndex(), animation = this.animation(), animations = this.animations(), anim = animations[animation], len = anim.length / 4;
if (index < len - 1) {
this.frameIndex(index + 1);
}
else {
this.frameIndex(0);
}
}
}
Sprite.prototype.className = 'Sprite';
_registerNode(Sprite);
// add getters setters
Factory.addGetterSetter(Sprite, 'animation');
/**
* get/set animation key
* @name Konva.Sprite#animation
* @method
* @param {String} anim animation key
* @returns {String}
* @example
* // get animation key
* var animation = sprite.animation();
*
* // set animation key
* sprite.animation('kicking');
*/
Factory.addGetterSetter(Sprite, 'animations');
/**
* get/set animations map
* @name Konva.Sprite#animations
* @method
* @param {Object} animations
* @returns {Object}
* @example
* // get animations map
* var animations = sprite.animations();
*
* // set animations map
* sprite.animations({
* standing: [
* // x, y, width, height (6 frames)
* 0, 0, 49, 109,
* 52, 0, 49, 109,
* 105, 0, 49, 109,
* 158, 0, 49, 109,
* 210, 0, 49, 109,
* 262, 0, 49, 109
* ],
* kicking: [
* // x, y, width, height (6 frames)
* 0, 109, 45, 98,
* 45, 109, 45, 98,
* 95, 109, 63, 98,
* 156, 109, 70, 98,
* 229, 109, 60, 98,
* 287, 109, 41, 98
* ]
* });
*/
Factory.addGetterSetter(Sprite, 'frameOffsets');
/**
* get/set offsets map
* @name Konva.Sprite#offsets
* @method
* @param {Object} offsets
* @returns {Object}
* @example
* // get offsets map
* var offsets = sprite.offsets();
*
* // set offsets map
* sprite.offsets({
* standing: [
* // x, y (6 frames)
* 0, 0,
* 0, 0,
* 5, 0,
* 0, 0,
* 0, 3,
* 2, 0
* ],
* kicking: [
* // x, y (6 frames)
* 0, 5,
* 5, 0,
* 10, 0,
* 0, 0,
* 2, 1,
* 0, 0
* ]
* });
*/
Factory.addGetterSetter(Sprite, 'image');
/**
* get/set image
* @name Konva.Sprite#image
* @method
* @param {Image} image
* @returns {Image}
* @example
* // get image
* var image = sprite.image();
*
* // set image
* sprite.image(imageObj);
*/
Factory.addGetterSetter(Sprite, 'frameIndex', 0, getNumberValidator());
/**
* set/set animation frame index
* @name Konva.Sprite#frameIndex
* @method
* @param {Integer} frameIndex
* @returns {Integer}
* @example
* // get animation frame index
* var frameIndex = sprite.frameIndex();
*
* // set animation frame index
* sprite.frameIndex(3);
*/
Factory.addGetterSetter(Sprite, 'frameRate', 17, getNumberValidator());
/**
* get/set frame rate in frames per second. Increase this number to make the sprite
* animation run faster, and decrease the number to make the sprite animation run slower
* The default is 17 frames per second
* @name Konva.Sprite#frameRate
* @method
* @param {Integer} frameRate
* @returns {Integer}
* @example
* // get frame rate
* var frameRate = sprite.frameRate();
*
* // set frame rate to 2 frames per second
* sprite.frameRate(2);
*/
Factory.backCompat(Sprite, {
index: 'frameIndex',
getIndex: 'getFrameIndex',
setIndex: 'setFrameIndex',
});
/**
* Star constructor
* @constructor
* @memberof Konva
* @augments Konva.Shape
* @param {Object} config
* @param {Integer} config.numPoints
* @param {Number} config.innerRadius
* @param {Number} config.outerRadius
* @param {String} [config.fill] fill color
* @param {Image} [config.fillPatternImage] fill pattern image
* @param {Number} [config.fillPatternX]
* @param {Number} [config.fillPatternY]
* @param {Object} [config.fillPatternOffset] object with x and y component
* @param {Number} [config.fillPatternOffsetX]
* @param {Number} [config.fillPatternOffsetY]
* @param {Object} [config.fillPatternScale] object with x and y component
* @param {Number} [config.fillPatternScaleX]
* @param {Number} [config.fillPatternScaleY]
* @param {Number} [config.fillPatternRotation]
* @param {String} [config.fillPatternRepeat] can be "repeat", "repeat-x", "repeat-y", or "no-repeat". The default is "no-repeat"
* @param {Object} [config.fillLinearGradientStartPoint] object with x and y component
* @param {Number} [config.fillLinearGradientStartPointX]
* @param {Number} [config.fillLinearGradientStartPointY]
* @param {Object} [config.fillLinearGradientEndPoint] object with x and y component
* @param {Number} [config.fillLinearGradientEndPointX]
* @param {Number} [config.fillLinearGradientEndPointY]
* @param {Array} [config.fillLinearGradientColorStops] array of color stops
* @param {Object} [config.fillRadialGradientStartPoint] object with x and y component
* @param {Number} [config.fillRadialGradientStartPointX]
* @param {Number} [config.fillRadialGradientStartPointY]
* @param {Object} [config.fillRadialGradientEndPoint] object with x and y component
* @param {Number} [config.fillRadialGradientEndPointX]
* @param {Number} [config.fillRadialGradientEndPointY]
* @param {Number} [config.fillRadialGradientStartRadius]
* @param {Number} [config.fillRadialGradientEndRadius]
* @param {Array} [config.fillRadialGradientColorStops] array of color stops
* @param {Boolean} [config.fillEnabled] flag which enables or disables the fill. The default value is true
* @param {String} [config.fillPriority] can be color, linear-gradient, radial-graident, or pattern. The default value is color. The fillPriority property makes it really easy to toggle between different fill types. For example, if you want to toggle between a fill color style and a fill pattern style, simply set the fill property and the fillPattern properties, and then use setFillPriority('color') to render the shape with a color fill, or use setFillPriority('pattern') to render the shape with the pattern fill configuration
* @param {String} [config.stroke] stroke color
* @param {Number} [config.strokeWidth] stroke width
* @param {Boolean} [config.fillAfterStrokeEnabled]. Should we draw fill AFTER stroke? Default is false.
* @param {Number} [config.hitStrokeWidth] size of the stroke on hit canvas. The default is "auto" - equals to strokeWidth
* @param {Boolean} [config.strokeHitEnabled] flag which enables or disables stroke hit region. The default is true
* @param {Boolean} [config.perfectDrawEnabled] flag which enables or disables using buffer canvas. The default is true
* @param {Boolean} [config.shadowForStrokeEnabled] flag which enables or disables shadow for stroke. The default is true
* @param {Boolean} [config.strokeScaleEnabled] flag which enables or disables stroke scale. The default is true
* @param {Boolean} [config.strokeEnabled] flag which enables or disables the stroke. The default value is true
* @param {String} [config.lineJoin] can be miter, round, or bevel. The default
* is miter
* @param {String} [config.lineCap] can be butt, round, or square. The default
* is butt
* @param {String} [config.shadowColor]
* @param {Number} [config.shadowBlur]
* @param {Object} [config.shadowOffset] object with x and y component
* @param {Number} [config.shadowOffsetX]
* @param {Number} [config.shadowOffsetY]
* @param {Number} [config.shadowOpacity] shadow opacity. Can be any real number
* between 0 and 1
* @param {Boolean} [config.shadowEnabled] flag which enables or disables the shadow. The default value is true
* @param {Array} [config.dash]
* @param {Boolean} [config.dashEnabled] flag which enables or disables the dashArray. The default value is true
* @param {Number} [config.x]
* @param {Number} [config.y]
* @param {Number} [config.width]
* @param {Number} [config.height]
* @param {Boolean} [config.visible]
* @param {Boolean} [config.listening] whether or not the node is listening for events
* @param {String} [config.id] unique id
* @param {String} [config.name] non-unique name
* @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1
* @param {Object} [config.scale] set scale
* @param {Number} [config.scaleX] set scale x
* @param {Number} [config.scaleY] set scale y
* @param {Number} [config.rotation] rotation in degrees
* @param {Object} [config.offset] offset from center point and rotation point
* @param {Number} [config.offsetX] set offset x
* @param {Number} [config.offsetY] set offset y
* @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop
* the entire stage by dragging any portion of the stage
* @param {Number} [config.dragDistance]
* @param {Function} [config.dragBoundFunc]
* @example
* var star = new Konva.Star({
* x: 100,
* y: 200,
* numPoints: 5,
* innerRadius: 70,
* outerRadius: 70,
* fill: 'red',
* stroke: 'black',
* strokeWidth: 4
* });
*/
class Star extends Shape {
_sceneFunc(context) {
var innerRadius = this.innerRadius(), outerRadius = this.outerRadius(), numPoints = this.numPoints();
context.beginPath();
context.moveTo(0, 0 - outerRadius);
for (var n = 1; n < numPoints * 2; n++) {
var radius = n % 2 === 0 ? outerRadius : innerRadius;
var x = radius * Math.sin((n * Math.PI) / numPoints);
var y = -1 * radius * Math.cos((n * Math.PI) / numPoints);
context.lineTo(x, y);
}
context.closePath();
context.fillStrokeShape(this);
}
getWidth() {
return this.outerRadius() * 2;
}
getHeight() {
return this.outerRadius() * 2;
}
setWidth(width) {
this.outerRadius(width / 2);
}
setHeight(height) {
this.outerRadius(height / 2);
}
}
Star.prototype.className = 'Star';
Star.prototype._centroid = true;
Star.prototype._attrsAffectingSize = ['innerRadius', 'outerRadius'];
_registerNode(Star);
/**
* get/set number of points
* @name Konva.Star#numPoints
* @method
* @param {Number} numPoints
* @returns {Number}
* @example
* // get inner radius
* var numPoints = star.numPoints();
*
* // set inner radius
* star.numPoints(20);
*/
Factory.addGetterSetter(Star, 'numPoints', 5, getNumberValidator());
/**
* get/set innerRadius
* @name Konva.Star#innerRadius
* @method
* @param {Number} innerRadius
* @returns {Number}
* @example
* // get inner radius
* var innerRadius = star.innerRadius();
*
* // set inner radius
* star.innerRadius(20);
*/
Factory.addGetterSetter(Star, 'innerRadius', 0, getNumberValidator());
/**
* get/set outerRadius
* @name Konva.Star#outerRadius
* @method
* @param {Number} outerRadius
* @returns {Number}
* @example
* // get inner radius
* var outerRadius = star.outerRadius();
*
* // set inner radius
* star.outerRadius(20);
*/
Factory.addGetterSetter(Star, 'outerRadius', 0, getNumberValidator());
function stringToArray(string) {
// we need to use `Array.from` because it can split unicode string correctly
// we also can use some regexp magic from lodash:
// https://github.com/lodash/lodash/blob/fb1f99d9d90ad177560d771bc5953a435b2dc119/lodash.toarray/index.js#L256
// but I decided it is too much code for that small fix
return Array.from(string);
}
// constants
var AUTO = 'auto',
//CANVAS = 'canvas',
CENTER = 'center', JUSTIFY = 'justify', CHANGE_KONVA = 'Change.konva', CONTEXT_2D = '2d', DASH = '-', LEFT = 'left', TEXT = 'text', TEXT_UPPER = 'Text', TOP = 'top', BOTTOM = 'bottom', MIDDLE = 'middle', NORMAL$1 = 'normal', PX_SPACE = 'px ', SPACE = ' ', RIGHT = 'right', WORD = 'word', CHAR = 'char', NONE = 'none', ELLIPSIS = '…', ATTR_CHANGE_LIST$1 = [
'fontFamily',
'fontSize',
'fontStyle',
'fontVariant',
'padding',
'align',
'verticalAlign',
'lineHeight',
'text',
'width',
'height',
'wrap',
'ellipsis',
'letterSpacing',
],
// cached variables
attrChangeListLen = ATTR_CHANGE_LIST$1.length;
function normalizeFontFamily(fontFamily) {
return fontFamily
.split(',')
.map((family) => {
family = family.trim();
const hasSpace = family.indexOf(' ') >= 0;
const hasQuotes = family.indexOf('"') >= 0 || family.indexOf("'") >= 0;
if (hasSpace && !hasQuotes) {
family = `"${family}"`;
}
return family;
})
.join(', ');
}
var dummyContext;
function getDummyContext() {
if (dummyContext) {
return dummyContext;
}
dummyContext = Util.createCanvasElement().getContext(CONTEXT_2D);
return dummyContext;
}
function _fillFunc$1(context) {
context.fillText(this._partialText, this._partialTextX, this._partialTextY);
}
function _strokeFunc$1(context) {
context.strokeText(this._partialText, this._partialTextX, this._partialTextY);
}
function checkDefaultFill(config) {
config = config || {};
// set default color to black
if (!config.fillLinearGradientColorStops &&
!config.fillRadialGradientColorStops &&
!config.fillPatternImage) {
config.fill = config.fill || 'black';
}
return config;
}
/**
* Text constructor
* @constructor
* @memberof Konva
* @augments Konva.Shape
* @param {Object} config
* @param {String} [config.fontFamily] default is Arial
* @param {Number} [config.fontSize] in pixels. Default is 12
* @param {String} [config.fontStyle] can be 'normal', 'bold', 'italic' or even 'italic bold'. Default is 'normal'
* @param {String} [config.fontVariant] can be normal or small-caps. Default is normal
* @param {String} [config.textDecoration] can be line-through, underline or empty string. Default is empty string.
* @param {String} config.text
* @param {String} [config.align] can be left, center, or right
* @param {String} [config.verticalAlign] can be top, middle or bottom
* @param {Number} [config.padding]
* @param {Number} [config.lineHeight] default is 1
* @param {String} [config.wrap] can be "word", "char", or "none". Default is word
* @param {Boolean} [config.ellipsis] can be true or false. Default is false. if Konva.Text config is set to wrap="none" and ellipsis=true, then it will add "..." to the end
* @param {String} [config.fill] fill color
* @param {Image} [config.fillPatternImage] fill pattern image
* @param {Number} [config.fillPatternX]
* @param {Number} [config.fillPatternY]
* @param {Object} [config.fillPatternOffset] object with x and y component
* @param {Number} [config.fillPatternOffsetX]
* @param {Number} [config.fillPatternOffsetY]
* @param {Object} [config.fillPatternScale] object with x and y component
* @param {Number} [config.fillPatternScaleX]
* @param {Number} [config.fillPatternScaleY]
* @param {Number} [config.fillPatternRotation]
* @param {String} [config.fillPatternRepeat] can be "repeat", "repeat-x", "repeat-y", or "no-repeat". The default is "no-repeat"
* @param {Object} [config.fillLinearGradientStartPoint] object with x and y component
* @param {Number} [config.fillLinearGradientStartPointX]
* @param {Number} [config.fillLinearGradientStartPointY]
* @param {Object} [config.fillLinearGradientEndPoint] object with x and y component
* @param {Number} [config.fillLinearGradientEndPointX]
* @param {Number} [config.fillLinearGradientEndPointY]
* @param {Array} [config.fillLinearGradientColorStops] array of color stops
* @param {Object} [config.fillRadialGradientStartPoint] object with x and y component
* @param {Number} [config.fillRadialGradientStartPointX]
* @param {Number} [config.fillRadialGradientStartPointY]
* @param {Object} [config.fillRadialGradientEndPoint] object with x and y component
* @param {Number} [config.fillRadialGradientEndPointX]
* @param {Number} [config.fillRadialGradientEndPointY]
* @param {Number} [config.fillRadialGradientStartRadius]
* @param {Number} [config.fillRadialGradientEndRadius]
* @param {Array} [config.fillRadialGradientColorStops] array of color stops
* @param {Boolean} [config.fillEnabled] flag which enables or disables the fill. The default value is true
* @param {String} [config.fillPriority] can be color, linear-gradient, radial-graident, or pattern. The default value is color. The fillPriority property makes it really easy to toggle between different fill types. For example, if you want to toggle between a fill color style and a fill pattern style, simply set the fill property and the fillPattern properties, and then use setFillPriority('color') to render the shape with a color fill, or use setFillPriority('pattern') to render the shape with the pattern fill configuration
* @param {String} [config.stroke] stroke color
* @param {Number} [config.strokeWidth] stroke width
* @param {Boolean} [config.fillAfterStrokeEnabled]. Should we draw fill AFTER stroke? Default is false.
* @param {Number} [config.hitStrokeWidth] size of the stroke on hit canvas. The default is "auto" - equals to strokeWidth
* @param {Boolean} [config.strokeHitEnabled] flag which enables or disables stroke hit region. The default is true
* @param {Boolean} [config.perfectDrawEnabled] flag which enables or disables using buffer canvas. The default is true
* @param {Boolean} [config.shadowForStrokeEnabled] flag which enables or disables shadow for stroke. The default is true
* @param {Boolean} [config.strokeScaleEnabled] flag which enables or disables stroke scale. The default is true
* @param {Boolean} [config.strokeEnabled] flag which enables or disables the stroke. The default value is true
* @param {String} [config.lineJoin] can be miter, round, or bevel. The default
* is miter
* @param {String} [config.lineCap] can be butt, round, or square. The default
* is butt
* @param {String} [config.shadowColor]
* @param {Number} [config.shadowBlur]
* @param {Object} [config.shadowOffset] object with x and y component
* @param {Number} [config.shadowOffsetX]
* @param {Number} [config.shadowOffsetY]
* @param {Number} [config.shadowOpacity] shadow opacity. Can be any real number
* between 0 and 1
* @param {Boolean} [config.shadowEnabled] flag which enables or disables the shadow. The default value is true
* @param {Array} [config.dash]
* @param {Boolean} [config.dashEnabled] flag which enables or disables the dashArray. The default value is true
* @param {Number} [config.x]
* @param {Number} [config.y]
* @param {Number} [config.width]
* @param {Number} [config.height]
* @param {Boolean} [config.visible]
* @param {Boolean} [config.listening] whether or not the node is listening for events
* @param {String} [config.id] unique id
* @param {String} [config.name] non-unique name
* @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1
* @param {Object} [config.scale] set scale
* @param {Number} [config.scaleX] set scale x
* @param {Number} [config.scaleY] set scale y
* @param {Number} [config.rotation] rotation in degrees
* @param {Object} [config.offset] offset from center point and rotation point
* @param {Number} [config.offsetX] set offset x
* @param {Number} [config.offsetY] set offset y
* @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop
* the entire stage by dragging any portion of the stage
* @param {Number} [config.dragDistance]
* @param {Function} [config.dragBoundFunc]
* @example
* var text = new Konva.Text({
* x: 10,
* y: 15,
* text: 'Simple Text',
* fontSize: 30,
* fontFamily: 'Calibri',
* fill: 'green'
* });
*/
class Text extends Shape {
constructor(config) {
super(checkDefaultFill(config));
this._partialTextX = 0;
this._partialTextY = 0;
// update text data for certain attr changes
for (var n = 0; n < attrChangeListLen; n++) {
this.on(ATTR_CHANGE_LIST$1[n] + CHANGE_KONVA, this._setTextData);
}
this._setTextData();
}
_sceneFunc(context) {
var textArr = this.textArr, textArrLen = textArr.length;
if (!this.text()) {
return;
}
var padding = this.padding(), fontSize = this.fontSize(), lineHeightPx = this.lineHeight() * fontSize, verticalAlign = this.verticalAlign(), alignY = 0, align = this.align(), totalWidth = this.getWidth(), letterSpacing = this.letterSpacing(), fill = this.fill(), textDecoration = this.textDecoration(), shouldUnderline = textDecoration.indexOf('underline') !== -1, shouldLineThrough = textDecoration.indexOf('line-through') !== -1, n;
var translateY = 0;
var translateY = lineHeightPx / 2;
var lineTranslateX = 0;
var lineTranslateY = 0;
context.setAttr('font', this._getContextFont());
context.setAttr('textBaseline', MIDDLE);
context.setAttr('textAlign', LEFT);
// handle vertical alignment
if (verticalAlign === MIDDLE) {
alignY = (this.getHeight() - textArrLen * lineHeightPx - padding * 2) / 2;
}
else if (verticalAlign === BOTTOM) {
alignY = this.getHeight() - textArrLen * lineHeightPx - padding * 2;
}
context.translate(padding, alignY + padding);
// draw text lines
for (n = 0; n < textArrLen; n++) {
var lineTranslateX = 0;
var lineTranslateY = 0;
var obj = textArr[n], text = obj.text, width = obj.width, lastLine = n !== textArrLen - 1, spacesNumber, oneWord, lineWidth;
// horizontal alignment
context.save();
if (align === RIGHT) {
lineTranslateX += totalWidth - width - padding * 2;
}
else if (align === CENTER) {
lineTranslateX += (totalWidth - width - padding * 2) / 2;
}
if (shouldUnderline) {
context.save();
context.beginPath();
context.moveTo(lineTranslateX, translateY + lineTranslateY + Math.round(fontSize / 2));
spacesNumber = text.split(' ').length - 1;
oneWord = spacesNumber === 0;
lineWidth =
align === JUSTIFY && lastLine && !oneWord
? totalWidth - padding * 2
: width;
context.lineTo(lineTranslateX + Math.round(lineWidth), translateY + lineTranslateY + Math.round(fontSize / 2));
// I have no idea what is real ratio
// just /15 looks good enough
context.lineWidth = fontSize / 15;
context.strokeStyle = fill;
context.stroke();
context.restore();
}
if (shouldLineThrough) {
context.save();
context.beginPath();
context.moveTo(lineTranslateX, translateY + lineTranslateY);
spacesNumber = text.split(' ').length - 1;
oneWord = spacesNumber === 0;
lineWidth =
align === JUSTIFY && lastLine && !oneWord
? totalWidth - padding * 2
: width;
context.lineTo(lineTranslateX + Math.round(lineWidth), translateY + lineTranslateY);
context.lineWidth = fontSize / 15;
context.strokeStyle = fill;
context.stroke();
context.restore();
}
if (letterSpacing !== 0 || align === JUSTIFY) {
// var words = text.split(' ');
spacesNumber = text.split(' ').length - 1;
var array = stringToArray(text);
for (var li = 0; li < array.length; li++) {
var letter = array[li];
// skip justify for the last line
if (letter === ' ' && n !== textArrLen - 1 && align === JUSTIFY) {
lineTranslateX += (totalWidth - padding * 2 - width) / spacesNumber;
// context.translate(
// Math.floor((totalWidth - padding * 2 - width) / spacesNumber),
// 0
// );
}
this._partialTextX = lineTranslateX;
this._partialTextY = translateY + lineTranslateY;
this._partialText = letter;
context.fillStrokeShape(this);
lineTranslateX += this.measureSize(letter).width + letterSpacing;
}
}
else {
this._partialTextX = lineTranslateX;
this._partialTextY = translateY + lineTranslateY;
this._partialText = text;
context.fillStrokeShape(this);
}
context.restore();
if (textArrLen > 1) {
translateY += lineHeightPx;
}
}
}
_hitFunc(context) {
var width = this.getWidth(), height = this.getHeight();
context.beginPath();
context.rect(0, 0, width, height);
context.closePath();
context.fillStrokeShape(this);
}
setText(text) {
var str = Util._isString(text)
? text
: text === null || text === undefined
? ''
: text + '';
this._setAttr(TEXT, str);
return this;
}
getWidth() {
var isAuto = this.attrs.width === AUTO || this.attrs.width === undefined;
return isAuto ? this.getTextWidth() + this.padding() * 2 : this.attrs.width;
}
getHeight() {
var isAuto = this.attrs.height === AUTO || this.attrs.height === undefined;
return isAuto
? this.fontSize() * this.textArr.length * this.lineHeight() +
this.padding() * 2
: this.attrs.height;
}
/**
* get pure text width without padding
* @method
* @name Konva.Text#getTextWidth
* @returns {Number}
*/
getTextWidth() {
return this.textWidth;
}
getTextHeight() {
Util.warn('text.getTextHeight() method is deprecated. Use text.height() - for full height and text.fontSize() - for one line height.');
return this.textHeight;
}
/**
* measure string with the font of current text shape.
* That method can't handle multiline text.
* @method
* @name Konva.Text#measureSize
* @param {String} [text] text to measure
* @returns {Object} { width , height} of measured text
*/
measureSize(text) {
var _context = getDummyContext(), fontSize = this.fontSize(), metrics;
_context.save();
_context.font = this._getContextFont();
metrics = _context.measureText(text);
_context.restore();
return {
width: metrics.width,
height: fontSize,
};
}
_getContextFont() {
return (this.fontStyle() +
SPACE +
this.fontVariant() +
SPACE +
(this.fontSize() + PX_SPACE) +
// wrap font family into " so font families with spaces works ok
normalizeFontFamily(this.fontFamily()));
}
_addTextLine(line) {
if (this.align() === JUSTIFY) {
line = line.trim();
}
var width = this._getTextWidth(line);
return this.textArr.push({ text: line, width: width });
}
_getTextWidth(text) {
var letterSpacing = this.letterSpacing();
var length = text.length;
return (getDummyContext().measureText(text).width +
(length ? letterSpacing * (length - 1) : 0));
}
_setTextData() {
var lines = this.text().split('\n'), fontSize = +this.fontSize(), textWidth = 0, lineHeightPx = this.lineHeight() * fontSize, width = this.attrs.width, height = this.attrs.height, fixedWidth = width !== AUTO && width !== undefined, fixedHeight = height !== AUTO && height !== undefined, padding = this.padding(), maxWidth = width - padding * 2, maxHeightPx = height - padding * 2, currentHeightPx = 0, wrap = this.wrap(),
// align = this.align(),
shouldWrap = wrap !== NONE, wrapAtWord = wrap !== CHAR && shouldWrap, shouldAddEllipsis = this.ellipsis();
this.textArr = [];
getDummyContext().font = this._getContextFont();
var additionalWidth = shouldAddEllipsis ? this._getTextWidth(ELLIPSIS) : 0;
for (var i = 0, max = lines.length; i < max; ++i) {
var line = lines[i];
var lineWidth = this._getTextWidth(line);
if (fixedWidth && lineWidth > maxWidth) {
/*
* if width is fixed and line does not fit entirely
* break the line into multiple fitting lines
*/
while (line.length > 0) {
/*
* use binary search to find the longest substring that
* that would fit in the specified width
*/
var low = 0, high = line.length, match = '', matchWidth = 0;
while (low < high) {
var mid = (low + high) >>> 1, substr = line.slice(0, mid + 1), substrWidth = this._getTextWidth(substr) + additionalWidth;
if (substrWidth <= maxWidth) {
low = mid + 1;
match = substr;
matchWidth = substrWidth;
}
else {
high = mid;
}
}
/*
* 'low' is now the index of the substring end
* 'match' is the substring
* 'matchWidth' is the substring width in px
*/
if (match) {
// a fitting substring was found
if (wrapAtWord) {
// try to find a space or dash where wrapping could be done
var wrapIndex;
var nextChar = line[match.length];
var nextIsSpaceOrDash = nextChar === SPACE || nextChar === DASH;
if (nextIsSpaceOrDash && matchWidth <= maxWidth) {
wrapIndex = match.length;
}
else {
wrapIndex =
Math.max(match.lastIndexOf(SPACE), match.lastIndexOf(DASH)) +
1;
}
if (wrapIndex > 0) {
// re-cut the substring found at the space/dash position
low = wrapIndex;
match = match.slice(0, low);
matchWidth = this._getTextWidth(match);
}
}
// if (align === 'right') {
match = match.trimRight();
// }
this._addTextLine(match);
textWidth = Math.max(textWidth, matchWidth);
currentHeightPx += lineHeightPx;
if (!shouldWrap ||
(fixedHeight && currentHeightPx + lineHeightPx > maxHeightPx)) {
var lastLine = this.textArr[this.textArr.length - 1];
if (lastLine) {
if (shouldAddEllipsis) {
var haveSpace = this._getTextWidth(lastLine.text + ELLIPSIS) < maxWidth;
if (!haveSpace) {
lastLine.text = lastLine.text.slice(0, lastLine.text.length - 3);
}
this.textArr.splice(this.textArr.length - 1, 1);
this._addTextLine(lastLine.text + ELLIPSIS);
}
}
/*
* stop wrapping if wrapping is disabled or if adding
* one more line would overflow the fixed height
*/
break;
}
line = line.slice(low);
line = line.trimLeft();
if (line.length > 0) {
// Check if the remaining text would fit on one line
lineWidth = this._getTextWidth(line);
if (lineWidth <= maxWidth) {
// if it does, add the line and break out of the loop
this._addTextLine(line);
currentHeightPx += lineHeightPx;
textWidth = Math.max(textWidth, lineWidth);
break;
}
}
}
else {
// not even one character could fit in the element, abort
break;
}
}
}
else {
// element width is automatically adjusted to max line width
this._addTextLine(line);
currentHeightPx += lineHeightPx;
textWidth = Math.max(textWidth, lineWidth);
}
// if element height is fixed, abort if adding one more line would overflow
if (fixedHeight && currentHeightPx + lineHeightPx > maxHeightPx) {
break;
}
}
this.textHeight = fontSize;
// var maxTextWidth = 0;
// for(var j = 0; j < this.textArr.length; j++) {
// maxTextWidth = Math.max(maxTextWidth, this.textArr[j].width);
// }
this.textWidth = textWidth;
}
// for text we can't disable stroke scaling
// if we do, the result will be unexpected
getStrokeScaleEnabled() {
return true;
}
}
Text.prototype._fillFunc = _fillFunc$1;
Text.prototype._strokeFunc = _strokeFunc$1;
Text.prototype.className = TEXT_UPPER;
Text.prototype._attrsAffectingSize = [
'text',
'fontSize',
'padding',
'wrap',
'lineHeight',
'letterSpacing',
];
_registerNode(Text);
/**
* get/set width of text area, which includes padding.
* @name Konva.Text#width
* @method
* @param {Number} width
* @returns {Number}
* @example
* // get width
* var width = text.width();
*
* // set width
* text.width(20);
*
* // set to auto
* text.width('auto');
* text.width() // will return calculated width, and not "auto"
*/
Factory.overWriteSetter(Text, 'width', getNumberOrAutoValidator());
/**
* get/set the height of the text area, which takes into account multi-line text, line heights, and padding.
* @name Konva.Text#height
* @method
* @param {Number} height
* @returns {Number}
* @example
* // get height
* var height = text.height();
*
* // set height
* text.height(20);
*
* // set to auto
* text.height('auto');
* text.height() // will return calculated height, and not "auto"
*/
Factory.overWriteSetter(Text, 'height', getNumberOrAutoValidator());
/**
* get/set font family
* @name Konva.Text#fontFamily
* @method
* @param {String} fontFamily
* @returns {String}
* @example
* // get font family
* var fontFamily = text.fontFamily();
*
* // set font family
* text.fontFamily('Arial');
*/
Factory.addGetterSetter(Text, 'fontFamily', 'Arial');
/**
* get/set font size in pixels
* @name Konva.Text#fontSize
* @method
* @param {Number} fontSize
* @returns {Number}
* @example
* // get font size
* var fontSize = text.fontSize();
*
* // set font size to 22px
* text.fontSize(22);
*/
Factory.addGetterSetter(Text, 'fontSize', 12, getNumberValidator());
/**
* get/set font style. Can be 'normal', 'italic', or 'bold' or even 'italic bold'. 'normal' is the default.
* @name Konva.Text#fontStyle
* @method
* @param {String} fontStyle
* @returns {String}
* @example
* // get font style
* var fontStyle = text.fontStyle();
*
* // set font style
* text.fontStyle('bold');
*/
Factory.addGetterSetter(Text, 'fontStyle', NORMAL$1);
/**
* get/set font variant. Can be 'normal' or 'small-caps'. 'normal' is the default.
* @name Konva.Text#fontVariant
* @method
* @param {String} fontVariant
* @returns {String}
* @example
* // get font variant
* var fontVariant = text.fontVariant();
*
* // set font variant
* text.fontVariant('small-caps');
*/
Factory.addGetterSetter(Text, 'fontVariant', NORMAL$1);
/**
* get/set padding
* @name Konva.Text#padding
* @method
* @param {Number} padding
* @returns {Number}
* @example
* // get padding
* var padding = text.padding();
*
* // set padding to 10 pixels
* text.padding(10);
*/
Factory.addGetterSetter(Text, 'padding', 0, getNumberValidator());
/**
* get/set horizontal align of text. Can be 'left', 'center', 'right' or 'justify'
* @name Konva.Text#align
* @method
* @param {String} align
* @returns {String}
* @example
* // get text align
* var align = text.align();
*
* // center text
* text.align('center');
*
* // align text to right
* text.align('right');
*/
Factory.addGetterSetter(Text, 'align', LEFT);
/**
* get/set vertical align of text. Can be 'top', 'middle', 'bottom'.
* @name Konva.Text#verticalAlign
* @method
* @param {String} verticalAlign
* @returns {String}
* @example
* // get text vertical align
* var verticalAlign = text.verticalAlign();
*
* // center text
* text.verticalAlign('middle');
*/
Factory.addGetterSetter(Text, 'verticalAlign', TOP);
/**
* get/set line height. The default is 1.
* @name Konva.Text#lineHeight
* @method
* @param {Number} lineHeight
* @returns {Number}
* @example
* // get line height
* var lineHeight = text.lineHeight();
*
* // set the line height
* text.lineHeight(2);
*/
Factory.addGetterSetter(Text, 'lineHeight', 1, getNumberValidator());
/**
* get/set wrap. Can be "word", "char", or "none". Default is "word".
* In "word" wrapping any word still can be wrapped if it can't be placed in the required width
* without breaks.
* @name Konva.Text#wrap
* @method
* @param {String} wrap
* @returns {String}
* @example
* // get wrap
* var wrap = text.wrap();
*
* // set wrap
* text.wrap('word');
*/
Factory.addGetterSetter(Text, 'wrap', WORD);
/**
* get/set ellipsis. Can be true or false. Default is false. If ellipses is true,
* Konva will add "..." at the end of the text if it doesn't have enough space to write characters.
* That is possible only when you limit both width and height of the text
* @name Konva.Text#ellipsis
* @method
* @param {Boolean} ellipsis
* @returns {Boolean}
* @example
* // get ellipsis param, returns true or false
* var ellipsis = text.ellipsis();
*
* // set ellipsis
* text.ellipsis(true);
*/
Factory.addGetterSetter(Text, 'ellipsis', false, getBooleanValidator());
/**
* set letter spacing property. Default value is 0.
* @name Konva.Text#letterSpacing
* @method
* @param {Number} letterSpacing
*/
Factory.addGetterSetter(Text, 'letterSpacing', 0, getNumberValidator());
/**
* get/set text
* @name Konva.Text#text
* @method
* @param {String} text
* @returns {String}
* @example
* // get text
* var text = text.text();
*
* // set text
* text.text('Hello world!');
*/
Factory.addGetterSetter(Text, 'text', '', getStringValidator());
/**
* get/set text decoration of a text. Possible values are 'underline', 'line-through' or combination of these values separated by space
* @name Konva.Text#textDecoration
* @method
* @param {String} textDecoration
* @returns {String}
* @example
* // get text decoration
* var textDecoration = text.textDecoration();
*
* // underline text
* text.textDecoration('underline');
*
* // strike text
* text.textDecoration('line-through');
*
* // underline and strike text
* text.textDecoration('underline line-through');
*/
Factory.addGetterSetter(Text, 'textDecoration', '');
var EMPTY_STRING = '', NORMAL = 'normal';
function _fillFunc(context) {
context.fillText(this.partialText, 0, 0);
}
function _strokeFunc(context) {
context.strokeText(this.partialText, 0, 0);
}
/**
* Path constructor.
* @author Jason Follas
* @constructor
* @memberof Konva
* @augments Konva.Shape
* @param {Object} config
* @param {String} [config.fontFamily] default is Arial
* @param {Number} [config.fontSize] default is 12
* @param {String} [config.fontStyle] can be normal, bold, or italic. Default is normal
* @param {String} [config.fontVariant] can be normal or small-caps. Default is normal
* @param {String} [config.textBaseline] Can be 'top', 'bottom', 'middle', 'alphabetic', 'hanging'. Default is middle
* @param {String} config.text
* @param {String} config.data SVG data string
* @param {Function} config.kerningFunc a getter for kerning values for the specified characters
* @param {String} [config.fill] fill color
* @param {Image} [config.fillPatternImage] fill pattern image
* @param {Number} [config.fillPatternX]
* @param {Number} [config.fillPatternY]
* @param {Object} [config.fillPatternOffset] object with x and y component
* @param {Number} [config.fillPatternOffsetX]
* @param {Number} [config.fillPatternOffsetY]
* @param {Object} [config.fillPatternScale] object with x and y component
* @param {Number} [config.fillPatternScaleX]
* @param {Number} [config.fillPatternScaleY]
* @param {Number} [config.fillPatternRotation]
* @param {String} [config.fillPatternRepeat] can be "repeat", "repeat-x", "repeat-y", or "no-repeat". The default is "no-repeat"
* @param {Object} [config.fillLinearGradientStartPoint] object with x and y component
* @param {Number} [config.fillLinearGradientStartPointX]
* @param {Number} [config.fillLinearGradientStartPointY]
* @param {Object} [config.fillLinearGradientEndPoint] object with x and y component
* @param {Number} [config.fillLinearGradientEndPointX]
* @param {Number} [config.fillLinearGradientEndPointY]
* @param {Array} [config.fillLinearGradientColorStops] array of color stops
* @param {Object} [config.fillRadialGradientStartPoint] object with x and y component
* @param {Number} [config.fillRadialGradientStartPointX]
* @param {Number} [config.fillRadialGradientStartPointY]
* @param {Object} [config.fillRadialGradientEndPoint] object with x and y component
* @param {Number} [config.fillRadialGradientEndPointX]
* @param {Number} [config.fillRadialGradientEndPointY]
* @param {Number} [config.fillRadialGradientStartRadius]
* @param {Number} [config.fillRadialGradientEndRadius]
* @param {Array} [config.fillRadialGradientColorStops] array of color stops
* @param {Boolean} [config.fillEnabled] flag which enables or disables the fill. The default value is true
* @param {String} [config.fillPriority] can be color, linear-gradient, radial-graident, or pattern. The default value is color. The fillPriority property makes it really easy to toggle between different fill types. For example, if you want to toggle between a fill color style and a fill pattern style, simply set the fill property and the fillPattern properties, and then use setFillPriority('color') to render the shape with a color fill, or use setFillPriority('pattern') to render the shape with the pattern fill configuration
* @param {String} [config.stroke] stroke color
* @param {Number} [config.strokeWidth] stroke width
* @param {Boolean} [config.fillAfterStrokeEnabled]. Should we draw fill AFTER stroke? Default is false.
* @param {Number} [config.hitStrokeWidth] size of the stroke on hit canvas. The default is "auto" - equals to strokeWidth
* @param {Boolean} [config.strokeHitEnabled] flag which enables or disables stroke hit region. The default is true
* @param {Boolean} [config.perfectDrawEnabled] flag which enables or disables using buffer canvas. The default is true
* @param {Boolean} [config.shadowForStrokeEnabled] flag which enables or disables shadow for stroke. The default is true
* @param {Boolean} [config.strokeScaleEnabled] flag which enables or disables stroke scale. The default is true
* @param {Boolean} [config.strokeEnabled] flag which enables or disables the stroke. The default value is true
* @param {String} [config.lineJoin] can be miter, round, or bevel. The default
* is miter
* @param {String} [config.lineCap] can be butt, round, or square. The default
* is butt
* @param {String} [config.shadowColor]
* @param {Number} [config.shadowBlur]
* @param {Object} [config.shadowOffset] object with x and y component
* @param {Number} [config.shadowOffsetX]
* @param {Number} [config.shadowOffsetY]
* @param {Number} [config.shadowOpacity] shadow opacity. Can be any real number
* between 0 and 1
* @param {Boolean} [config.shadowEnabled] flag which enables or disables the shadow. The default value is true
* @param {Array} [config.dash]
* @param {Boolean} [config.dashEnabled] flag which enables or disables the dashArray. The default value is true
* @param {Number} [config.x]
* @param {Number} [config.y]
* @param {Number} [config.width]
* @param {Number} [config.height]
* @param {Boolean} [config.visible]
* @param {Boolean} [config.listening] whether or not the node is listening for events
* @param {String} [config.id] unique id
* @param {String} [config.name] non-unique name
* @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1
* @param {Object} [config.scale] set scale
* @param {Number} [config.scaleX] set scale x
* @param {Number} [config.scaleY] set scale y
* @param {Number} [config.rotation] rotation in degrees
* @param {Object} [config.offset] offset from center point and rotation point
* @param {Number} [config.offsetX] set offset x
* @param {Number} [config.offsetY] set offset y
* @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop
* the entire stage by dragging any portion of the stage
* @param {Number} [config.dragDistance]
* @param {Function} [config.dragBoundFunc]
* @example
* var kerningPairs = {
* 'A': {
* ' ': -0.05517578125,
* 'T': -0.07421875,
* 'V': -0.07421875
* }
* 'V': {
* ',': -0.091796875,
* ":": -0.037109375,
* ";": -0.037109375,
* "A": -0.07421875
* }
* }
* var textpath = new Konva.TextPath({
* x: 100,
* y: 50,
* fill: '#333',
* fontSize: '24',
* fontFamily: 'Arial',
* text: 'All the world\'s a stage, and all the men and women merely players.',
* data: 'M10,10 C0,0 10,150 100,100 S300,150 400,50',
* kerningFunc(leftChar, rightChar) {
* return kerningPairs.hasOwnProperty(leftChar) ? pairs[leftChar][rightChar] || 0 : 0
* }
* });
*/
class TextPath extends Shape {
constructor(config) {
// call super constructor
super(config);
this.dummyCanvas = Util.createCanvasElement();
this.dataArray = [];
this.dataArray = Path.parsePathData(this.attrs.data);
this.on('dataChange.konva', function () {
this.dataArray = Path.parsePathData(this.attrs.data);
this._setTextData();
});
// update text data for certain attr changes
this.on('textChange.konva alignChange.konva letterSpacingChange.konva kerningFuncChange.konva fontSizeChange.konva', this._setTextData);
this._setTextData();
}
_sceneFunc(context) {
context.setAttr('font', this._getContextFont());
context.setAttr('textBaseline', this.textBaseline());
context.setAttr('textAlign', 'left');
context.save();
var textDecoration = this.textDecoration();
var fill = this.fill();
var fontSize = this.fontSize();
var glyphInfo = this.glyphInfo;
if (textDecoration === 'underline') {
context.beginPath();
}
for (var i = 0; i < glyphInfo.length; i++) {
context.save();
var p0 = glyphInfo[i].p0;
context.translate(p0.x, p0.y);
context.rotate(glyphInfo[i].rotation);
this.partialText = glyphInfo[i].text;
context.fillStrokeShape(this);
if (textDecoration === 'underline') {
if (i === 0) {
context.moveTo(0, fontSize / 2 + 1);
}
context.lineTo(fontSize, fontSize / 2 + 1);
}
context.restore();
//// To assist with debugging visually, uncomment following
//
// if (i % 2) context.strokeStyle = 'cyan';
// else context.strokeStyle = 'green';
// var p1 = glyphInfo[i].p1;
// context.moveTo(p0.x, p0.y);
// context.lineTo(p1.x, p1.y);
// context.stroke();
}
if (textDecoration === 'underline') {
context.strokeStyle = fill;
context.lineWidth = fontSize / 20;
context.stroke();
}
context.restore();
}
_hitFunc(context) {
context.beginPath();
var glyphInfo = this.glyphInfo;
if (glyphInfo.length >= 1) {
var p0 = glyphInfo[0].p0;
context.moveTo(p0.x, p0.y);
}
for (var i = 0; i < glyphInfo.length; i++) {
var p1 = glyphInfo[i].p1;
context.lineTo(p1.x, p1.y);
}
context.setAttr('lineWidth', this.fontSize());
context.setAttr('strokeStyle', this.colorKey);
context.stroke();
}
/**
* get text width in pixels
* @method
* @name Konva.TextPath#getTextWidth
*/
getTextWidth() {
return this.textWidth;
}
getTextHeight() {
Util.warn('text.getTextHeight() method is deprecated. Use text.height() - for full height and text.fontSize() - for one line height.');
return this.textHeight;
}
setText(text) {
return Text.prototype.setText.call(this, text);
}
_getContextFont() {
return Text.prototype._getContextFont.call(this);
}
_getTextSize(text) {
var dummyCanvas = this.dummyCanvas;
var _context = dummyCanvas.getContext('2d');
_context.save();
_context.font = this._getContextFont();
var metrics = _context.measureText(text);
_context.restore();
return {
width: metrics.width,
height: parseInt(this.attrs.fontSize, 10),
};
}
_setTextData() {
var that = this;
var size = this._getTextSize(this.attrs.text);
var letterSpacing = this.letterSpacing();
var align = this.align();
var kerningFunc = this.kerningFunc();
this.textWidth = size.width;
this.textHeight = size.height;
var textFullWidth = Math.max(this.textWidth + ((this.attrs.text || '').length - 1) * letterSpacing, 0);
this.glyphInfo = [];
var fullPathWidth = 0;
for (var l = 0; l < that.dataArray.length; l++) {
if (that.dataArray[l].pathLength > 0) {
fullPathWidth += that.dataArray[l].pathLength;
}
}
var offset = 0;
if (align === 'center') {
offset = Math.max(0, fullPathWidth / 2 - textFullWidth / 2);
}
if (align === 'right') {
offset = Math.max(0, fullPathWidth - textFullWidth);
}
var charArr = stringToArray(this.text());
var spacesNumber = this.text().split(' ').length - 1;
var p0, p1, pathCmd;
var pIndex = -1;
var currentT = 0;
// var sumLength = 0;
// for(var j = 0; j < that.dataArray.length; j++) {
// if(that.dataArray[j].pathLength > 0) {
//
// if (sumLength + that.dataArray[j].pathLength > offset) {}
// fullPathWidth += that.dataArray[j].pathLength;
// }
// }
var getNextPathSegment = function () {
currentT = 0;
var pathData = that.dataArray;
for (var j = pIndex + 1; j < pathData.length; j++) {
if (pathData[j].pathLength > 0) {
pIndex = j;
return pathData[j];
}
else if (pathData[j].command === 'M') {
p0 = {
x: pathData[j].points[0],
y: pathData[j].points[1],
};
}
}
return {};
};
var findSegmentToFitCharacter = function (c) {
var glyphWidth = that._getTextSize(c).width + letterSpacing;
if (c === ' ' && align === 'justify') {
glyphWidth += (fullPathWidth - textFullWidth) / spacesNumber;
}
var currLen = 0;
var attempts = 0;
p1 = undefined;
while (Math.abs(glyphWidth - currLen) / glyphWidth > 0.01 &&
attempts < 20) {
attempts++;
var cumulativePathLength = currLen;
while (pathCmd === undefined) {
pathCmd = getNextPathSegment();
if (pathCmd &&
cumulativePathLength + pathCmd.pathLength < glyphWidth) {
cumulativePathLength += pathCmd.pathLength;
pathCmd = undefined;
}
}
if (pathCmd === {} || p0 === undefined) {
return undefined;
}
var needNewSegment = false;
switch (pathCmd.command) {
case 'L':
if (Path.getLineLength(p0.x, p0.y, pathCmd.points[0], pathCmd.points[1]) > glyphWidth) {
p1 = Path.getPointOnLine(glyphWidth, p0.x, p0.y, pathCmd.points[0], pathCmd.points[1], p0.x, p0.y);
}
else {
pathCmd = undefined;
}
break;
case 'A':
var start = pathCmd.points[4];
// 4 = theta
var dTheta = pathCmd.points[5];
// 5 = dTheta
var end = pathCmd.points[4] + dTheta;
if (currentT === 0) {
currentT = start + 0.00000001;
}
else if (glyphWidth > currLen) {
// Just in case start is 0
currentT += ((Math.PI / 180.0) * dTheta) / Math.abs(dTheta);
}
else {
currentT -= ((Math.PI / 360.0) * dTheta) / Math.abs(dTheta);
}
// Credit for bug fix: @therth https://github.com/ericdrowell/KonvaJS/issues/249
// Old code failed to render text along arc of this path: "M 50 50 a 150 50 0 0 1 250 50 l 50 0"
if ((dTheta < 0 && currentT < end) ||
(dTheta >= 0 && currentT > end)) {
currentT = end;
needNewSegment = true;
}
p1 = Path.getPointOnEllipticalArc(pathCmd.points[0], pathCmd.points[1], pathCmd.points[2], pathCmd.points[3], currentT, pathCmd.points[6]);
break;
case 'C':
if (currentT === 0) {
if (glyphWidth > pathCmd.pathLength) {
currentT = 0.00000001;
}
else {
currentT = glyphWidth / pathCmd.pathLength;
}
}
else if (glyphWidth > currLen) {
currentT += (glyphWidth - currLen) / pathCmd.pathLength / 2;
}
else {
currentT = Math.max(currentT - (currLen - glyphWidth) / pathCmd.pathLength / 2, 0);
}
if (currentT > 1.0) {
currentT = 1.0;
needNewSegment = true;
}
p1 = Path.getPointOnCubicBezier(currentT, pathCmd.start.x, pathCmd.start.y, pathCmd.points[0], pathCmd.points[1], pathCmd.points[2], pathCmd.points[3], pathCmd.points[4], pathCmd.points[5]);
break;
case 'Q':
if (currentT === 0) {
currentT = glyphWidth / pathCmd.pathLength;
}
else if (glyphWidth > currLen) {
currentT += (glyphWidth - currLen) / pathCmd.pathLength;
}
else {
currentT -= (currLen - glyphWidth) / pathCmd.pathLength;
}
if (currentT > 1.0) {
currentT = 1.0;
needNewSegment = true;
}
p1 = Path.getPointOnQuadraticBezier(currentT, pathCmd.start.x, pathCmd.start.y, pathCmd.points[0], pathCmd.points[1], pathCmd.points[2], pathCmd.points[3]);
break;
}
if (p1 !== undefined) {
currLen = Path.getLineLength(p0.x, p0.y, p1.x, p1.y);
}
if (needNewSegment) {
needNewSegment = false;
pathCmd = undefined;
}
}
};
// fake search for offset, this is the best approach
var testChar = 'C';
var glyphWidth = that._getTextSize(testChar).width + letterSpacing;
var lettersInOffset = offset / glyphWidth - 1;
// the idea is simple
// try to draw testChar until we fill offset
for (var k = 0; k < lettersInOffset; k++) {
findSegmentToFitCharacter(testChar);
if (p0 === undefined || p1 === undefined) {
break;
}
p0 = p1;
}
for (var i = 0; i < charArr.length; i++) {
// Find p1 such that line segment between p0 and p1 is approx. width of glyph
findSegmentToFitCharacter(charArr[i]);
if (p0 === undefined || p1 === undefined) {
break;
}
var width = Path.getLineLength(p0.x, p0.y, p1.x, p1.y);
var kern = 0;
if (kerningFunc) {
try {
// getKerning is a user provided getter. Make sure it never breaks our logic
kern = kerningFunc(charArr[i - 1], charArr[i]) * this.fontSize();
}
catch (e) {
kern = 0;
}
}
p0.x += kern;
p1.x += kern;
this.textWidth += kern;
var midpoint = Path.getPointOnLine(kern + width / 2.0, p0.x, p0.y, p1.x, p1.y);
var rotation = Math.atan2(p1.y - p0.y, p1.x - p0.x);
this.glyphInfo.push({
transposeX: midpoint.x,
transposeY: midpoint.y,
text: charArr[i],
rotation: rotation,
p0: p0,
p1: p1,
});
p0 = p1;
}
}
getSelfRect() {
if (!this.glyphInfo.length) {
return {
x: 0,
y: 0,
width: 0,
height: 0,
};
}
var points = [];
this.glyphInfo.forEach(function (info) {
points.push(info.p0.x);
points.push(info.p0.y);
points.push(info.p1.x);
points.push(info.p1.y);
});
var minX = points[0] || 0;
var maxX = points[0] || 0;
var minY = points[1] || 0;
var maxY = points[1] || 0;
var x, y;
for (var i = 0; i < points.length / 2; i++) {
x = points[i * 2];
y = points[i * 2 + 1];
minX = Math.min(minX, x);
maxX = Math.max(maxX, x);
minY = Math.min(minY, y);
maxY = Math.max(maxY, y);
}
var fontSize = this.fontSize();
return {
x: minX - fontSize / 2,
y: minY - fontSize / 2,
width: maxX - minX + fontSize,
height: maxY - minY + fontSize,
};
}
}
TextPath.prototype._fillFunc = _fillFunc;
TextPath.prototype._strokeFunc = _strokeFunc;
TextPath.prototype._fillFuncHit = _fillFunc;
TextPath.prototype._strokeFuncHit = _strokeFunc;
TextPath.prototype.className = 'TextPath';
TextPath.prototype._attrsAffectingSize = ['text', 'fontSize', 'data'];
_registerNode(TextPath);
/**
* get/set SVG path data string. This method
* also automatically parses the data string
* into a data array. Currently supported SVG data:
* M, m, L, l, H, h, V, v, Q, q, T, t, C, c, S, s, A, a, Z, z
* @name Konva.TextPath#data
* @method
* @param {String} data svg path string
* @returns {String}
* @example
* // get data
* var data = shape.data();
*
* // set data
* shape.data('M200,100h100v50z');
*/
Factory.addGetterSetter(TextPath, 'data');
/**
* get/set font family
* @name Konva.TextPath#fontFamily
* @method
* @param {String} fontFamily
* @returns {String}
* @example
* // get font family
* var fontFamily = shape.fontFamily();
*
* // set font family
* shape.fontFamily('Arial');
*/
Factory.addGetterSetter(TextPath, 'fontFamily', 'Arial');
/**
* get/set font size in pixels
* @name Konva.TextPath#fontSize
* @method
* @param {Number} fontSize
* @returns {Number}
* @example
* // get font size
* var fontSize = shape.fontSize();
*
* // set font size to 22px
* shape.fontSize(22);
*/
Factory.addGetterSetter(TextPath, 'fontSize', 12, getNumberValidator());
/**
* get/set font style. Can be 'normal', 'italic', or 'bold'. 'normal' is the default.
* @name Konva.TextPath#fontStyle
* @method
* @param {String} fontStyle
* @returns {String}
* @example
* // get font style
* var fontStyle = shape.fontStyle();
*
* // set font style
* shape.fontStyle('bold');
*/
Factory.addGetterSetter(TextPath, 'fontStyle', NORMAL);
/**
* get/set horizontal align of text. Can be 'left', 'center', 'right' or 'justify'
* @name Konva.TextPath#align
* @method
* @param {String} align
* @returns {String}
* @example
* // get text align
* var align = text.align();
*
* // center text
* text.align('center');
*
* // align text to right
* text.align('right');
*/
Factory.addGetterSetter(TextPath, 'align', 'left');
/**
* get/set letter spacing. The default is 0.
* @name Konva.TextPath#letterSpacing
* @method
* @param {Number} letterSpacing
* @returns {Number}
* @example
* // get line height
* var letterSpacing = shape.letterSpacing();
*
* // set the line height
* shape.letterSpacing(2);
*/
Factory.addGetterSetter(TextPath, 'letterSpacing', 0, getNumberValidator());
/**
* get/set text baseline. The default is 'middle'. Can be 'top', 'bottom', 'middle', 'alphabetic', 'hanging'
* @name Konva.TextPath#textBaseline
* @method
* @param {String} textBaseline
* @returns {String}
* @example
* // get line height
* var textBaseline = shape.textBaseline();
*
* // set the line height
* shape.textBaseline('top');
*/
Factory.addGetterSetter(TextPath, 'textBaseline', 'middle');
/**
* get/set font variant. Can be 'normal' or 'small-caps'. 'normal' is the default.
* @name Konva.TextPath#fontVariant
* @method
* @param {String} fontVariant
* @returns {String}
* @example
* // get font variant
* var fontVariant = shape.fontVariant();
*
* // set font variant
* shape.fontVariant('small-caps');
*/
Factory.addGetterSetter(TextPath, 'fontVariant', NORMAL);
/**
* get/set text
* @name Konva.TextPath#getText
* @method
* @param {String} text
* @returns {String}
* @example
* // get text
* var text = text.text();
*
* // set text
* text.text('Hello world!');
*/
Factory.addGetterSetter(TextPath, 'text', EMPTY_STRING);
/**
* get/set text decoration of a text. Can be '' or 'underline'.
* @name Konva.TextPath#textDecoration
* @method
* @param {String} textDecoration
* @returns {String}
* @example
* // get text decoration
* var textDecoration = shape.textDecoration();
*
* // underline text
* shape.textDecoration('underline');
*/
Factory.addGetterSetter(TextPath, 'textDecoration', null);
/**
* get/set kerning function.
* @name Konva.TextPath#kerningFunc
* @method
* @param {String} kerningFunc
* @returns {String}
* @example
* // get text decoration
* var kerningFunc = text.kerningFunc();
*
* // center text
* text.kerningFunc(function(leftChar, rightChar) {
* return 1;
* });
*/
Factory.addGetterSetter(TextPath, 'kerningFunc', null);
var EVENTS_NAME = 'tr-konva';
var ATTR_CHANGE_LIST = [
'resizeEnabledChange',
'rotateAnchorOffsetChange',
'rotateEnabledChange',
'enabledAnchorsChange',
'anchorSizeChange',
'borderEnabledChange',
'borderStrokeChange',
'borderStrokeWidthChange',
'borderDashChange',
'anchorStrokeChange',
'anchorStrokeWidthChange',
'anchorFillChange',
'anchorCornerRadiusChange',
'ignoreStrokeChange',
]
.map((e) => e + `.${EVENTS_NAME}`)
.join(' ');
var NODES_RECT = 'nodesRect';
var TRANSFORM_CHANGE_STR = [
'widthChange',
'heightChange',
'scaleXChange',
'scaleYChange',
'skewXChange',
'skewYChange',
'rotationChange',
'offsetXChange',
'offsetYChange',
'transformsEnabledChange',
'strokeWidthChange',
];
var ANGLES = {
'top-left': -45,
'top-center': 0,
'top-right': 45,
'middle-right': -90,
'middle-left': 90,
'bottom-left': -135,
'bottom-center': 180,
'bottom-right': 135,
};
const TOUCH_DEVICE = 'ontouchstart' in Konva$2._global;
function getCursor(anchorName, rad) {
if (anchorName === 'rotater') {
return 'crosshair';
}
rad += Util.degToRad(ANGLES[anchorName] || 0);
var angle = ((Util.radToDeg(rad) % 360) + 360) % 360;
if (Util._inRange(angle, 315 + 22.5, 360) || Util._inRange(angle, 0, 22.5)) {
// TOP
return 'ns-resize';
}
else if (Util._inRange(angle, 45 - 22.5, 45 + 22.5)) {
// TOP - RIGHT
return 'nesw-resize';
}
else if (Util._inRange(angle, 90 - 22.5, 90 + 22.5)) {
// RIGHT
return 'ew-resize';
}
else if (Util._inRange(angle, 135 - 22.5, 135 + 22.5)) {
// BOTTOM - RIGHT
return 'nwse-resize';
}
else if (Util._inRange(angle, 180 - 22.5, 180 + 22.5)) {
// BOTTOM
return 'ns-resize';
}
else if (Util._inRange(angle, 225 - 22.5, 225 + 22.5)) {
// BOTTOM - LEFT
return 'nesw-resize';
}
else if (Util._inRange(angle, 270 - 22.5, 270 + 22.5)) {
// RIGHT
return 'ew-resize';
}
else if (Util._inRange(angle, 315 - 22.5, 315 + 22.5)) {
// BOTTOM - RIGHT
return 'nwse-resize';
}
else {
// how can we can there?
Util.error('Transformer has unknown angle for cursor detection: ' + angle);
return 'pointer';
}
}
var ANCHORS_NAMES = [
'top-left',
'top-center',
'top-right',
'middle-right',
'middle-left',
'bottom-left',
'bottom-center',
'bottom-right',
];
var MAX_SAFE_INTEGER = 100000000;
function getCenter(shape) {
return {
x: shape.x +
(shape.width / 2) * Math.cos(shape.rotation) +
(shape.height / 2) * Math.sin(-shape.rotation),
y: shape.y +
(shape.height / 2) * Math.cos(shape.rotation) +
(shape.width / 2) * Math.sin(shape.rotation),
};
}
function rotateAroundPoint(shape, angleRad, point) {
const x = point.x +
(shape.x - point.x) * Math.cos(angleRad) -
(shape.y - point.y) * Math.sin(angleRad);
const y = point.y +
(shape.x - point.x) * Math.sin(angleRad) +
(shape.y - point.y) * Math.cos(angleRad);
return Object.assign(Object.assign({}, shape), { rotation: shape.rotation + angleRad, x,
y });
}
function rotateAroundCenter(shape, deltaRad) {
const center = getCenter(shape);
return rotateAroundPoint(shape, deltaRad, center);
}
function getSnap(snaps, newRotationRad, tol) {
let snapped = newRotationRad;
for (let i = 0; i < snaps.length; i++) {
const angle = Konva$2.getAngle(snaps[i]);
const absDiff = Math.abs(angle - newRotationRad) % (Math.PI * 2);
const dif = Math.min(absDiff, Math.PI * 2 - absDiff);
if (dif < tol) {
snapped = angle;
}
}
return snapped;
}
/**
* Transformer constructor. Transformer is a special type of group that allow you transform Konva
* primitives and shapes. Transforming tool is not changing `width` and `height` properties of nodes
* when you resize them. Instead it changes `scaleX` and `scaleY` properties.
* @constructor
* @memberof Konva
* @param {Object} config
* @param {Boolean} [config.resizeEnabled] Default is true
* @param {Boolean} [config.rotateEnabled] Default is true
* @param {Array} [config.rotationSnaps] Array of angles for rotation snaps. Default is []
* @param {Number} [config.rotationSnapTolerance] Snapping tolerance. If closer than this it will snap. Default is 5
* @param {Number} [config.rotateAnchorOffset] Default is 50
* @param {Number} [config.padding] Default is 0
* @param {Boolean} [config.borderEnabled] Should we draw border? Default is true
* @param {String} [config.borderStroke] Border stroke color
* @param {Number} [config.borderStrokeWidth] Border stroke size
* @param {Array} [config.borderDash] Array for border dash.
* @param {String} [config.anchorFill] Anchor fill color
* @param {String} [config.anchorStroke] Anchor stroke color
* @param {String} [config.anchorCornerRadius] Anchor corner radius
* @param {Number} [config.anchorStrokeWidth] Anchor stroke size
* @param {Number} [config.anchorSize] Default is 10
* @param {Boolean} [config.keepRatio] Should we keep ratio when we are moving edges? Default is true
* @param {Boolean} [config.centeredScaling] Should we resize relative to node's center? Default is false
* @param {Array} [config.enabledAnchors] Array of names of enabled handles
* @param {Boolean} [config.flipEnabled] Can we flip/mirror shape on transform?. True by default
* @param {Function} [config.boundBoxFunc] Bounding box function
* @param {Function} [config.ignoreStroke] Should we ignore stroke size? Default is false
* @param {Boolean} [config.useSingleNodeRotation] When just one node attached, should we use its rotation for transformer?
* @param {Boolean} [config.shouldOverdrawWholeArea] Should we fill whole transformer area with fake transparent shape to enable dragging from empty spaces?
* @example
* var transformer = new Konva.Transformer({
* nodes: [rectangle],
* rotateAnchorOffset: 60,
* enabledAnchors: ['top-left', 'top-right', 'bottom-left', 'bottom-right']
* });
* layer.add(transformer);
*/
class Transformer extends Group {
constructor(config) {
// call super constructor
super(config);
this._transforming = false;
this._createElements();
// bindings
this._handleMouseMove = this._handleMouseMove.bind(this);
this._handleMouseUp = this._handleMouseUp.bind(this);
this.update = this.update.bind(this);
// update transformer data for certain attr changes
this.on(ATTR_CHANGE_LIST, this.update);
if (this.getNode()) {
this.update();
}
}
/**
* alias to `tr.nodes([shape])`/ This method is deprecated and will be removed soon.
* @method
* @name Konva.Transformer#attachTo
* @returns {Konva.Transformer}
* @example
* transformer.attachTo(shape);
*/
attachTo(node) {
this.setNode(node);
return this;
}
setNode(node) {
Util.warn('tr.setNode(shape), tr.node(shape) and tr.attachTo(shape) methods are deprecated. Please use tr.nodes(nodesArray) instead.');
return this.setNodes([node]);
}
getNode() {
return this._nodes && this._nodes[0];
}
_getEventNamespace() {
return EVENTS_NAME + this._id;
}
setNodes(nodes = []) {
if (this._nodes && this._nodes.length) {
this.detach();
}
this._nodes = nodes;
if (nodes.length === 1 && this.useSingleNodeRotation()) {
this.rotation(nodes[0].getAbsoluteRotation());
}
else {
this.rotation(0);
}
this._nodes.forEach((node) => {
const onChange = () => {
if (this.nodes().length === 1 && this.useSingleNodeRotation()) {
this.rotation(this.nodes()[0].getAbsoluteRotation());
}
this._resetTransformCache();
if (!this._transforming && !this.isDragging()) {
this.update();
}
};
const additionalEvents = node._attrsAffectingSize
.map((prop) => prop + 'Change.' + this._getEventNamespace())
.join(' ');
node.on(additionalEvents, onChange);
node.on(TRANSFORM_CHANGE_STR.map((e) => e + `.${this._getEventNamespace()}`).join(' '), onChange);
node.on(`absoluteTransformChange.${this._getEventNamespace()}`, onChange);
this._proxyDrag(node);
});
this._resetTransformCache();
// we may need it if we set node in initial props
// so elements are not defined yet
var elementsCreated = !!this.findOne('.top-left');
if (elementsCreated) {
this.update();
}
return this;
}
_proxyDrag(node) {
let lastPos;
node.on(`dragstart.${this._getEventNamespace()}`, (e) => {
lastPos = node.getAbsolutePosition();
// actual dragging of Transformer doesn't make sense
// but we need to make sure it also has all drag events
if (!this.isDragging() && node !== this.findOne('.back')) {
this.startDrag(e, false);
}
});
node.on(`dragmove.${this._getEventNamespace()}`, (e) => {
if (!lastPos) {
return;
}
const abs = node.getAbsolutePosition();
const dx = abs.x - lastPos.x;
const dy = abs.y - lastPos.y;
this.nodes().forEach((otherNode) => {
if (otherNode === node) {
return;
}
if (otherNode.isDragging()) {
return;
}
const otherAbs = otherNode.getAbsolutePosition();
otherNode.setAbsolutePosition({
x: otherAbs.x + dx,
y: otherAbs.y + dy,
});
otherNode.startDrag(e);
});
lastPos = null;
});
}
getNodes() {
return this._nodes || [];
}
/**
* return the name of current active anchor
* @method
* @name Konva.Transformer#getActiveAnchor
* @returns {String | Null}
* @example
* transformer.getActiveAnchor();
*/
getActiveAnchor() {
return this._movingAnchorName;
}
/**
* detach transformer from an attached node
* @method
* @name Konva.Transformer#detach
* @returns {Konva.Transformer}
* @example
* transformer.detach();
*/
detach() {
// remove events
if (this._nodes) {
this._nodes.forEach((node) => {
node.off('.' + this._getEventNamespace());
});
}
this._nodes = [];
this._resetTransformCache();
}
_resetTransformCache() {
this._clearCache(NODES_RECT);
this._clearCache('transform');
this._clearSelfAndDescendantCache('absoluteTransform');
}
_getNodeRect() {
return this._getCache(NODES_RECT, this.__getNodeRect);
}
// return absolute rotated bounding rectangle
__getNodeShape(node, rot = this.rotation(), relative) {
var rect = node.getClientRect({
skipTransform: true,
skipShadow: true,
skipStroke: this.ignoreStroke(),
});
var absScale = node.getAbsoluteScale(relative);
var absPos = node.getAbsolutePosition(relative);
var dx = rect.x * absScale.x - node.offsetX() * absScale.x;
var dy = rect.y * absScale.y - node.offsetY() * absScale.y;
const rotation = (Konva$2.getAngle(node.getAbsoluteRotation()) + Math.PI * 2) %
(Math.PI * 2);
const box = {
x: absPos.x + dx * Math.cos(rotation) + dy * Math.sin(-rotation),
y: absPos.y + dy * Math.cos(rotation) + dx * Math.sin(rotation),
width: rect.width * absScale.x,
height: rect.height * absScale.y,
rotation: rotation,
};
return rotateAroundPoint(box, -Konva$2.getAngle(rot), {
x: 0,
y: 0,
});
}
// returns box + rotation of all shapes
__getNodeRect() {
var node = this.getNode();
if (!node) {
return {
x: -MAX_SAFE_INTEGER,
y: -MAX_SAFE_INTEGER,
width: 0,
height: 0,
rotation: 0,
};
}
const totalPoints = [];
this.nodes().map((node) => {
const box = node.getClientRect({
skipTransform: true,
skipShadow: true,
skipStroke: this.ignoreStroke(),
});
var points = [
{ x: box.x, y: box.y },
{ x: box.x + box.width, y: box.y },
{ x: box.x + box.width, y: box.y + box.height },
{ x: box.x, y: box.y + box.height },
];
var trans = node.getAbsoluteTransform();
points.forEach(function (point) {
var transformed = trans.point(point);
totalPoints.push(transformed);
});
});
const tr = new Transform();
tr.rotate(-Konva$2.getAngle(this.rotation()));
var minX, minY, maxX, maxY;
totalPoints.forEach(function (point) {
var transformed = tr.point(point);
if (minX === undefined) {
minX = maxX = transformed.x;
minY = maxY = transformed.y;
}
minX = Math.min(minX, transformed.x);
minY = Math.min(minY, transformed.y);
maxX = Math.max(maxX, transformed.x);
maxY = Math.max(maxY, transformed.y);
});
tr.invert();
const p = tr.point({ x: minX, y: minY });
return {
x: p.x,
y: p.y,
width: maxX - minX,
height: maxY - minY,
rotation: Konva$2.getAngle(this.rotation()),
};
// const shapes = this.nodes().map(node => {
// return this.__getNodeShape(node);
// });
// const box = getShapesRect(shapes);
// return rotateAroundPoint(box, Konva.getAngle(this.rotation()), {
// x: 0,
// y: 0
// });
}
getX() {
return this._getNodeRect().x;
}
getY() {
return this._getNodeRect().y;
}
getWidth() {
return this._getNodeRect().width;
}
getHeight() {
return this._getNodeRect().height;
}
_createElements() {
this._createBack();
ANCHORS_NAMES.forEach(function (name) {
this._createAnchor(name);
}.bind(this));
this._createAnchor('rotater');
}
_createAnchor(name) {
var anchor = new Rect({
stroke: 'rgb(0, 161, 255)',
fill: 'white',
strokeWidth: 1,
name: name + ' _anchor',
dragDistance: 0,
// make it draggable,
// so activating the anchor will not start drag&drop of any parent
draggable: true,
hitStrokeWidth: TOUCH_DEVICE ? 10 : 'auto',
});
var self = this;
anchor.on('mousedown touchstart', function (e) {
self._handleMouseDown(e);
});
anchor.on('dragstart', (e) => {
anchor.stopDrag();
e.cancelBubble = true;
});
anchor.on('dragend', (e) => {
e.cancelBubble = true;
});
// add hover styling
anchor.on('mouseenter', () => {
var rad = Konva$2.getAngle(this.rotation());
var cursor = getCursor(name, rad);
anchor.getStage().content &&
(anchor.getStage().content.style.cursor = cursor);
this._cursorChange = true;
});
anchor.on('mouseout', () => {
anchor.getStage().content &&
(anchor.getStage().content.style.cursor = '');
this._cursorChange = false;
});
this.add(anchor);
}
_createBack() {
var back = new Shape({
name: 'back',
width: 0,
height: 0,
draggable: true,
sceneFunc(ctx) {
var tr = this.getParent();
var padding = tr.padding();
ctx.beginPath();
ctx.rect(-padding, -padding, this.width() + padding * 2, this.height() + padding * 2);
ctx.moveTo(this.width() / 2, -padding);
if (tr.rotateEnabled()) {
ctx.lineTo(this.width() / 2, -tr.rotateAnchorOffset() * Util._sign(this.height()) - padding);
}
ctx.fillStrokeShape(this);
},
hitFunc: (ctx, shape) => {
if (!this.shouldOverdrawWholeArea()) {
return;
}
var padding = this.padding();
ctx.beginPath();
ctx.rect(-padding, -padding, shape.width() + padding * 2, shape.height() + padding * 2);
ctx.fillStrokeShape(shape);
},
});
this.add(back);
this._proxyDrag(back);
// do not bubble drag from the back shape
// because we already "drag" whole transformer
// so we don't want to trigger drag twice on transformer
back.on('dragstart', (e) => {
e.cancelBubble = true;
});
back.on('dragmove', (e) => {
e.cancelBubble = true;
});
back.on('dragend', (e) => {
e.cancelBubble = true;
});
// force self update when we drag with shouldOverDrawWholeArea setting
this.on('dragmove', (e) => {
this.update();
});
}
_handleMouseDown(e) {
this._movingAnchorName = e.target.name().split(' ')[0];
var attrs = this._getNodeRect();
var width = attrs.width;
var height = attrs.height;
var hypotenuse = Math.sqrt(Math.pow(width, 2) + Math.pow(height, 2));
this.sin = Math.abs(height / hypotenuse);
this.cos = Math.abs(width / hypotenuse);
if (typeof window !== 'undefined') {
window.addEventListener('mousemove', this._handleMouseMove);
window.addEventListener('touchmove', this._handleMouseMove);
window.addEventListener('mouseup', this._handleMouseUp, true);
window.addEventListener('touchend', this._handleMouseUp, true);
}
this._transforming = true;
var ap = e.target.getAbsolutePosition();
var pos = e.target.getStage().getPointerPosition();
this._anchorDragOffset = {
x: pos.x - ap.x,
y: pos.y - ap.y,
};
this._fire('transformstart', { evt: e, target: this.getNode() });
this._nodes.forEach((target) => {
target._fire('transformstart', { evt: e, target });
});
}
_handleMouseMove(e) {
var x, y, newHypotenuse;
var anchorNode = this.findOne('.' + this._movingAnchorName);
var stage = anchorNode.getStage();
stage.setPointersPositions(e);
const pp = stage.getPointerPosition();
let newNodePos = {
x: pp.x - this._anchorDragOffset.x,
y: pp.y - this._anchorDragOffset.y,
};
const oldAbs = anchorNode.getAbsolutePosition();
if (this.anchorDragBoundFunc()) {
newNodePos = this.anchorDragBoundFunc()(oldAbs, newNodePos, e);
}
anchorNode.setAbsolutePosition(newNodePos);
const newAbs = anchorNode.getAbsolutePosition();
// console.log(oldAbs, newNodePos, newAbs);
if (oldAbs.x === newAbs.x && oldAbs.y === newAbs.y) {
return;
}
// rotater is working very differently, so do it first
if (this._movingAnchorName === 'rotater') {
var attrs = this._getNodeRect();
x = anchorNode.x() - attrs.width / 2;
y = -anchorNode.y() + attrs.height / 2;
// hor angle is changed?
let delta = Math.atan2(-y, x) + Math.PI / 2;
if (attrs.height < 0) {
delta -= Math.PI;
}
var oldRotation = Konva$2.getAngle(this.rotation());
const newRotation = oldRotation + delta;
const tol = Konva$2.getAngle(this.rotationSnapTolerance());
const snappedRot = getSnap(this.rotationSnaps(), newRotation, tol);
const diff = snappedRot - attrs.rotation;
const shape = rotateAroundCenter(attrs, diff);
this._fitNodesInto(shape, e);
return;
}
var keepProportion = this.keepRatio() || e.shiftKey;
var centeredScaling = this.centeredScaling() || e.altKey;
if (this._movingAnchorName === 'top-left') {
if (keepProportion) {
var comparePoint = centeredScaling
? {
x: this.width() / 2,
y: this.height() / 2,
}
: {
x: this.findOne('.bottom-right').x(),
y: this.findOne('.bottom-right').y(),
};
newHypotenuse = Math.sqrt(Math.pow(comparePoint.x - anchorNode.x(), 2) +
Math.pow(comparePoint.y - anchorNode.y(), 2));
var reverseX = this.findOne('.top-left').x() > comparePoint.x ? -1 : 1;
var reverseY = this.findOne('.top-left').y() > comparePoint.y ? -1 : 1;
x = newHypotenuse * this.cos * reverseX;
y = newHypotenuse * this.sin * reverseY;
this.findOne('.top-left').x(comparePoint.x - x);
this.findOne('.top-left').y(comparePoint.y - y);
}
}
else if (this._movingAnchorName === 'top-center') {
this.findOne('.top-left').y(anchorNode.y());
}
else if (this._movingAnchorName === 'top-right') {
if (keepProportion) {
var comparePoint = centeredScaling
? {
x: this.width() / 2,
y: this.height() / 2,
}
: {
x: this.findOne('.bottom-left').x(),
y: this.findOne('.bottom-left').y(),
};
newHypotenuse = Math.sqrt(Math.pow(anchorNode.x() - comparePoint.x, 2) +
Math.pow(comparePoint.y - anchorNode.y(), 2));
var reverseX = this.findOne('.top-right').x() < comparePoint.x ? -1 : 1;
var reverseY = this.findOne('.top-right').y() > comparePoint.y ? -1 : 1;
x = newHypotenuse * this.cos * reverseX;
y = newHypotenuse * this.sin * reverseY;
this.findOne('.top-right').x(comparePoint.x + x);
this.findOne('.top-right').y(comparePoint.y - y);
}
var pos = anchorNode.position();
this.findOne('.top-left').y(pos.y);
this.findOne('.bottom-right').x(pos.x);
}
else if (this._movingAnchorName === 'middle-left') {
this.findOne('.top-left').x(anchorNode.x());
}
else if (this._movingAnchorName === 'middle-right') {
this.findOne('.bottom-right').x(anchorNode.x());
}
else if (this._movingAnchorName === 'bottom-left') {
if (keepProportion) {
var comparePoint = centeredScaling
? {
x: this.width() / 2,
y: this.height() / 2,
}
: {
x: this.findOne('.top-right').x(),
y: this.findOne('.top-right').y(),
};
newHypotenuse = Math.sqrt(Math.pow(comparePoint.x - anchorNode.x(), 2) +
Math.pow(anchorNode.y() - comparePoint.y, 2));
var reverseX = comparePoint.x < anchorNode.x() ? -1 : 1;
var reverseY = anchorNode.y() < comparePoint.y ? -1 : 1;
x = newHypotenuse * this.cos * reverseX;
y = newHypotenuse * this.sin * reverseY;
anchorNode.x(comparePoint.x - x);
anchorNode.y(comparePoint.y + y);
}
pos = anchorNode.position();
this.findOne('.top-left').x(pos.x);
this.findOne('.bottom-right').y(pos.y);
}
else if (this._movingAnchorName === 'bottom-center') {
this.findOne('.bottom-right').y(anchorNode.y());
}
else if (this._movingAnchorName === 'bottom-right') {
if (keepProportion) {
var comparePoint = centeredScaling
? {
x: this.width() / 2,
y: this.height() / 2,
}
: {
x: this.findOne('.top-left').x(),
y: this.findOne('.top-left').y(),
};
newHypotenuse = Math.sqrt(Math.pow(anchorNode.x() - comparePoint.x, 2) +
Math.pow(anchorNode.y() - comparePoint.y, 2));
var reverseX = this.findOne('.bottom-right').x() < comparePoint.x ? -1 : 1;
var reverseY = this.findOne('.bottom-right').y() < comparePoint.y ? -1 : 1;
x = newHypotenuse * this.cos * reverseX;
y = newHypotenuse * this.sin * reverseY;
this.findOne('.bottom-right').x(comparePoint.x + x);
this.findOne('.bottom-right').y(comparePoint.y + y);
}
}
else {
console.error(new Error('Wrong position argument of selection resizer: ' +
this._movingAnchorName));
}
var centeredScaling = this.centeredScaling() || e.altKey;
if (centeredScaling) {
var topLeft = this.findOne('.top-left');
var bottomRight = this.findOne('.bottom-right');
var topOffsetX = topLeft.x();
var topOffsetY = topLeft.y();
var bottomOffsetX = this.getWidth() - bottomRight.x();
var bottomOffsetY = this.getHeight() - bottomRight.y();
bottomRight.move({
x: -topOffsetX,
y: -topOffsetY,
});
topLeft.move({
x: bottomOffsetX,
y: bottomOffsetY,
});
}
var absPos = this.findOne('.top-left').getAbsolutePosition();
x = absPos.x;
y = absPos.y;
var width = this.findOne('.bottom-right').x() - this.findOne('.top-left').x();
var height = this.findOne('.bottom-right').y() - this.findOne('.top-left').y();
this._fitNodesInto({
x: x,
y: y,
width: width,
height: height,
rotation: Konva$2.getAngle(this.rotation()),
}, e);
}
_handleMouseUp(e) {
this._removeEvents(e);
}
getAbsoluteTransform() {
return this.getTransform();
}
_removeEvents(e) {
if (this._transforming) {
this._transforming = false;
if (typeof window !== 'undefined') {
window.removeEventListener('mousemove', this._handleMouseMove);
window.removeEventListener('touchmove', this._handleMouseMove);
window.removeEventListener('mouseup', this._handleMouseUp, true);
window.removeEventListener('touchend', this._handleMouseUp, true);
}
var node = this.getNode();
this._fire('transformend', { evt: e, target: node });
if (node) {
this._nodes.forEach((target) => {
target._fire('transformend', { evt: e, target });
});
}
this._movingAnchorName = null;
}
}
_fitNodesInto(newAttrs, evt) {
var oldAttrs = this._getNodeRect();
const minSize = 1;
if (Util._inRange(newAttrs.width, -this.padding() * 2 - minSize, minSize)) {
this.update();
return;
}
if (Util._inRange(newAttrs.height, -this.padding() * 2 - minSize, minSize)) {
this.update();
return;
}
const allowNegativeScale = this.flipEnabled();
var t = new Transform();
t.rotate(Konva$2.getAngle(this.rotation()));
if (this._movingAnchorName &&
newAttrs.width < 0 &&
this._movingAnchorName.indexOf('left') >= 0) {
const offset = t.point({
x: -this.padding() * 2,
y: 0,
});
newAttrs.x += offset.x;
newAttrs.y += offset.y;
newAttrs.width += this.padding() * 2;
this._movingAnchorName = this._movingAnchorName.replace('left', 'right');
this._anchorDragOffset.x -= offset.x;
this._anchorDragOffset.y -= offset.y;
if (!allowNegativeScale) {
this.update();
return;
}
}
else if (this._movingAnchorName &&
newAttrs.width < 0 &&
this._movingAnchorName.indexOf('right') >= 0) {
const offset = t.point({
x: this.padding() * 2,
y: 0,
});
this._movingAnchorName = this._movingAnchorName.replace('right', 'left');
this._anchorDragOffset.x -= offset.x;
this._anchorDragOffset.y -= offset.y;
newAttrs.width += this.padding() * 2;
if (!allowNegativeScale) {
this.update();
return;
}
}
if (this._movingAnchorName &&
newAttrs.height < 0 &&
this._movingAnchorName.indexOf('top') >= 0) {
const offset = t.point({
x: 0,
y: -this.padding() * 2,
});
newAttrs.x += offset.x;
newAttrs.y += offset.y;
this._movingAnchorName = this._movingAnchorName.replace('top', 'bottom');
this._anchorDragOffset.x -= offset.x;
this._anchorDragOffset.y -= offset.y;
newAttrs.height += this.padding() * 2;
if (!allowNegativeScale) {
this.update();
return;
}
}
else if (this._movingAnchorName &&
newAttrs.height < 0 &&
this._movingAnchorName.indexOf('bottom') >= 0) {
const offset = t.point({
x: 0,
y: this.padding() * 2,
});
this._movingAnchorName = this._movingAnchorName.replace('bottom', 'top');
this._anchorDragOffset.x -= offset.x;
this._anchorDragOffset.y -= offset.y;
newAttrs.height += this.padding() * 2;
if (!allowNegativeScale) {
this.update();
return;
}
}
if (this.boundBoxFunc()) {
const bounded = this.boundBoxFunc()(oldAttrs, newAttrs);
if (bounded) {
newAttrs = bounded;
}
else {
Util.warn('boundBoxFunc returned falsy. You should return new bound rect from it!');
}
}
// base size value doesn't really matter
// we just need to think about bounding boxes as transforms
// but how?
// the idea is that we have a transformed rectangle with the size of "baseSize"
const baseSize = 10000000;
const oldTr = new Transform();
oldTr.translate(oldAttrs.x, oldAttrs.y);
oldTr.rotate(oldAttrs.rotation);
oldTr.scale(oldAttrs.width / baseSize, oldAttrs.height / baseSize);
const newTr = new Transform();
newTr.translate(newAttrs.x, newAttrs.y);
newTr.rotate(newAttrs.rotation);
newTr.scale(newAttrs.width / baseSize, newAttrs.height / baseSize);
// now lets think we had [old transform] and n ow we have [new transform]
// Now, the questions is: how can we transform "parent" to go from [old transform] into [new transform]
// in equation it will be:
// [delta transform] * [old transform] = [new transform]
// that means that
// [delta transform] = [new transform] * [old transform inverted]
const delta = newTr.multiply(oldTr.invert());
this._nodes.forEach((node) => {
var _a;
// for each node we have the same [delta transform]
// the equations is
// [delta transform] * [parent transform] * [old local transform] = [parent transform] * [new local transform]
// and we need to find [new local transform]
// [new local] = [parent inverted] * [delta] * [parent] * [old local]
const parentTransform = node.getParent().getAbsoluteTransform();
const localTransform = node.getTransform().copy();
// skip offset:
localTransform.translate(node.offsetX(), node.offsetY());
const newLocalTransform = new Transform();
newLocalTransform
.multiply(parentTransform.copy().invert())
.multiply(delta)
.multiply(parentTransform)
.multiply(localTransform);
const attrs = newLocalTransform.decompose();
node.setAttrs(attrs);
this._fire('transform', { evt: evt, target: node });
node._fire('transform', { evt: evt, target: node });
(_a = node.getLayer()) === null || _a === void 0 ? void 0 : _a.batchDraw();
});
this.rotation(Util._getRotation(newAttrs.rotation));
this._resetTransformCache();
this.update();
this.getLayer().batchDraw();
}
/**
* force update of Konva.Transformer.
* Use it when you updated attached Konva.Group and now you need to reset transformer size
* @method
* @name Konva.Transformer#forceUpdate
*/
forceUpdate() {
this._resetTransformCache();
this.update();
}
_batchChangeChild(selector, attrs) {
const anchor = this.findOne(selector);
anchor.setAttrs(attrs);
}
update() {
var _a;
var attrs = this._getNodeRect();
this.rotation(Util._getRotation(attrs.rotation));
var width = attrs.width;
var height = attrs.height;
var enabledAnchors = this.enabledAnchors();
var resizeEnabled = this.resizeEnabled();
var padding = this.padding();
var anchorSize = this.anchorSize();
this.find('._anchor').forEach((node) => {
node.setAttrs({
width: anchorSize,
height: anchorSize,
offsetX: anchorSize / 2,
offsetY: anchorSize / 2,
stroke: this.anchorStroke(),
strokeWidth: this.anchorStrokeWidth(),
fill: this.anchorFill(),
cornerRadius: this.anchorCornerRadius(),
});
});
this._batchChangeChild('.top-left', {
x: 0,
y: 0,
offsetX: anchorSize / 2 + padding,
offsetY: anchorSize / 2 + padding,
visible: resizeEnabled && enabledAnchors.indexOf('top-left') >= 0,
});
this._batchChangeChild('.top-center', {
x: width / 2,
y: 0,
offsetY: anchorSize / 2 + padding,
visible: resizeEnabled && enabledAnchors.indexOf('top-center') >= 0,
});
this._batchChangeChild('.top-right', {
x: width,
y: 0,
offsetX: anchorSize / 2 - padding,
offsetY: anchorSize / 2 + padding,
visible: resizeEnabled && enabledAnchors.indexOf('top-right') >= 0,
});
this._batchChangeChild('.middle-left', {
x: 0,
y: height / 2,
offsetX: anchorSize / 2 + padding,
visible: resizeEnabled && enabledAnchors.indexOf('middle-left') >= 0,
});
this._batchChangeChild('.middle-right', {
x: width,
y: height / 2,
offsetX: anchorSize / 2 - padding,
visible: resizeEnabled && enabledAnchors.indexOf('middle-right') >= 0,
});
this._batchChangeChild('.bottom-left', {
x: 0,
y: height,
offsetX: anchorSize / 2 + padding,
offsetY: anchorSize / 2 - padding,
visible: resizeEnabled && enabledAnchors.indexOf('bottom-left') >= 0,
});
this._batchChangeChild('.bottom-center', {
x: width / 2,
y: height,
offsetY: anchorSize / 2 - padding,
visible: resizeEnabled && enabledAnchors.indexOf('bottom-center') >= 0,
});
this._batchChangeChild('.bottom-right', {
x: width,
y: height,
offsetX: anchorSize / 2 - padding,
offsetY: anchorSize / 2 - padding,
visible: resizeEnabled && enabledAnchors.indexOf('bottom-right') >= 0,
});
this._batchChangeChild('.rotater', {
x: width / 2,
y: -this.rotateAnchorOffset() * Util._sign(height) - padding,
visible: this.rotateEnabled(),
});
this._batchChangeChild('.back', {
width: width,
height: height,
visible: this.borderEnabled(),
stroke: this.borderStroke(),
strokeWidth: this.borderStrokeWidth(),
dash: this.borderDash(),
x: 0,
y: 0,
});
(_a = this.getLayer()) === null || _a === void 0 ? void 0 : _a.batchDraw();
}
/**
* determine if transformer is in active transform
* @method
* @name Konva.Transformer#isTransforming
* @returns {Boolean}
*/
isTransforming() {
return this._transforming;
}
/**
* Stop active transform action
* @method
* @name Konva.Transformer#stopTransform
* @returns {Boolean}
*/
stopTransform() {
if (this._transforming) {
this._removeEvents();
var anchorNode = this.findOne('.' + this._movingAnchorName);
if (anchorNode) {
anchorNode.stopDrag();
}
}
}
destroy() {
if (this.getStage() && this._cursorChange) {
this.getStage().content && (this.getStage().content.style.cursor = '');
}
Group.prototype.destroy.call(this);
this.detach();
this._removeEvents();
return this;
}
// do not work as a container
// we will recreate inner nodes manually
toObject() {
return Node.prototype.toObject.call(this);
}
}
function validateAnchors(val) {
if (!(val instanceof Array)) {
Util.warn('enabledAnchors value should be an array');
}
if (val instanceof Array) {
val.forEach(function (name) {
if (ANCHORS_NAMES.indexOf(name) === -1) {
Util.warn('Unknown anchor name: ' +
name +
'. Available names are: ' +
ANCHORS_NAMES.join(', '));
}
});
}
return val || [];
}
Transformer.prototype.className = 'Transformer';
_registerNode(Transformer);
/**
* get/set enabled handlers
* @name Konva.Transformer#enabledAnchors
* @method
* @param {Array} array
* @returns {Array}
* @example
* // get list of handlers
* var enabledAnchors = transformer.enabledAnchors();
*
* // set handlers
* transformer.enabledAnchors(['top-left', 'top-center', 'top-right', 'middle-right', 'middle-left', 'bottom-left', 'bottom-center', 'bottom-right']);
*/
Factory.addGetterSetter(Transformer, 'enabledAnchors', ANCHORS_NAMES, validateAnchors);
/**
* get/set flip enabled
* @name Konva.Transformer#flipEnabled
* @method
* @param {Boolean} flag
* @returns {Boolean}
* @example
* // get flip enabled property
* var flipEnabled = transformer.flipEnabled();
*
* // set flip enabled property
* transformer.flipEnabled(false);
*/
Factory.addGetterSetter(Transformer, 'flipEnabled', true, getBooleanValidator());
/**
* get/set resize ability. If false it will automatically hide resizing handlers
* @name Konva.Transformer#resizeEnabled
* @method
* @param {Array} array
* @returns {Array}
* @example
* // get
* var resizeEnabled = transformer.resizeEnabled();
*
* // set
* transformer.resizeEnabled(false);
*/
Factory.addGetterSetter(Transformer, 'resizeEnabled', true);
/**
* get/set anchor size. Default is 10
* @name Konva.Transformer#validateAnchors
* @method
* @param {Number} 10
* @returns {Number}
* @example
* // get
* var anchorSize = transformer.anchorSize();
*
* // set
* transformer.anchorSize(20)
*/
Factory.addGetterSetter(Transformer, 'anchorSize', 10, getNumberValidator());
/**
* get/set ability to rotate.
* @name Konva.Transformer#rotateEnabled
* @method
* @param {Boolean} enabled
* @returns {Boolean}
* @example
* // get
* var rotateEnabled = transformer.rotateEnabled();
*
* // set
* transformer.rotateEnabled(false);
*/
Factory.addGetterSetter(Transformer, 'rotateEnabled', true);
/**
* get/set rotation snaps angles.
* @name Konva.Transformer#rotationSnaps
* @method
* @param {Array} array
* @returns {Array}
* @example
* // get
* var rotationSnaps = transformer.rotationSnaps();
*
* // set
* transformer.rotationSnaps([0, 90, 180, 270]);
*/
Factory.addGetterSetter(Transformer, 'rotationSnaps', []);
/**
* get/set distance for rotation handler
* @name Konva.Transformer#rotateAnchorOffset
* @method
* @param {Number} offset
* @returns {Number}
* @example
* // get
* var rotateAnchorOffset = transformer.rotateAnchorOffset();
*
* // set
* transformer.rotateAnchorOffset(100);
*/
Factory.addGetterSetter(Transformer, 'rotateAnchorOffset', 50, getNumberValidator());
/**
* get/set distance for rotation tolerance
* @name Konva.Transformer#rotationSnapTolerance
* @method
* @param {Number} tolerance
* @returns {Number}
* @example
* // get
* var rotationSnapTolerance = transformer.rotationSnapTolerance();
*
* // set
* transformer.rotationSnapTolerance(100);
*/
Factory.addGetterSetter(Transformer, 'rotationSnapTolerance', 5, getNumberValidator());
/**
* get/set visibility of border
* @name Konva.Transformer#borderEnabled
* @method
* @param {Boolean} enabled
* @returns {Boolean}
* @example
* // get
* var borderEnabled = transformer.borderEnabled();
*
* // set
* transformer.borderEnabled(false);
*/
Factory.addGetterSetter(Transformer, 'borderEnabled', true);
/**
* get/set anchor stroke color
* @name Konva.Transformer#anchorStroke
* @method
* @param {Boolean} enabled
* @returns {Boolean}
* @example
* // get
* var anchorStroke = transformer.anchorStroke();
*
* // set
* transformer.anchorStroke('red');
*/
Factory.addGetterSetter(Transformer, 'anchorStroke', 'rgb(0, 161, 255)');
/**
* get/set anchor stroke width
* @name Konva.Transformer#anchorStrokeWidth
* @method
* @param {Boolean} enabled
* @returns {Boolean}
* @example
* // get
* var anchorStrokeWidth = transformer.anchorStrokeWidth();
*
* // set
* transformer.anchorStrokeWidth(3);
*/
Factory.addGetterSetter(Transformer, 'anchorStrokeWidth', 1, getNumberValidator());
/**
* get/set anchor fill color
* @name Konva.Transformer#anchorFill
* @method
* @param {Boolean} enabled
* @returns {Boolean}
* @example
* // get
* var anchorFill = transformer.anchorFill();
*
* // set
* transformer.anchorFill('red');
*/
Factory.addGetterSetter(Transformer, 'anchorFill', 'white');
/**
* get/set anchor corner radius
* @name Konva.Transformer#anchorCornerRadius
* @method
* @param {Number} enabled
* @returns {Number}
* @example
* // get
* var anchorCornerRadius = transformer.anchorCornerRadius();
*
* // set
* transformer.anchorCornerRadius(3);
*/
Factory.addGetterSetter(Transformer, 'anchorCornerRadius', 0, getNumberValidator());
/**
* get/set border stroke color
* @name Konva.Transformer#borderStroke
* @method
* @param {Boolean} enabled
* @returns {Boolean}
* @example
* // get
* var borderStroke = transformer.borderStroke();
*
* // set
* transformer.borderStroke('red');
*/
Factory.addGetterSetter(Transformer, 'borderStroke', 'rgb(0, 161, 255)');
/**
* get/set border stroke width
* @name Konva.Transformer#borderStrokeWidth
* @method
* @param {Boolean} enabled
* @returns {Boolean}
* @example
* // get
* var borderStrokeWidth = transformer.borderStrokeWidth();
*
* // set
* transformer.borderStrokeWidth(3);
*/
Factory.addGetterSetter(Transformer, 'borderStrokeWidth', 1, getNumberValidator());
/**
* get/set border dash array
* @name Konva.Transformer#borderDash
* @method
* @param {Boolean} enabled
* @returns {Boolean}
* @example
* // get
* var borderDash = transformer.borderDash();
*
* // set
* transformer.borderDash([2, 2]);
*/
Factory.addGetterSetter(Transformer, 'borderDash');
/**
* get/set should we keep ratio while resize anchors at corners
* @name Konva.Transformer#keepRatio
* @method
* @param {Boolean} keepRatio
* @returns {Boolean}
* @example
* // get
* var keepRatio = transformer.keepRatio();
*
* // set
* transformer.keepRatio(false);
*/
Factory.addGetterSetter(Transformer, 'keepRatio', true);
/**
* get/set should we resize relative to node's center?
* @name Konva.Transformer#centeredScaling
* @method
* @param {Boolean} centeredScaling
* @returns {Boolean}
* @example
* // get
* var centeredScaling = transformer.centeredScaling();
*
* // set
* transformer.centeredScaling(true);
*/
Factory.addGetterSetter(Transformer, 'centeredScaling', false);
/**
* get/set should we think about stroke while resize? Good to use when a shape has strokeScaleEnabled = false
* default is false
* @name Konva.Transformer#ignoreStroke
* @method
* @param {Boolean} ignoreStroke
* @returns {Boolean}
* @example
* // get
* var ignoreStroke = transformer.ignoreStroke();
*
* // set
* transformer.ignoreStroke(true);
*/
Factory.addGetterSetter(Transformer, 'ignoreStroke', false);
/**
* get/set padding
* @name Konva.Transformer#padding
* @method
* @param {Number} padding
* @returns {Number}
* @example
* // get
* var padding = transformer.padding();
*
* // set
* transformer.padding(10);
*/
Factory.addGetterSetter(Transformer, 'padding', 0, getNumberValidator());
Factory.addGetterSetter(Transformer, 'node');
/**
* get/set attached nodes of the Transformer. Transformer will adapt to their size and listen to their events
* @method
* @name Konva.Transformer#nodes
* @returns {Konva.Node}
* @example
* // get
* const nodes = transformer.nodes();
*
* // set
* transformer.nodes([rect, circle]);
*
* // push new item:
* const oldNodes = transformer.nodes();
* const newNodes = oldNodes.concat([newShape]);
* // it is important to set new array instance (and concat method above will create it)
* transformer.nodes(newNodes);
*/
Factory.addGetterSetter(Transformer, 'nodes');
/**
* get/set bounding box function. **IMPORTANT!** boundBondFunc operates in absolute coordinates.
* @name Konva.Transformer#boundBoxFunc
* @method
* @param {Function} func
* @returns {Function}
* @example
* // get
* var boundBoxFunc = transformer.boundBoxFunc();
*
* // set
* transformer.boundBoxFunc(function(oldBox, newBox) {
* // width and height of the boxes are corresponding to total absolute width and height of all nodes combined
* // so it includes scale of the node.
* if (newBox.width > 200) {
* return oldBox;
* }
* return newBox;
* });
*/
Factory.addGetterSetter(Transformer, 'boundBoxFunc');
/**
* get/set dragging func for transformer anchors
* @name Konva.Transformer#anchorDragBoundFunc
* @method
* @param {Function} func
* @returns {Function}
* @example
* // get
* var anchorDragBoundFunc = transformer.anchorDragBoundFunc();
*
* // set
* transformer.anchorDragBoundFunc(function(oldAbsPos, newAbsPos, event) {
* return {
* x: 0,
* y: newAbsolutePosition.y
* }
* });
*/
Factory.addGetterSetter(Transformer, 'anchorDragBoundFunc');
/**
* using this setting you can drag transformer group by dragging empty space between attached nodes
* shouldOverdrawWholeArea = true may temporary disable all events on attached nodes
* @name Konva.Transformer#shouldOverdrawWholeArea
* @method
* @param {Boolean} shouldOverdrawWholeArea
* @returns {Boolean}
* @example
* // get
* var shouldOverdrawWholeArea = transformer.shouldOverdrawWholeArea();
*
* // set
* transformer.shouldOverdrawWholeArea(true);
*/
Factory.addGetterSetter(Transformer, 'shouldOverdrawWholeArea', false);
/**
* If you have just one attached node to Transformer it will set its initial rotation to the rotation of that node.
* In some cases you may need to set a different rotation.
* @name Konva.Transformer#useSingleNodeRotation
* @method
* @param {Boolean} useSingleNodeRotation
* @returns {Boolean}
* @example
* // set flag to false
* transformer.useSingleNodeRotation(false);
* // attach a shape
* transformer.nodes([shape]);
* transformer.rotation(45);
* transformer.update();
*/
Factory.addGetterSetter(Transformer, 'useSingleNodeRotation', true);
Factory.backCompat(Transformer, {
lineEnabled: 'borderEnabled',
rotateHandlerOffset: 'rotateAnchorOffset',
enabledHandlers: 'enabledAnchors',
});
/**
* Wedge constructor
* @constructor
* @memberof Konva
* @augments Konva.Shape
* @param {Object} config
* @param {Number} config.angle in degrees
* @param {Number} config.radius
* @param {Boolean} [config.clockwise]
* @param {String} [config.fill] fill color
* @param {Image} [config.fillPatternImage] fill pattern image
* @param {Number} [config.fillPatternX]
* @param {Number} [config.fillPatternY]
* @param {Object} [config.fillPatternOffset] object with x and y component
* @param {Number} [config.fillPatternOffsetX]
* @param {Number} [config.fillPatternOffsetY]
* @param {Object} [config.fillPatternScale] object with x and y component
* @param {Number} [config.fillPatternScaleX]
* @param {Number} [config.fillPatternScaleY]
* @param {Number} [config.fillPatternRotation]
* @param {String} [config.fillPatternRepeat] can be "repeat", "repeat-x", "repeat-y", or "no-repeat". The default is "no-repeat"
* @param {Object} [config.fillLinearGradientStartPoint] object with x and y component
* @param {Number} [config.fillLinearGradientStartPointX]
* @param {Number} [config.fillLinearGradientStartPointY]
* @param {Object} [config.fillLinearGradientEndPoint] object with x and y component
* @param {Number} [config.fillLinearGradientEndPointX]
* @param {Number} [config.fillLinearGradientEndPointY]
* @param {Array} [config.fillLinearGradientColorStops] array of color stops
* @param {Object} [config.fillRadialGradientStartPoint] object with x and y component
* @param {Number} [config.fillRadialGradientStartPointX]
* @param {Number} [config.fillRadialGradientStartPointY]
* @param {Object} [config.fillRadialGradientEndPoint] object with x and y component
* @param {Number} [config.fillRadialGradientEndPointX]
* @param {Number} [config.fillRadialGradientEndPointY]
* @param {Number} [config.fillRadialGradientStartRadius]
* @param {Number} [config.fillRadialGradientEndRadius]
* @param {Array} [config.fillRadialGradientColorStops] array of color stops
* @param {Boolean} [config.fillEnabled] flag which enables or disables the fill. The default value is true
* @param {String} [config.fillPriority] can be color, linear-gradient, radial-graident, or pattern. The default value is color. The fillPriority property makes it really easy to toggle between different fill types. For example, if you want to toggle between a fill color style and a fill pattern style, simply set the fill property and the fillPattern properties, and then use setFillPriority('color') to render the shape with a color fill, or use setFillPriority('pattern') to render the shape with the pattern fill configuration
* @param {String} [config.stroke] stroke color
* @param {Number} [config.strokeWidth] stroke width
* @param {Boolean} [config.fillAfterStrokeEnabled]. Should we draw fill AFTER stroke? Default is false.
* @param {Number} [config.hitStrokeWidth] size of the stroke on hit canvas. The default is "auto" - equals to strokeWidth
* @param {Boolean} [config.strokeHitEnabled] flag which enables or disables stroke hit region. The default is true
* @param {Boolean} [config.perfectDrawEnabled] flag which enables or disables using buffer canvas. The default is true
* @param {Boolean} [config.shadowForStrokeEnabled] flag which enables or disables shadow for stroke. The default is true
* @param {Boolean} [config.strokeScaleEnabled] flag which enables or disables stroke scale. The default is true
* @param {Boolean} [config.strokeEnabled] flag which enables or disables the stroke. The default value is true
* @param {String} [config.lineJoin] can be miter, round, or bevel. The default
* is miter
* @param {String} [config.lineCap] can be butt, round, or square. The default
* is butt
* @param {String} [config.shadowColor]
* @param {Number} [config.shadowBlur]
* @param {Object} [config.shadowOffset] object with x and y component
* @param {Number} [config.shadowOffsetX]
* @param {Number} [config.shadowOffsetY]
* @param {Number} [config.shadowOpacity] shadow opacity. Can be any real number
* between 0 and 1
* @param {Boolean} [config.shadowEnabled] flag which enables or disables the shadow. The default value is true
* @param {Array} [config.dash]
* @param {Boolean} [config.dashEnabled] flag which enables or disables the dashArray. The default value is true
* @param {Number} [config.x]
* @param {Number} [config.y]
* @param {Number} [config.width]
* @param {Number} [config.height]
* @param {Boolean} [config.visible]
* @param {Boolean} [config.listening] whether or not the node is listening for events
* @param {String} [config.id] unique id
* @param {String} [config.name] non-unique name
* @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1
* @param {Object} [config.scale] set scale
* @param {Number} [config.scaleX] set scale x
* @param {Number} [config.scaleY] set scale y
* @param {Number} [config.rotation] rotation in degrees
* @param {Object} [config.offset] offset from center point and rotation point
* @param {Number} [config.offsetX] set offset x
* @param {Number} [config.offsetY] set offset y
* @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop
* the entire stage by dragging any portion of the stage
* @param {Number} [config.dragDistance]
* @param {Function} [config.dragBoundFunc]
* @example
* // draw a wedge that's pointing downwards
* var wedge = new Konva.Wedge({
* radius: 40,
* fill: 'red',
* stroke: 'black'
* strokeWidth: 5,
* angleDeg: 60,
* rotationDeg: -120
* });
*/
class Wedge extends Shape {
_sceneFunc(context) {
context.beginPath();
context.arc(0, 0, this.radius(), 0, Konva$2.getAngle(this.angle()), this.clockwise());
context.lineTo(0, 0);
context.closePath();
context.fillStrokeShape(this);
}
getWidth() {
return this.radius() * 2;
}
getHeight() {
return this.radius() * 2;
}
setWidth(width) {
this.radius(width / 2);
}
setHeight(height) {
this.radius(height / 2);
}
}
Wedge.prototype.className = 'Wedge';
Wedge.prototype._centroid = true;
Wedge.prototype._attrsAffectingSize = ['radius'];
_registerNode(Wedge);
/**
* get/set radius
* @name Konva.Wedge#radius
* @method
* @param {Number} radius
* @returns {Number}
* @example
* // get radius
* var radius = wedge.radius();
*
* // set radius
* wedge.radius(10);
*/
Factory.addGetterSetter(Wedge, 'radius', 0, getNumberValidator());
/**
* get/set angle in degrees
* @name Konva.Wedge#angle
* @method
* @param {Number} angle
* @returns {Number}
* @example
* // get angle
* var angle = wedge.angle();
*
* // set angle
* wedge.angle(20);
*/
Factory.addGetterSetter(Wedge, 'angle', 0, getNumberValidator());
/**
* get/set clockwise flag
* @name Konva.Wedge#clockwise
* @method
* @param {Number} clockwise
* @returns {Number}
* @example
* // get clockwise flag
* var clockwise = wedge.clockwise();
*
* // draw wedge counter-clockwise
* wedge.clockwise(false);
*
* // draw wedge clockwise
* wedge.clockwise(true);
*/
Factory.addGetterSetter(Wedge, 'clockwise', false);
Factory.backCompat(Wedge, {
angleDeg: 'angle',
getAngleDeg: 'getAngle',
setAngleDeg: 'setAngle',
});
/*
the Gauss filter
master repo: https://github.com/pavelpower/kineticjsGaussFilter
*/
/*
StackBlur - a fast almost Gaussian Blur For Canvas
Version: 0.5
Author: Mario Klingemann
Contact: mario@quasimondo.com
Website: http://www.quasimondo.com/StackBlurForCanvas
Twitter: @quasimondo
In case you find this class useful - especially in commercial projects -
I am not totally unhappy for a small donation to my PayPal account
mario@quasimondo.de
Or support me on flattr:
https://flattr.com/thing/72791/StackBlur-a-fast-almost-Gaussian-Blur-Effect-for-CanvasJavascript
Copyright (c) 2010 Mario Klingemann
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.
*/
function BlurStack() {
this.r = 0;
this.g = 0;
this.b = 0;
this.a = 0;
this.next = null;
}
var mul_table = [
512,
512,
456,
512,
328,
456,
335,
512,
405,
328,
271,
456,
388,
335,
292,
512,
454,
405,
364,
328,
298,
271,
496,
456,
420,
388,
360,
335,
312,
292,
273,
512,
482,
454,
428,
405,
383,
364,
345,
328,
312,
298,
284,
271,
259,
496,
475,
456,
437,
420,
404,
388,
374,
360,
347,
335,
323,
312,
302,
292,
282,
273,
265,
512,
497,
482,
468,
454,
441,
428,
417,
405,
394,
383,
373,
364,
354,
345,
337,
328,
320,
312,
305,
298,
291,
284,
278,
271,
265,
259,
507,
496,
485,
475,
465,
456,
446,
437,
428,
420,
412,
404,
396,
388,
381,
374,
367,
360,
354,
347,
341,
335,
329,
323,
318,
312,
307,
302,
297,
292,
287,
282,
278,
273,
269,
265,
261,
512,
505,
497,
489,
482,
475,
468,
461,
454,
447,
441,
435,
428,
422,
417,
411,
405,
399,
394,
389,
383,
378,
373,
368,
364,
359,
354,
350,
345,
341,
337,
332,
328,
324,
320,
316,
312,
309,
305,
301,
298,
294,
291,
287,
284,
281,
278,
274,
271,
268,
265,
262,
259,
257,
507,
501,
496,
491,
485,
480,
475,
470,
465,
460,
456,
451,
446,
442,
437,
433,
428,
424,
420,
416,
412,
408,
404,
400,
396,
392,
388,
385,
381,
377,
374,
370,
367,
363,
360,
357,
354,
350,
347,
344,
341,
338,
335,
332,
329,
326,
323,
320,
318,
315,
312,
310,
307,
304,
302,
299,
297,
294,
292,
289,
287,
285,
282,
280,
278,
275,
273,
271,
269,
267,
265,
263,
261,
259,
];
var shg_table = [
9,
11,
12,
13,
13,
14,
14,
15,
15,
15,
15,
16,
16,
16,
16,
17,
17,
17,
17,
17,
17,
17,
18,
18,
18,
18,
18,
18,
18,
18,
18,
19,
19,
19,
19,
19,
19,
19,
19,
19,
19,
19,
19,
19,
19,
20,
20,
20,
20,
20,
20,
20,
20,
20,
20,
20,
20,
20,
20,
20,
20,
20,
20,
21,
21,
21,
21,
21,
21,
21,
21,
21,
21,
21,
21,
21,
21,
21,
21,
21,
21,
21,
21,
21,
21,
21,
21,
21,
21,
21,
22,
22,
22,
22,
22,
22,
22,
22,
22,
22,
22,
22,
22,
22,
22,
22,
22,
22,
22,
22,
22,
22,
22,
22,
22,
22,
22,
22,
22,
22,
22,
22,
22,
22,
22,
22,
22,
23,
23,
23,
23,
23,
23,
23,
23,
23,
23,
23,
23,
23,
23,
23,
23,
23,
23,
23,
23,
23,
23,
23,
23,
23,
23,
23,
23,
23,
23,
23,
23,
23,
23,
23,
23,
23,
23,
23,
23,
23,
23,
23,
23,
23,
23,
23,
23,
23,
23,
23,
23,
23,
23,
24,
24,
24,
24,
24,
24,
24,
24,
24,
24,
24,
24,
24,
24,
24,
24,
24,
24,
24,
24,
24,
24,
24,
24,
24,
24,
24,
24,
24,
24,
24,
24,
24,
24,
24,
24,
24,
24,
24,
24,
24,
24,
24,
24,
24,
24,
24,
24,
24,
24,
24,
24,
24,
24,
24,
24,
24,
24,
24,
24,
24,
24,
24,
24,
24,
24,
24,
24,
24,
24,
24,
24,
24,
24,
];
function filterGaussBlurRGBA(imageData, radius) {
var pixels = imageData.data, width = imageData.width, height = imageData.height;
var x, y, i, p, yp, yi, yw, r_sum, g_sum, b_sum, a_sum, r_out_sum, g_out_sum, b_out_sum, a_out_sum, r_in_sum, g_in_sum, b_in_sum, a_in_sum, pr, pg, pb, pa, rbs;
var div = radius + radius + 1, widthMinus1 = width - 1, heightMinus1 = height - 1, radiusPlus1 = radius + 1, sumFactor = (radiusPlus1 * (radiusPlus1 + 1)) / 2, stackStart = new BlurStack(), stackEnd = null, stack = stackStart, stackIn = null, stackOut = null, mul_sum = mul_table[radius], shg_sum = shg_table[radius];
for (i = 1; i < div; i++) {
stack = stack.next = new BlurStack();
if (i === radiusPlus1) {
stackEnd = stack;
}
}
stack.next = stackStart;
yw = yi = 0;
for (y = 0; y < height; y++) {
r_in_sum = g_in_sum = b_in_sum = a_in_sum = r_sum = g_sum = b_sum = a_sum = 0;
r_out_sum = radiusPlus1 * (pr = pixels[yi]);
g_out_sum = radiusPlus1 * (pg = pixels[yi + 1]);
b_out_sum = radiusPlus1 * (pb = pixels[yi + 2]);
a_out_sum = radiusPlus1 * (pa = pixels[yi + 3]);
r_sum += sumFactor * pr;
g_sum += sumFactor * pg;
b_sum += sumFactor * pb;
a_sum += sumFactor * pa;
stack = stackStart;
for (i = 0; i < radiusPlus1; i++) {
stack.r = pr;
stack.g = pg;
stack.b = pb;
stack.a = pa;
stack = stack.next;
}
for (i = 1; i < radiusPlus1; i++) {
p = yi + ((widthMinus1 < i ? widthMinus1 : i) << 2);
r_sum += (stack.r = pr = pixels[p]) * (rbs = radiusPlus1 - i);
g_sum += (stack.g = pg = pixels[p + 1]) * rbs;
b_sum += (stack.b = pb = pixels[p + 2]) * rbs;
a_sum += (stack.a = pa = pixels[p + 3]) * rbs;
r_in_sum += pr;
g_in_sum += pg;
b_in_sum += pb;
a_in_sum += pa;
stack = stack.next;
}
stackIn = stackStart;
stackOut = stackEnd;
for (x = 0; x < width; x++) {
pixels[yi + 3] = pa = (a_sum * mul_sum) >> shg_sum;
if (pa !== 0) {
pa = 255 / pa;
pixels[yi] = ((r_sum * mul_sum) >> shg_sum) * pa;
pixels[yi + 1] = ((g_sum * mul_sum) >> shg_sum) * pa;
pixels[yi + 2] = ((b_sum * mul_sum) >> shg_sum) * pa;
}
else {
pixels[yi] = pixels[yi + 1] = pixels[yi + 2] = 0;
}
r_sum -= r_out_sum;
g_sum -= g_out_sum;
b_sum -= b_out_sum;
a_sum -= a_out_sum;
r_out_sum -= stackIn.r;
g_out_sum -= stackIn.g;
b_out_sum -= stackIn.b;
a_out_sum -= stackIn.a;
p = (yw + ((p = x + radius + 1) < widthMinus1 ? p : widthMinus1)) << 2;
r_in_sum += stackIn.r = pixels[p];
g_in_sum += stackIn.g = pixels[p + 1];
b_in_sum += stackIn.b = pixels[p + 2];
a_in_sum += stackIn.a = pixels[p + 3];
r_sum += r_in_sum;
g_sum += g_in_sum;
b_sum += b_in_sum;
a_sum += a_in_sum;
stackIn = stackIn.next;
r_out_sum += pr = stackOut.r;
g_out_sum += pg = stackOut.g;
b_out_sum += pb = stackOut.b;
a_out_sum += pa = stackOut.a;
r_in_sum -= pr;
g_in_sum -= pg;
b_in_sum -= pb;
a_in_sum -= pa;
stackOut = stackOut.next;
yi += 4;
}
yw += width;
}
for (x = 0; x < width; x++) {
g_in_sum = b_in_sum = a_in_sum = r_in_sum = g_sum = b_sum = a_sum = r_sum = 0;
yi = x << 2;
r_out_sum = radiusPlus1 * (pr = pixels[yi]);
g_out_sum = radiusPlus1 * (pg = pixels[yi + 1]);
b_out_sum = radiusPlus1 * (pb = pixels[yi + 2]);
a_out_sum = radiusPlus1 * (pa = pixels[yi + 3]);
r_sum += sumFactor * pr;
g_sum += sumFactor * pg;
b_sum += sumFactor * pb;
a_sum += sumFactor * pa;
stack = stackStart;
for (i = 0; i < radiusPlus1; i++) {
stack.r = pr;
stack.g = pg;
stack.b = pb;
stack.a = pa;
stack = stack.next;
}
yp = width;
for (i = 1; i <= radius; i++) {
yi = (yp + x) << 2;
r_sum += (stack.r = pr = pixels[yi]) * (rbs = radiusPlus1 - i);
g_sum += (stack.g = pg = pixels[yi + 1]) * rbs;
b_sum += (stack.b = pb = pixels[yi + 2]) * rbs;
a_sum += (stack.a = pa = pixels[yi + 3]) * rbs;
r_in_sum += pr;
g_in_sum += pg;
b_in_sum += pb;
a_in_sum += pa;
stack = stack.next;
if (i < heightMinus1) {
yp += width;
}
}
yi = x;
stackIn = stackStart;
stackOut = stackEnd;
for (y = 0; y < height; y++) {
p = yi << 2;
pixels[p + 3] = pa = (a_sum * mul_sum) >> shg_sum;
if (pa > 0) {
pa = 255 / pa;
pixels[p] = ((r_sum * mul_sum) >> shg_sum) * pa;
pixels[p + 1] = ((g_sum * mul_sum) >> shg_sum) * pa;
pixels[p + 2] = ((b_sum * mul_sum) >> shg_sum) * pa;
}
else {
pixels[p] = pixels[p + 1] = pixels[p + 2] = 0;
}
r_sum -= r_out_sum;
g_sum -= g_out_sum;
b_sum -= b_out_sum;
a_sum -= a_out_sum;
r_out_sum -= stackIn.r;
g_out_sum -= stackIn.g;
b_out_sum -= stackIn.b;
a_out_sum -= stackIn.a;
p =
(x +
((p = y + radiusPlus1) < heightMinus1 ? p : heightMinus1) * width) <<
2;
r_sum += r_in_sum += stackIn.r = pixels[p];
g_sum += g_in_sum += stackIn.g = pixels[p + 1];
b_sum += b_in_sum += stackIn.b = pixels[p + 2];
a_sum += a_in_sum += stackIn.a = pixels[p + 3];
stackIn = stackIn.next;
r_out_sum += pr = stackOut.r;
g_out_sum += pg = stackOut.g;
b_out_sum += pb = stackOut.b;
a_out_sum += pa = stackOut.a;
r_in_sum -= pr;
g_in_sum -= pg;
b_in_sum -= pb;
a_in_sum -= pa;
stackOut = stackOut.next;
yi += width;
}
}
}
/**
* Blur Filter
* @function
* @name Blur
* @memberof Konva.Filters
* @param {Object} imageData
* @example
* node.cache();
* node.filters([Konva.Filters.Blur]);
* node.blurRadius(10);
*/
const Blur = function Blur(imageData) {
var radius = Math.round(this.blurRadius());
if (radius > 0) {
filterGaussBlurRGBA(imageData, radius);
}
};
Factory.addGetterSetter(Node, 'blurRadius', 0, getNumberValidator(), Factory.afterSetFilter);
/**
* get/set blur radius. Use with {@link Konva.Filters.Blur} filter
* @name Konva.Node#blurRadius
* @method
* @param {Integer} radius
* @returns {Integer}
*/
/**
* Brighten Filter.
* @function
* @memberof Konva.Filters
* @param {Object} imageData
* @example
* node.cache();
* node.filters([Konva.Filters.Brighten]);
* node.brightness(0.8);
*/
const Brighten = function (imageData) {
var brightness = this.brightness() * 255, data = imageData.data, len = data.length, i;
for (i = 0; i < len; i += 4) {
// red
data[i] += brightness;
// green
data[i + 1] += brightness;
// blue
data[i + 2] += brightness;
}
};
Factory.addGetterSetter(Node, 'brightness', 0, getNumberValidator(), Factory.afterSetFilter);
/**
* get/set filter brightness. The brightness is a number between -1 and 1. Positive values
* brighten the pixels and negative values darken them. Use with {@link Konva.Filters.Brighten} filter.
* @name Konva.Node#brightness
* @method
* @param {Number} brightness value between -1 and 1
* @returns {Number}
*/
/**
* Contrast Filter.
* @function
* @memberof Konva.Filters
* @param {Object} imageData
* @example
* node.cache();
* node.filters([Konva.Filters.Contrast]);
* node.contrast(10);
*/
const Contrast = function (imageData) {
var adjust = Math.pow((this.contrast() + 100) / 100, 2);
var data = imageData.data, nPixels = data.length, red = 150, green = 150, blue = 150, i;
for (i = 0; i < nPixels; i += 4) {
red = data[i];
green = data[i + 1];
blue = data[i + 2];
//Red channel
red /= 255;
red -= 0.5;
red *= adjust;
red += 0.5;
red *= 255;
//Green channel
green /= 255;
green -= 0.5;
green *= adjust;
green += 0.5;
green *= 255;
//Blue channel
blue /= 255;
blue -= 0.5;
blue *= adjust;
blue += 0.5;
blue *= 255;
red = red < 0 ? 0 : red > 255 ? 255 : red;
green = green < 0 ? 0 : green > 255 ? 255 : green;
blue = blue < 0 ? 0 : blue > 255 ? 255 : blue;
data[i] = red;
data[i + 1] = green;
data[i + 2] = blue;
}
};
/**
* get/set filter contrast. The contrast is a number between -100 and 100.
* Use with {@link Konva.Filters.Contrast} filter.
* @name Konva.Node#contrast
* @method
* @param {Number} contrast value between -100 and 100
* @returns {Number}
*/
Factory.addGetterSetter(Node, 'contrast', 0, getNumberValidator(), Factory.afterSetFilter);
/**
* Emboss Filter.
* Pixastic Lib - Emboss filter - v0.1.0
* Copyright (c) 2008 Jacob Seidelin, jseidelin@nihilogic.dk, http://blog.nihilogic.dk/
* License: [http://www.pixastic.com/lib/license.txt]
* @function
* @memberof Konva.Filters
* @param {Object} imageData
* @example
* node.cache();
* node.filters([Konva.Filters.Emboss]);
* node.embossStrength(0.8);
* node.embossWhiteLevel(0.3);
* node.embossDirection('right');
* node.embossBlend(true);
*/
const Emboss = function (imageData) {
// pixastic strength is between 0 and 10. I want it between 0 and 1
// pixastic greyLevel is between 0 and 255. I want it between 0 and 1. Also,
// a max value of greyLevel yields a white emboss, and the min value yields a black
// emboss. Therefore, I changed greyLevel to whiteLevel
var strength = this.embossStrength() * 10, greyLevel = this.embossWhiteLevel() * 255, direction = this.embossDirection(), blend = this.embossBlend(), dirY = 0, dirX = 0, data = imageData.data, w = imageData.width, h = imageData.height, w4 = w * 4, y = h;
switch (direction) {
case 'top-left':
dirY = -1;
dirX = -1;
break;
case 'top':
dirY = -1;
dirX = 0;
break;
case 'top-right':
dirY = -1;
dirX = 1;
break;
case 'right':
dirY = 0;
dirX = 1;
break;
case 'bottom-right':
dirY = 1;
dirX = 1;
break;
case 'bottom':
dirY = 1;
dirX = 0;
break;
case 'bottom-left':
dirY = 1;
dirX = -1;
break;
case 'left':
dirY = 0;
dirX = -1;
break;
default:
Util.error('Unknown emboss direction: ' + direction);
}
do {
var offsetY = (y - 1) * w4;
var otherY = dirY;
if (y + otherY < 1) {
otherY = 0;
}
if (y + otherY > h) {
otherY = 0;
}
var offsetYOther = (y - 1 + otherY) * w * 4;
var x = w;
do {
var offset = offsetY + (x - 1) * 4;
var otherX = dirX;
if (x + otherX < 1) {
otherX = 0;
}
if (x + otherX > w) {
otherX = 0;
}
var offsetOther = offsetYOther + (x - 1 + otherX) * 4;
var dR = data[offset] - data[offsetOther];
var dG = data[offset + 1] - data[offsetOther + 1];
var dB = data[offset + 2] - data[offsetOther + 2];
var dif = dR;
var absDif = dif > 0 ? dif : -dif;
var absG = dG > 0 ? dG : -dG;
var absB = dB > 0 ? dB : -dB;
if (absG > absDif) {
dif = dG;
}
if (absB > absDif) {
dif = dB;
}
dif *= strength;
if (blend) {
var r = data[offset] + dif;
var g = data[offset + 1] + dif;
var b = data[offset + 2] + dif;
data[offset] = r > 255 ? 255 : r < 0 ? 0 : r;
data[offset + 1] = g > 255 ? 255 : g < 0 ? 0 : g;
data[offset + 2] = b > 255 ? 255 : b < 0 ? 0 : b;
}
else {
var grey = greyLevel - dif;
if (grey < 0) {
grey = 0;
}
else if (grey > 255) {
grey = 255;
}
data[offset] = data[offset + 1] = data[offset + 2] = grey;
}
} while (--x);
} while (--y);
};
Factory.addGetterSetter(Node, 'embossStrength', 0.5, getNumberValidator(), Factory.afterSetFilter);
/**
* get/set emboss strength. Use with {@link Konva.Filters.Emboss} filter.
* @name Konva.Node#embossStrength
* @method
* @param {Number} level between 0 and 1. Default is 0.5
* @returns {Number}
*/
Factory.addGetterSetter(Node, 'embossWhiteLevel', 0.5, getNumberValidator(), Factory.afterSetFilter);
/**
* get/set emboss white level. Use with {@link Konva.Filters.Emboss} filter.
* @name Konva.Node#embossWhiteLevel
* @method
* @param {Number} embossWhiteLevel between 0 and 1. Default is 0.5
* @returns {Number}
*/
Factory.addGetterSetter(Node, 'embossDirection', 'top-left', null, Factory.afterSetFilter);
/**
* get/set emboss direction. Use with {@link Konva.Filters.Emboss} filter.
* @name Konva.Node#embossDirection
* @method
* @param {String} embossDirection can be top-left, top, top-right, right, bottom-right, bottom, bottom-left or left
* The default is top-left
* @returns {String}
*/
Factory.addGetterSetter(Node, 'embossBlend', false, null, Factory.afterSetFilter);
/**
* get/set emboss blend. Use with {@link Konva.Filters.Emboss} filter.
* @name Konva.Node#embossBlend
* @method
* @param {Boolean} embossBlend
* @returns {Boolean}
*/
function remap(fromValue, fromMin, fromMax, toMin, toMax) {
// Compute the range of the data
var fromRange = fromMax - fromMin, toRange = toMax - toMin, toValue;
// If either range is 0, then the value can only be mapped to 1 value
if (fromRange === 0) {
return toMin + toRange / 2;
}
if (toRange === 0) {
return toMin;
}
// (1) untranslate, (2) unscale, (3) rescale, (4) retranslate
toValue = (fromValue - fromMin) / fromRange;
toValue = toRange * toValue + toMin;
return toValue;
}
/**
* Enhance Filter. Adjusts the colors so that they span the widest
* possible range (ie 0-255). Performs w*h pixel reads and w*h pixel
* writes.
* @function
* @name Enhance
* @memberof Konva.Filters
* @param {Object} imageData
* @author ippo615
* @example
* node.cache();
* node.filters([Konva.Filters.Enhance]);
* node.enhance(0.4);
*/
const Enhance = function (imageData) {
var data = imageData.data, nSubPixels = data.length, rMin = data[0], rMax = rMin, r, gMin = data[1], gMax = gMin, g, bMin = data[2], bMax = bMin, b, i;
// If we are not enhancing anything - don't do any computation
var enhanceAmount = this.enhance();
if (enhanceAmount === 0) {
return;
}
// 1st Pass - find the min and max for each channel:
for (i = 0; i < nSubPixels; i += 4) {
r = data[i + 0];
if (r < rMin) {
rMin = r;
}
else if (r > rMax) {
rMax = r;
}
g = data[i + 1];
if (g < gMin) {
gMin = g;
}
else if (g > gMax) {
gMax = g;
}
b = data[i + 2];
if (b < bMin) {
bMin = b;
}
else if (b > bMax) {
bMax = b;
}
//a = data[i + 3];
//if (a < aMin) { aMin = a; } else
//if (a > aMax) { aMax = a; }
}
// If there is only 1 level - don't remap
if (rMax === rMin) {
rMax = 255;
rMin = 0;
}
if (gMax === gMin) {
gMax = 255;
gMin = 0;
}
if (bMax === bMin) {
bMax = 255;
bMin = 0;
}
var rMid, rGoalMax, rGoalMin, gMid, gGoalMax, gGoalMin, bMid, bGoalMax, bGoalMin;
// If the enhancement is positive - stretch the histogram
if (enhanceAmount > 0) {
rGoalMax = rMax + enhanceAmount * (255 - rMax);
rGoalMin = rMin - enhanceAmount * (rMin - 0);
gGoalMax = gMax + enhanceAmount * (255 - gMax);
gGoalMin = gMin - enhanceAmount * (gMin - 0);
bGoalMax = bMax + enhanceAmount * (255 - bMax);
bGoalMin = bMin - enhanceAmount * (bMin - 0);
// If the enhancement is negative - compress the histogram
}
else {
rMid = (rMax + rMin) * 0.5;
rGoalMax = rMax + enhanceAmount * (rMax - rMid);
rGoalMin = rMin + enhanceAmount * (rMin - rMid);
gMid = (gMax + gMin) * 0.5;
gGoalMax = gMax + enhanceAmount * (gMax - gMid);
gGoalMin = gMin + enhanceAmount * (gMin - gMid);
bMid = (bMax + bMin) * 0.5;
bGoalMax = bMax + enhanceAmount * (bMax - bMid);
bGoalMin = bMin + enhanceAmount * (bMin - bMid);
}
// Pass 2 - remap everything, except the alpha
for (i = 0; i < nSubPixels; i += 4) {
data[i + 0] = remap(data[i + 0], rMin, rMax, rGoalMin, rGoalMax);
data[i + 1] = remap(data[i + 1], gMin, gMax, gGoalMin, gGoalMax);
data[i + 2] = remap(data[i + 2], bMin, bMax, bGoalMin, bGoalMax);
//data[i + 3] = remap(data[i + 3], aMin, aMax, aGoalMin, aGoalMax);
}
};
/**
* get/set enhance. Use with {@link Konva.Filters.Enhance} filter. -1 to 1 values
* @name Konva.Node#enhance
* @method
* @param {Float} amount
* @returns {Float}
*/
Factory.addGetterSetter(Node, 'enhance', 0, getNumberValidator(), Factory.afterSetFilter);
/**
* Grayscale Filter
* @function
* @memberof Konva.Filters
* @param {Object} imageData
* @example
* node.cache();
* node.filters([Konva.Filters.Grayscale]);
*/
const Grayscale = function (imageData) {
var data = imageData.data, len = data.length, i, brightness;
for (i = 0; i < len; i += 4) {
brightness = 0.34 * data[i] + 0.5 * data[i + 1] + 0.16 * data[i + 2];
// red
data[i] = brightness;
// green
data[i + 1] = brightness;
// blue
data[i + 2] = brightness;
}
};
Factory.addGetterSetter(Node, 'hue', 0, getNumberValidator(), Factory.afterSetFilter);
/**
* get/set hsv hue in degrees. Use with {@link Konva.Filters.HSV} or {@link Konva.Filters.HSL} filter.
* @name Konva.Node#hue
* @method
* @param {Number} hue value between 0 and 359
* @returns {Number}
*/
Factory.addGetterSetter(Node, 'saturation', 0, getNumberValidator(), Factory.afterSetFilter);
/**
* get/set hsv saturation. Use with {@link Konva.Filters.HSV} or {@link Konva.Filters.HSL} filter.
* @name Konva.Node#saturation
* @method
* @param {Number} saturation 0 is no change, -1.0 halves the saturation, 1.0 doubles, etc..
* @returns {Number}
*/
Factory.addGetterSetter(Node, 'luminance', 0, getNumberValidator(), Factory.afterSetFilter);
/**
* get/set hsl luminance. Use with {@link Konva.Filters.HSL} filter.
* @name Konva.Node#luminance
* @method
* @param {Number} value from -1 to 1
* @returns {Number}
*/
/**
* HSL Filter. Adjusts the hue, saturation and luminance (or lightness)
* @function
* @memberof Konva.Filters
* @param {Object} imageData
* @author ippo615
* @example
* image.filters([Konva.Filters.HSL]);
* image.luminance(0.2);
*/
const HSL = function (imageData) {
var data = imageData.data, nPixels = data.length, v = 1, s = Math.pow(2, this.saturation()), h = Math.abs(this.hue() + 360) % 360, l = this.luminance() * 127, i;
// Basis for the technique used:
// http://beesbuzz.biz/code/hsv_color_transforms.php
// V is the value multiplier (1 for none, 2 for double, 0.5 for half)
// S is the saturation multiplier (1 for none, 2 for double, 0.5 for half)
// H is the hue shift in degrees (0 to 360)
// vsu = V*S*cos(H*PI/180);
// vsw = V*S*sin(H*PI/180);
//[ .299V+.701vsu+.168vsw .587V-.587vsu+.330vsw .114V-.114vsu-.497vsw ] [R]
//[ .299V-.299vsu-.328vsw .587V+.413vsu+.035vsw .114V-.114vsu+.292vsw ]*[G]
//[ .299V-.300vsu+1.25vsw .587V-.588vsu-1.05vsw .114V+.886vsu-.203vsw ] [B]
// Precompute the values in the matrix:
var vsu = v * s * Math.cos((h * Math.PI) / 180), vsw = v * s * Math.sin((h * Math.PI) / 180);
// (result spot)(source spot)
var rr = 0.299 * v + 0.701 * vsu + 0.167 * vsw, rg = 0.587 * v - 0.587 * vsu + 0.33 * vsw, rb = 0.114 * v - 0.114 * vsu - 0.497 * vsw;
var gr = 0.299 * v - 0.299 * vsu - 0.328 * vsw, gg = 0.587 * v + 0.413 * vsu + 0.035 * vsw, gb = 0.114 * v - 0.114 * vsu + 0.293 * vsw;
var br = 0.299 * v - 0.3 * vsu + 1.25 * vsw, bg = 0.587 * v - 0.586 * vsu - 1.05 * vsw, bb = 0.114 * v + 0.886 * vsu - 0.2 * vsw;
var r, g, b, a;
for (i = 0; i < nPixels; i += 4) {
r = data[i + 0];
g = data[i + 1];
b = data[i + 2];
a = data[i + 3];
data[i + 0] = rr * r + rg * g + rb * b + l;
data[i + 1] = gr * r + gg * g + gb * b + l;
data[i + 2] = br * r + bg * g + bb * b + l;
data[i + 3] = a; // alpha
}
};
/**
* HSV Filter. Adjusts the hue, saturation and value
* @function
* @name HSV
* @memberof Konva.Filters
* @param {Object} imageData
* @author ippo615
* @example
* image.filters([Konva.Filters.HSV]);
* image.value(200);
*/
const HSV = function (imageData) {
var data = imageData.data, nPixels = data.length, v = Math.pow(2, this.value()), s = Math.pow(2, this.saturation()), h = Math.abs(this.hue() + 360) % 360, i;
// Basis for the technique used:
// http://beesbuzz.biz/code/hsv_color_transforms.php
// V is the value multiplier (1 for none, 2 for double, 0.5 for half)
// S is the saturation multiplier (1 for none, 2 for double, 0.5 for half)
// H is the hue shift in degrees (0 to 360)
// vsu = V*S*cos(H*PI/180);
// vsw = V*S*sin(H*PI/180);
//[ .299V+.701vsu+.168vsw .587V-.587vsu+.330vsw .114V-.114vsu-.497vsw ] [R]
//[ .299V-.299vsu-.328vsw .587V+.413vsu+.035vsw .114V-.114vsu+.292vsw ]*[G]
//[ .299V-.300vsu+1.25vsw .587V-.588vsu-1.05vsw .114V+.886vsu-.203vsw ] [B]
// Precompute the values in the matrix:
var vsu = v * s * Math.cos((h * Math.PI) / 180), vsw = v * s * Math.sin((h * Math.PI) / 180);
// (result spot)(source spot)
var rr = 0.299 * v + 0.701 * vsu + 0.167 * vsw, rg = 0.587 * v - 0.587 * vsu + 0.33 * vsw, rb = 0.114 * v - 0.114 * vsu - 0.497 * vsw;
var gr = 0.299 * v - 0.299 * vsu - 0.328 * vsw, gg = 0.587 * v + 0.413 * vsu + 0.035 * vsw, gb = 0.114 * v - 0.114 * vsu + 0.293 * vsw;
var br = 0.299 * v - 0.3 * vsu + 1.25 * vsw, bg = 0.587 * v - 0.586 * vsu - 1.05 * vsw, bb = 0.114 * v + 0.886 * vsu - 0.2 * vsw;
var r, g, b, a;
for (i = 0; i < nPixels; i += 4) {
r = data[i + 0];
g = data[i + 1];
b = data[i + 2];
a = data[i + 3];
data[i + 0] = rr * r + rg * g + rb * b;
data[i + 1] = gr * r + gg * g + gb * b;
data[i + 2] = br * r + bg * g + bb * b;
data[i + 3] = a; // alpha
}
};
Factory.addGetterSetter(Node, 'hue', 0, getNumberValidator(), Factory.afterSetFilter);
/**
* get/set hsv hue in degrees. Use with {@link Konva.Filters.HSV} or {@link Konva.Filters.HSL} filter.
* @name Konva.Node#hue
* @method
* @param {Number} hue value between 0 and 359
* @returns {Number}
*/
Factory.addGetterSetter(Node, 'saturation', 0, getNumberValidator(), Factory.afterSetFilter);
/**
* get/set hsv saturation. Use with {@link Konva.Filters.HSV} or {@link Konva.Filters.HSL} filter.
* @name Konva.Node#saturation
* @method
* @param {Number} saturation 0 is no change, -1.0 halves the saturation, 1.0 doubles, etc..
* @returns {Number}
*/
Factory.addGetterSetter(Node, 'value', 0, getNumberValidator(), Factory.afterSetFilter);
/**
* get/set hsv value. Use with {@link Konva.Filters.HSV} filter.
* @name Konva.Node#value
* @method
* @param {Number} value 0 is no change, -1.0 halves the value, 1.0 doubles, etc..
* @returns {Number}
*/
/**
* Invert Filter
* @function
* @memberof Konva.Filters
* @param {Object} imageData
* @example
* node.cache();
* node.filters([Konva.Filters.Invert]);
*/
const Invert = function (imageData) {
var data = imageData.data, len = data.length, i;
for (i = 0; i < len; i += 4) {
// red
data[i] = 255 - data[i];
// green
data[i + 1] = 255 - data[i + 1];
// blue
data[i + 2] = 255 - data[i + 2];
}
};
/*
* ToPolar Filter. Converts image data to polar coordinates. Performs
* w*h*4 pixel reads and w*h pixel writes. The r axis is placed along
* what would be the y axis and the theta axis along the x axis.
* @function
* @author ippo615
* @memberof Konva.Filters
* @param {ImageData} src, the source image data (what will be transformed)
* @param {ImageData} dst, the destination image data (where it will be saved)
* @param {Object} opt
* @param {Number} [opt.polarCenterX] horizontal location for the center of the circle,
* default is in the middle
* @param {Number} [opt.polarCenterY] vertical location for the center of the circle,
* default is in the middle
*/
var ToPolar = function (src, dst, opt) {
var srcPixels = src.data, dstPixels = dst.data, xSize = src.width, ySize = src.height, xMid = opt.polarCenterX || xSize / 2, yMid = opt.polarCenterY || ySize / 2, i, x, y, r = 0, g = 0, b = 0, a = 0;
// Find the largest radius
var rad, rMax = Math.sqrt(xMid * xMid + yMid * yMid);
x = xSize - xMid;
y = ySize - yMid;
rad = Math.sqrt(x * x + y * y);
rMax = rad > rMax ? rad : rMax;
// We'll be uisng y as the radius, and x as the angle (theta=t)
var rSize = ySize, tSize = xSize, radius, theta;
// We want to cover all angles (0-360) and we need to convert to
// radians (*PI/180)
var conversion = ((360 / tSize) * Math.PI) / 180, sin, cos;
// var x1, x2, x1i, x2i, y1, y2, y1i, y2i, scale;
for (theta = 0; theta < tSize; theta += 1) {
sin = Math.sin(theta * conversion);
cos = Math.cos(theta * conversion);
for (radius = 0; radius < rSize; radius += 1) {
x = Math.floor(xMid + ((rMax * radius) / rSize) * cos);
y = Math.floor(yMid + ((rMax * radius) / rSize) * sin);
i = (y * xSize + x) * 4;
r = srcPixels[i + 0];
g = srcPixels[i + 1];
b = srcPixels[i + 2];
a = srcPixels[i + 3];
// Store it
//i = (theta * xSize + radius) * 4;
i = (theta + radius * xSize) * 4;
dstPixels[i + 0] = r;
dstPixels[i + 1] = g;
dstPixels[i + 2] = b;
dstPixels[i + 3] = a;
}
}
};
/*
* FromPolar Filter. Converts image data from polar coordinates back to rectangular.
* Performs w*h*4 pixel reads and w*h pixel writes.
* @function
* @author ippo615
* @memberof Konva.Filters
* @param {ImageData} src, the source image data (what will be transformed)
* @param {ImageData} dst, the destination image data (where it will be saved)
* @param {Object} opt
* @param {Number} [opt.polarCenterX] horizontal location for the center of the circle,
* default is in the middle
* @param {Number} [opt.polarCenterY] vertical location for the center of the circle,
* default is in the middle
* @param {Number} [opt.polarRotation] amount to rotate the image counterclockwis,
* 0 is no rotation, 360 degrees is a full rotation
*/
var FromPolar = function (src, dst, opt) {
var srcPixels = src.data, dstPixels = dst.data, xSize = src.width, ySize = src.height, xMid = opt.polarCenterX || xSize / 2, yMid = opt.polarCenterY || ySize / 2, i, x, y, dx, dy, r = 0, g = 0, b = 0, a = 0;
// Find the largest radius
var rad, rMax = Math.sqrt(xMid * xMid + yMid * yMid);
x = xSize - xMid;
y = ySize - yMid;
rad = Math.sqrt(x * x + y * y);
rMax = rad > rMax ? rad : rMax;
// We'll be uisng x as the radius, and y as the angle (theta=t)
var rSize = ySize, tSize = xSize, radius, theta, phaseShift = opt.polarRotation || 0;
// We need to convert to degrees and we need to make sure
// it's between (0-360)
// var conversion = tSize/360*180/Math.PI;
//var conversion = tSize/360*180/Math.PI;
var x1, y1;
for (x = 0; x < xSize; x += 1) {
for (y = 0; y < ySize; y += 1) {
dx = x - xMid;
dy = y - yMid;
radius = (Math.sqrt(dx * dx + dy * dy) * rSize) / rMax;
theta = ((Math.atan2(dy, dx) * 180) / Math.PI + 360 + phaseShift) % 360;
theta = (theta * tSize) / 360;
x1 = Math.floor(theta);
y1 = Math.floor(radius);
i = (y1 * xSize + x1) * 4;
r = srcPixels[i + 0];
g = srcPixels[i + 1];
b = srcPixels[i + 2];
a = srcPixels[i + 3];
// Store it
i = (y * xSize + x) * 4;
dstPixels[i + 0] = r;
dstPixels[i + 1] = g;
dstPixels[i + 2] = b;
dstPixels[i + 3] = a;
}
}
};
//Konva.Filters.ToPolar = Util._FilterWrapDoubleBuffer(ToPolar);
//Konva.Filters.FromPolar = Util._FilterWrapDoubleBuffer(FromPolar);
// create a temporary canvas for working - shared between multiple calls
/*
* Kaleidoscope Filter.
* @function
* @name Kaleidoscope
* @author ippo615
* @memberof Konva.Filters
* @example
* node.cache();
* node.filters([Konva.Filters.Kaleidoscope]);
* node.kaleidoscopePower(3);
* node.kaleidoscopeAngle(45);
*/
const Kaleidoscope = function (imageData) {
var xSize = imageData.width, ySize = imageData.height;
var x, y, xoff, i, r, g, b, a, srcPos, dstPos;
var power = Math.round(this.kaleidoscopePower());
var angle = Math.round(this.kaleidoscopeAngle());
var offset = Math.floor((xSize * (angle % 360)) / 360);
if (power < 1) {
return;
}
// Work with our shared buffer canvas
var tempCanvas = Util.createCanvasElement();
tempCanvas.width = xSize;
tempCanvas.height = ySize;
var scratchData = tempCanvas
.getContext('2d')
.getImageData(0, 0, xSize, ySize);
// Convert thhe original to polar coordinates
ToPolar(imageData, scratchData, {
polarCenterX: xSize / 2,
polarCenterY: ySize / 2,
});
// Determine how big each section will be, if it's too small
// make it bigger
var minSectionSize = xSize / Math.pow(2, power);
while (minSectionSize <= 8) {
minSectionSize = minSectionSize * 2;
power -= 1;
}
minSectionSize = Math.ceil(minSectionSize);
var sectionSize = minSectionSize;
// Copy the offset region to 0
// Depending on the size of filter and location of the offset we may need
// to copy the section backwards to prevent it from rewriting itself
var xStart = 0, xEnd = sectionSize, xDelta = 1;
if (offset + minSectionSize > xSize) {
xStart = sectionSize;
xEnd = 0;
xDelta = -1;
}
for (y = 0; y < ySize; y += 1) {
for (x = xStart; x !== xEnd; x += xDelta) {
xoff = Math.round(x + offset) % xSize;
srcPos = (xSize * y + xoff) * 4;
r = scratchData.data[srcPos + 0];
g = scratchData.data[srcPos + 1];
b = scratchData.data[srcPos + 2];
a = scratchData.data[srcPos + 3];
dstPos = (xSize * y + x) * 4;
scratchData.data[dstPos + 0] = r;
scratchData.data[dstPos + 1] = g;
scratchData.data[dstPos + 2] = b;
scratchData.data[dstPos + 3] = a;
}
}
// Perform the actual effect
for (y = 0; y < ySize; y += 1) {
sectionSize = Math.floor(minSectionSize);
for (i = 0; i < power; i += 1) {
for (x = 0; x < sectionSize + 1; x += 1) {
srcPos = (xSize * y + x) * 4;
r = scratchData.data[srcPos + 0];
g = scratchData.data[srcPos + 1];
b = scratchData.data[srcPos + 2];
a = scratchData.data[srcPos + 3];
dstPos = (xSize * y + sectionSize * 2 - x - 1) * 4;
scratchData.data[dstPos + 0] = r;
scratchData.data[dstPos + 1] = g;
scratchData.data[dstPos + 2] = b;
scratchData.data[dstPos + 3] = a;
}
sectionSize *= 2;
}
}
// Convert back from polar coordinates
FromPolar(scratchData, imageData, { polarRotation: 0 });
};
/**
* get/set kaleidoscope power. Use with {@link Konva.Filters.Kaleidoscope} filter.
* @name Konva.Node#kaleidoscopePower
* @method
* @param {Integer} power of kaleidoscope
* @returns {Integer}
*/
Factory.addGetterSetter(Node, 'kaleidoscopePower', 2, getNumberValidator(), Factory.afterSetFilter);
/**
* get/set kaleidoscope angle. Use with {@link Konva.Filters.Kaleidoscope} filter.
* @name Konva.Node#kaleidoscopeAngle
* @method
* @param {Integer} degrees
* @returns {Integer}
*/
Factory.addGetterSetter(Node, 'kaleidoscopeAngle', 0, getNumberValidator(), Factory.afterSetFilter);
function pixelAt(idata, x, y) {
var idx = (y * idata.width + x) * 4;
var d = [];
d.push(idata.data[idx++], idata.data[idx++], idata.data[idx++], idata.data[idx++]);
return d;
}
function rgbDistance(p1, p2) {
return Math.sqrt(Math.pow(p1[0] - p2[0], 2) +
Math.pow(p1[1] - p2[1], 2) +
Math.pow(p1[2] - p2[2], 2));
}
function rgbMean(pTab) {
var m = [0, 0, 0];
for (var i = 0; i < pTab.length; i++) {
m[0] += pTab[i][0];
m[1] += pTab[i][1];
m[2] += pTab[i][2];
}
m[0] /= pTab.length;
m[1] /= pTab.length;
m[2] /= pTab.length;
return m;
}
function backgroundMask(idata, threshold) {
var rgbv_no = pixelAt(idata, 0, 0);
var rgbv_ne = pixelAt(idata, idata.width - 1, 0);
var rgbv_so = pixelAt(idata, 0, idata.height - 1);
var rgbv_se = pixelAt(idata, idata.width - 1, idata.height - 1);
var thres = threshold || 10;
if (rgbDistance(rgbv_no, rgbv_ne) < thres &&
rgbDistance(rgbv_ne, rgbv_se) < thres &&
rgbDistance(rgbv_se, rgbv_so) < thres &&
rgbDistance(rgbv_so, rgbv_no) < thres) {
// Mean color
var mean = rgbMean([rgbv_ne, rgbv_no, rgbv_se, rgbv_so]);
// Mask based on color distance
var mask = [];
for (var i = 0; i < idata.width * idata.height; i++) {
var d = rgbDistance(mean, [
idata.data[i * 4],
idata.data[i * 4 + 1],
idata.data[i * 4 + 2],
]);
mask[i] = d < thres ? 0 : 255;
}
return mask;
}
}
function applyMask(idata, mask) {
for (var i = 0; i < idata.width * idata.height; i++) {
idata.data[4 * i + 3] = mask[i];
}
}
function erodeMask(mask, sw, sh) {
var weights = [1, 1, 1, 1, 0, 1, 1, 1, 1];
var side = Math.round(Math.sqrt(weights.length));
var halfSide = Math.floor(side / 2);
var maskResult = [];
for (var y = 0; y < sh; y++) {
for (var x = 0; x < sw; x++) {
var so = y * sw + x;
var a = 0;
for (var cy = 0; cy < side; cy++) {
for (var cx = 0; cx < side; cx++) {
var scy = y + cy - halfSide;
var scx = x + cx - halfSide;
if (scy >= 0 && scy < sh && scx >= 0 && scx < sw) {
var srcOff = scy * sw + scx;
var wt = weights[cy * side + cx];
a += mask[srcOff] * wt;
}
}
}
maskResult[so] = a === 255 * 8 ? 255 : 0;
}
}
return maskResult;
}
function dilateMask(mask, sw, sh) {
var weights = [1, 1, 1, 1, 1, 1, 1, 1, 1];
var side = Math.round(Math.sqrt(weights.length));
var halfSide = Math.floor(side / 2);
var maskResult = [];
for (var y = 0; y < sh; y++) {
for (var x = 0; x < sw; x++) {
var so = y * sw + x;
var a = 0;
for (var cy = 0; cy < side; cy++) {
for (var cx = 0; cx < side; cx++) {
var scy = y + cy - halfSide;
var scx = x + cx - halfSide;
if (scy >= 0 && scy < sh && scx >= 0 && scx < sw) {
var srcOff = scy * sw + scx;
var wt = weights[cy * side + cx];
a += mask[srcOff] * wt;
}
}
}
maskResult[so] = a >= 255 * 4 ? 255 : 0;
}
}
return maskResult;
}
function smoothEdgeMask(mask, sw, sh) {
var weights = [1 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 9];
var side = Math.round(Math.sqrt(weights.length));
var halfSide = Math.floor(side / 2);
var maskResult = [];
for (var y = 0; y < sh; y++) {
for (var x = 0; x < sw; x++) {
var so = y * sw + x;
var a = 0;
for (var cy = 0; cy < side; cy++) {
for (var cx = 0; cx < side; cx++) {
var scy = y + cy - halfSide;
var scx = x + cx - halfSide;
if (scy >= 0 && scy < sh && scx >= 0 && scx < sw) {
var srcOff = scy * sw + scx;
var wt = weights[cy * side + cx];
a += mask[srcOff] * wt;
}
}
}
maskResult[so] = a;
}
}
return maskResult;
}
/**
* Mask Filter
* @function
* @name Mask
* @memberof Konva.Filters
* @param {Object} imageData
* @example
* node.cache();
* node.filters([Konva.Filters.Mask]);
* node.threshold(200);
*/
const Mask = function (imageData) {
// Detect pixels close to the background color
var threshold = this.threshold(), mask = backgroundMask(imageData, threshold);
if (mask) {
// Erode
mask = erodeMask(mask, imageData.width, imageData.height);
// Dilate
mask = dilateMask(mask, imageData.width, imageData.height);
// Gradient
mask = smoothEdgeMask(mask, imageData.width, imageData.height);
// Apply mask
applyMask(imageData, mask);
}
return imageData;
};
Factory.addGetterSetter(Node, 'threshold', 0, getNumberValidator(), Factory.afterSetFilter);
/**
* Noise Filter. Randomly adds or substracts to the color channels
* @function
* @name Noise
* @memberof Konva.Filters
* @param {Object} imageData
* @author ippo615
* @example
* node.cache();
* node.filters([Konva.Filters.Noise]);
* node.noise(0.8);
*/
const Noise = function (imageData) {
var amount = this.noise() * 255, data = imageData.data, nPixels = data.length, half = amount / 2, i;
for (i = 0; i < nPixels; i += 4) {
data[i + 0] += half - 2 * half * Math.random();
data[i + 1] += half - 2 * half * Math.random();
data[i + 2] += half - 2 * half * Math.random();
}
};
Factory.addGetterSetter(Node, 'noise', 0.2, getNumberValidator(), Factory.afterSetFilter);
/**
* get/set noise amount. Must be a value between 0 and 1. Use with {@link Konva.Filters.Noise} filter.
* @name Konva.Node#noise
* @method
* @param {Number} noise
* @returns {Number}
*/
/*eslint-disable max-depth */
/**
* Pixelate Filter. Averages groups of pixels and redraws
* them as larger pixels
* @function
* @name Pixelate
* @memberof Konva.Filters
* @param {Object} imageData
* @author ippo615
* @example
* node.cache();
* node.filters([Konva.Filters.Pixelate]);
* node.pixelSize(10);
*/
const Pixelate = function (imageData) {
var pixelSize = Math.ceil(this.pixelSize()), width = imageData.width, height = imageData.height, x, y, i,
//pixelsPerBin = pixelSize * pixelSize,
red, green, blue, alpha, nBinsX = Math.ceil(width / pixelSize), nBinsY = Math.ceil(height / pixelSize), xBinStart, xBinEnd, yBinStart, yBinEnd, xBin, yBin, pixelsInBin, data = imageData.data;
if (pixelSize <= 0) {
Util.error('pixelSize value can not be <= 0');
return;
}
for (xBin = 0; xBin < nBinsX; xBin += 1) {
for (yBin = 0; yBin < nBinsY; yBin += 1) {
// Initialize the color accumlators to 0
red = 0;
green = 0;
blue = 0;
alpha = 0;
// Determine which pixels are included in this bin
xBinStart = xBin * pixelSize;
xBinEnd = xBinStart + pixelSize;
yBinStart = yBin * pixelSize;
yBinEnd = yBinStart + pixelSize;
// Add all of the pixels to this bin!
pixelsInBin = 0;
for (x = xBinStart; x < xBinEnd; x += 1) {
if (x >= width) {
continue;
}
for (y = yBinStart; y < yBinEnd; y += 1) {
if (y >= height) {
continue;
}
i = (width * y + x) * 4;
red += data[i + 0];
green += data[i + 1];
blue += data[i + 2];
alpha += data[i + 3];
pixelsInBin += 1;
}
}
// Make sure the channels are between 0-255
red = red / pixelsInBin;
green = green / pixelsInBin;
blue = blue / pixelsInBin;
alpha = alpha / pixelsInBin;
// Draw this bin
for (x = xBinStart; x < xBinEnd; x += 1) {
if (x >= width) {
continue;
}
for (y = yBinStart; y < yBinEnd; y += 1) {
if (y >= height) {
continue;
}
i = (width * y + x) * 4;
data[i + 0] = red;
data[i + 1] = green;
data[i + 2] = blue;
data[i + 3] = alpha;
}
}
}
}
};
Factory.addGetterSetter(Node, 'pixelSize', 8, getNumberValidator(), Factory.afterSetFilter);
/**
* get/set pixel size. Use with {@link Konva.Filters.Pixelate} filter.
* @name Konva.Node#pixelSize
* @method
* @param {Integer} pixelSize
* @returns {Integer}
*/
/**
* Posterize Filter. Adjusts the channels so that there are no more
* than n different values for that channel. This is also applied
* to the alpha channel.
* @function
* @name Posterize
* @author ippo615
* @memberof Konva.Filters
* @param {Object} imageData
* @example
* node.cache();
* node.filters([Konva.Filters.Posterize]);
* node.levels(0.8); // between 0 and 1
*/
const Posterize = function (imageData) {
// level must be between 1 and 255
var levels = Math.round(this.levels() * 254) + 1, data = imageData.data, len = data.length, scale = 255 / levels, i;
for (i = 0; i < len; i += 1) {
data[i] = Math.floor(data[i] / scale) * scale;
}
};
Factory.addGetterSetter(Node, 'levels', 0.5, getNumberValidator(), Factory.afterSetFilter);
/**
* get/set levels. Must be a number between 0 and 1. Use with {@link Konva.Filters.Posterize} filter.
* @name Konva.Node#levels
* @method
* @param {Number} level between 0 and 1
* @returns {Number}
*/
/**
* RGB Filter
* @function
* @name RGB
* @memberof Konva.Filters
* @param {Object} imageData
* @author ippo615
* @example
* node.cache();
* node.filters([Konva.Filters.RGB]);
* node.blue(120);
* node.green(200);
*/
const RGB = function (imageData) {
var data = imageData.data, nPixels = data.length, red = this.red(), green = this.green(), blue = this.blue(), i, brightness;
for (i = 0; i < nPixels; i += 4) {
brightness =
(0.34 * data[i] + 0.5 * data[i + 1] + 0.16 * data[i + 2]) / 255;
data[i] = brightness * red; // r
data[i + 1] = brightness * green; // g
data[i + 2] = brightness * blue; // b
data[i + 3] = data[i + 3]; // alpha
}
};
Factory.addGetterSetter(Node, 'red', 0, function (val) {
this._filterUpToDate = false;
if (val > 255) {
return 255;
}
else if (val < 0) {
return 0;
}
else {
return Math.round(val);
}
});
/**
* get/set filter red value. Use with {@link Konva.Filters.RGB} filter.
* @name red
* @method
* @memberof Konva.Node.prototype
* @param {Integer} red value between 0 and 255
* @returns {Integer}
*/
Factory.addGetterSetter(Node, 'green', 0, function (val) {
this._filterUpToDate = false;
if (val > 255) {
return 255;
}
else if (val < 0) {
return 0;
}
else {
return Math.round(val);
}
});
/**
* get/set filter green value. Use with {@link Konva.Filters.RGB} filter.
* @name green
* @method
* @memberof Konva.Node.prototype
* @param {Integer} green value between 0 and 255
* @returns {Integer}
*/
Factory.addGetterSetter(Node, 'blue', 0, RGBComponent, Factory.afterSetFilter);
/**
* get/set filter blue value. Use with {@link Konva.Filters.RGB} filter.
* @name blue
* @method
* @memberof Konva.Node.prototype
* @param {Integer} blue value between 0 and 255
* @returns {Integer}
*/
/**
* RGBA Filter
* @function
* @name RGBA
* @memberof Konva.Filters
* @param {Object} imageData
* @author codefo
* @example
* node.cache();
* node.filters([Konva.Filters.RGBA]);
* node.blue(120);
* node.green(200);
* node.alpha(0.3);
*/
const RGBA = function (imageData) {
var data = imageData.data, nPixels = data.length, red = this.red(), green = this.green(), blue = this.blue(), alpha = this.alpha(), i, ia;
for (i = 0; i < nPixels; i += 4) {
ia = 1 - alpha;
data[i] = red * alpha + data[i] * ia; // r
data[i + 1] = green * alpha + data[i + 1] * ia; // g
data[i + 2] = blue * alpha + data[i + 2] * ia; // b
}
};
Factory.addGetterSetter(Node, 'red', 0, function (val) {
this._filterUpToDate = false;
if (val > 255) {
return 255;
}
else if (val < 0) {
return 0;
}
else {
return Math.round(val);
}
});
/**
* get/set filter red value. Use with {@link Konva.Filters.RGBA} filter.
* @name red
* @method
* @memberof Konva.Node.prototype
* @param {Integer} red value between 0 and 255
* @returns {Integer}
*/
Factory.addGetterSetter(Node, 'green', 0, function (val) {
this._filterUpToDate = false;
if (val > 255) {
return 255;
}
else if (val < 0) {
return 0;
}
else {
return Math.round(val);
}
});
/**
* get/set filter green value. Use with {@link Konva.Filters.RGBA} filter.
* @name green
* @method
* @memberof Konva.Node.prototype
* @param {Integer} green value between 0 and 255
* @returns {Integer}
*/
Factory.addGetterSetter(Node, 'blue', 0, RGBComponent, Factory.afterSetFilter);
/**
* get/set filter blue value. Use with {@link Konva.Filters.RGBA} filter.
* @name blue
* @method
* @memberof Konva.Node.prototype
* @param {Integer} blue value between 0 and 255
* @returns {Integer}
*/
Factory.addGetterSetter(Node, 'alpha', 1, function (val) {
this._filterUpToDate = false;
if (val > 1) {
return 1;
}
else if (val < 0) {
return 0;
}
else {
return val;
}
});
/**
* get/set filter alpha value. Use with {@link Konva.Filters.RGBA} filter.
* @name alpha
* @method
* @memberof Konva.Node.prototype
* @param {Float} alpha value between 0 and 1
* @returns {Float}
*/
// based on https://stackoverflow.com/questions/1061093/how-is-a-sepia-tone-created
/**
* @function
* @name Sepia
* @memberof Konva.Filters
* @param {Object} imageData
* @example
* node.cache();
* node.filters([Konva.Filters.Sepia]);
*/
const Sepia = function (imageData) {
var data = imageData.data, nPixels = data.length, i, r, g, b;
for (i = 0; i < nPixels; i += 4) {
r = data[i + 0];
g = data[i + 1];
b = data[i + 2];
data[i + 0] = Math.min(255, r * 0.393 + g * 0.769 + b * 0.189);
data[i + 1] = Math.min(255, r * 0.349 + g * 0.686 + b * 0.168);
data[i + 2] = Math.min(255, r * 0.272 + g * 0.534 + b * 0.131);
}
};
/**
* Solarize Filter
* Pixastic Lib - Solarize filter - v0.1.0
* Copyright (c) 2008 Jacob Seidelin, jseidelin@nihilogic.dk, http://blog.nihilogic.dk/
* License: [http://www.pixastic.com/lib/license.txt]
* @function
* @name Solarize
* @memberof Konva.Filters
* @param {Object} imageData
* @example
* node.cache();
* node.filters([Konva.Filters.Solarize]);
*/
const Solarize = function (imageData) {
var data = imageData.data, w = imageData.width, h = imageData.height, w4 = w * 4, y = h;
do {
var offsetY = (y - 1) * w4;
var x = w;
do {
var offset = offsetY + (x - 1) * 4;
var r = data[offset];
var g = data[offset + 1];
var b = data[offset + 2];
if (r > 127) {
r = 255 - r;
}
if (g > 127) {
g = 255 - g;
}
if (b > 127) {
b = 255 - b;
}
data[offset] = r;
data[offset + 1] = g;
data[offset + 2] = b;
} while (--x);
} while (--y);
};
/**
* Threshold Filter. Pushes any value above the mid point to
* the max and any value below the mid point to the min.
* This affects the alpha channel.
* @function
* @name Threshold
* @memberof Konva.Filters
* @param {Object} imageData
* @author ippo615
* @example
* node.cache();
* node.filters([Konva.Filters.Threshold]);
* node.threshold(0.1);
*/
const Threshold = function (imageData) {
var level = this.threshold() * 255, data = imageData.data, len = data.length, i;
for (i = 0; i < len; i += 1) {
data[i] = data[i] < level ? 0 : 255;
}
};
Factory.addGetterSetter(Node, 'threshold', 0.5, getNumberValidator(), Factory.afterSetFilter);
/**
* get/set threshold. Must be a value between 0 and 1. Use with {@link Konva.Filters.Threshold} or {@link Konva.Filters.Mask} filter.
* @name threshold
* @method
* @memberof Konva.Node.prototype
* @param {Number} threshold
* @returns {Number}
*/
// we need to import core of the Konva and then extend it with all additional objects
const Konva = Konva$1.Util._assign(Konva$1, {
Arc,
Arrow,
Circle,
Ellipse,
Image,
Label,
Tag,
Line,
Path,
Rect,
RegularPolygon,
Ring,
Sprite,
Star,
Text,
TextPath,
Transformer,
Wedge,
/**
* @namespace Filters
* @memberof Konva
*/
Filters: {
Blur,
Brighten,
Contrast,
Emboss,
Enhance,
Grayscale,
HSL,
HSV,
Invert,
Kaleidoscope,
Mask,
Noise,
Pixelate,
Posterize,
RGB,
RGBA,
Sepia,
Solarize,
Threshold,
},
});
return Konva;
}));
|
/*!
* lightgallery | 2.2.0-beta.1 | July 15th 2021
* http://www.lightgalleryjs.com/
* Copyright (c) 2020 Sachin Neravath;
* @license GPLv3
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.lgAutoplay = factory());
}(this, (function () { 'use strict';
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
var __assign = function() {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
/**
* List of lightGallery events
* All events should be documented here
* Below interfaces are used to build the website documentations
* */
var lGEvents = {
afterAppendSlide: 'lgAfterAppendSlide',
init: 'lgInit',
hasVideo: 'lgHasVideo',
containerResize: 'lgContainerResize',
updateSlides: 'lgUpdateSlides',
afterAppendSubHtml: 'lgAfterAppendSubHtml',
beforeOpen: 'lgBeforeOpen',
afterOpen: 'lgAfterOpen',
slideItemLoad: 'lgSlideItemLoad',
beforeSlide: 'lgBeforeSlide',
afterSlide: 'lgAfterSlide',
posterClick: 'lgPosterClick',
dragStart: 'lgDragStart',
dragMove: 'lgDragMove',
dragEnd: 'lgDragEnd',
beforeNextSlide: 'lgBeforeNextSlide',
beforePrevSlide: 'lgBeforePrevSlide',
beforeClose: 'lgBeforeClose',
afterClose: 'lgAfterClose',
rotateLeft: 'lgRotateLeft',
rotateRight: 'lgRotateRight',
flipHorizontal: 'lgFlipHorizontal',
flipVertical: 'lgFlipVertical',
};
var autoplaySettings = {
autoplay: true,
slideShowAutoplay: false,
slideShowInterval: 5000,
progressBar: true,
forceSlideShowAutoplay: false,
autoplayControls: true,
appendAutoplayControlsTo: '.lg-toolbar',
};
/**
* Creates the autoplay plugin.
* @param {object} element - lightGallery element
*/
var Autoplay = /** @class */ (function () {
function Autoplay(instance) {
this.core = instance;
// extend module default settings with lightGallery core settings
this.settings = __assign(__assign({}, autoplaySettings), this.core.settings);
return this;
}
Autoplay.prototype.init = function () {
var _this = this;
if (!this.settings.autoplay) {
return;
}
this.interval = false;
// Identify if slide happened from autoplay
this.fromAuto = true;
// Identify if autoplay canceled from touch/drag
this.pausedOnTouchDrag = false;
this.pausedOnSlideChange = false;
// append autoplay controls
if (this.settings.autoplayControls) {
this.controls();
}
// Create progress bar
if (this.settings.progressBar) {
this.core.$lgContent.append('<div class="lg-progress-bar"><div class="lg-progress"></div></div>');
}
// Start autoplay
if (this.settings.slideShowAutoplay) {
this.core.LGel.once(lGEvents.slideItemLoad + ".autoplay", function () {
_this.startAuto();
});
}
// cancel interval on touchstart and dragstart
this.core.LGel.on(lGEvents.dragStart + ".autoplay touchstart.lg.autoplay", function () {
if (_this.interval) {
_this.cancelAuto();
_this.pausedOnTouchDrag = true;
}
});
// restore autoplay if autoplay canceled from touchstart / dragstart
this.core.LGel.on(lGEvents.dragEnd + ".autoplay touchend.lg.autoplay", function () {
if (!_this.interval && _this.pausedOnTouchDrag) {
_this.startAuto();
_this.pausedOnTouchDrag = false;
}
});
this.core.LGel.on(lGEvents.beforeSlide + ".autoplay", function () {
_this.showProgressBar();
if (!_this.fromAuto && _this.interval) {
_this.cancelAuto();
_this.pausedOnSlideChange = true;
}
else {
_this.pausedOnSlideChange = false;
}
_this.fromAuto = false;
});
// restore autoplay if autoplay canceled from touchstart / dragstart
this.core.LGel.on(lGEvents.afterSlide + ".autoplay", function () {
if (_this.pausedOnSlideChange &&
!_this.interval &&
_this.settings.forceSlideShowAutoplay) {
_this.startAuto();
_this.pausedOnSlideChange = false;
}
});
// set progress
this.showProgressBar();
};
Autoplay.prototype.showProgressBar = function () {
var _this = this;
if (this.settings.progressBar && this.fromAuto) {
var _$progressBar_1 = this.core.outer.find('.lg-progress-bar');
var _$progress_1 = this.core.outer.find('.lg-progress');
if (this.interval) {
_$progress_1.removeAttr('style');
_$progressBar_1.removeClass('lg-start');
setTimeout(function () {
_$progress_1.css('transition', 'width ' +
(_this.core.settings.speed +
_this.settings.slideShowInterval) +
'ms ease 0s');
_$progressBar_1.addClass('lg-start');
}, 20);
}
}
};
// Manage autoplay via play/stop buttons
Autoplay.prototype.controls = function () {
var _this = this;
var _html = '<button aria-label="Toggle autoplay" type="button" class="lg-autoplay-button lg-icon"></button>';
// Append autoplay controls
this.core.outer
.find(this.settings.appendAutoplayControlsTo)
.append(_html);
this.core.outer
.find('.lg-autoplay-button')
.first()
.on('click.lg.autoplay', function () {
if (_this.core.outer.hasClass('lg-show-autoplay')) {
_this.cancelAuto();
}
else {
if (!_this.interval) {
_this.startAuto();
}
}
});
};
// Autostart gallery
Autoplay.prototype.startAuto = function () {
var _this = this;
this.core.outer
.find('.lg-progress')
.css('transition', 'width ' +
(this.core.settings.speed +
this.settings.slideShowInterval) +
'ms ease 0s');
this.core.outer.addClass('lg-show-autoplay');
this.core.outer.find('.lg-progress-bar').addClass('lg-start');
this.interval = setInterval(function () {
if (_this.core.index + 1 < _this.core.galleryItems.length) {
_this.core.index++;
}
else {
_this.core.index = 0;
}
_this.fromAuto = true;
_this.core.slide(_this.core.index, false, false, 'next');
}, this.core.settings.speed + this.settings.slideShowInterval);
};
// cancel Autostart
Autoplay.prototype.cancelAuto = function () {
if (this.interval) {
this.core.outer.find('.lg-progress').removeAttr('style');
this.core.outer.removeClass('lg-show-autoplay');
this.core.outer.find('.lg-progress-bar').removeClass('lg-start');
}
clearInterval(this.interval);
this.interval = false;
};
Autoplay.prototype.closeGallery = function () {
this.cancelAuto();
};
Autoplay.prototype.destroy = function () {
if (this.settings.autoplay) {
this.core.outer.find('.lg-progress-bar').remove();
}
// Remove all event listeners added by autoplay plugin
this.core.LGel.off('.lg.autoplay');
this.core.LGel.off('.autoplay');
};
return Autoplay;
}());
return Autoplay;
})));
//# sourceMappingURL=lg-autoplay.umd.js.map
|
rolls = {
name: "rolls",
ingredients: [wheat] //depends on the global wheat.js being available
}; |
/* global ngDescribe, it, beforeEach, afterEach */
angular.module('BeforeAndAfterA', [])
.value('foo', 'bar');
ngDescribe({
name: 'before and after example',
module: 'BeforeAndAfterA',
inject: 'foo',
only: false,
verbose: false,
tests: function (deps) {
var localFoo;
beforeEach(function () {
la(deps.foo === 'bar');
localFoo = deps.foo;
});
it('test 1: has correct value foo', function () {
la(localFoo === 'bar');
la(deps.foo === 'bar', 'dependencies still has foo', deps);
});
it('test 2: has correct value foo', function () {
la(localFoo === 'bar');
la(deps.foo === 'bar', 'dependencies still has foo', deps);
});
afterEach(function insideNgDescribeAfterEach() {
la(localFoo === 'bar', 'localFoo is', localFoo);
la(deps.foo === 'bar', 'dependencies still has foo', deps);
});
}
});
|
var _ = require("lodash");
var async = require("async");
var request = require([__dirname, "request"].join("/"));
module.exports = {
dataset: function(code, options, fn){
if(_.isFunction(options) && _.isUndefined(fn)){
fn = options;
options = {};
}
var format = options.format || "json";
delete options.format;
var qs = options;
qs.auth_token = this.auth_token;
var config = {
uri: ["api", this.api_version, "datasets", code.source, code.table].join("/"),
format: format,
qs: qs,
proxy: this.proxy
}
request.create(config, fn);
},
metadata: function(code, options, fn){
options.exclude_data = true;
this.dataset(code, options, fn);
},
multiset: function(codes, options, fn){
if(_.isFunction(options) && _.isUndefined(fn)){
fn = options;
options = {};
}
var format = options.format || "json";
delete options.format;
var qs = options;
qs.auth_token = this.auth_token;
qs.columns = _.map(codes, function(code){
var combined_code = [code.source, code.table].join(".");
code = _.defaults(code, {
columns: []
});
columns = code.columns.join(".");
if(!_.isEmpty(columns))
combined_code = [combined_code, columns].join(".");
return combined_code;
}).join(",");
var config = {
uri: ["api", this.api_version, "multisets"].join("/"),
format: format,
qs: qs,
proxy: this.proxy
}
request.create(config, fn);
},
favorites: function(options, fn){
if(_.isFunction(options) && _.isUndefined(fn)){
fn = options;
options = {};
}
var format = options.format || "json";
delete options.format;
var qs = options;
qs.auth_token = this.auth_token;
var config = {
uri: ["api", this.api_version, "current_user", "collections", "datasets", "favourites"].join("/"),
format: format,
qs: qs,
proxy: this.proxy
}
request.create(config, fn);
},
search: function(terms, options, fn){
if(_.isFunction(options) && _.isUndefined(fn)){
fn = options;
options = {};
}
var format = options.format || "json";
delete options.format;
var qs = options;
qs.auth_token = this.auth_token;
qs.query = terms.replace(" ", "+");
var config = {
uri: ["api", this.api_version, "datasets"].join("/"),
format: format,
qs: qs,
proxy: this.proxy
}
request.create(config, fn);
}
}
|
describe('stringView', function() {
beforeEach(function() {
var that = this, done = false;
require(['stringUtil', 'jqueryCookie'], function(String) {
that.String = String;
done = true;
});
//等待初始化完成
waitsFor(function() {
return done;
}, "Create Models");
});
afterEach(function() {
});
describe('字符串格式化', function() {
it('string', function() {
var str = "my name is {0}";
var actual = this.String.format(str, 'ada');
expect(actual).toEqual("my name is ada");
});
it('html', function() {
var str = "my name is {0}";
var actual = this.String.format(str, '<div>123</div>');
expect(actual).toEqual("my name is <div>123</div>");
});
it('two string', function() {
var str = "my name is '{0} {1}'";
var actual = this.String.format(str, 'ada', 'alax');
expect(actual).toEqual("my name is 'ada alax'");
});
it('undefined', function() {
var str = "my name is '{0}'";
var actual = this.String.format(str, undefined);
expect(actual).toEqual("my name is 'undefined'");
});
it('null', function() {
var str = "my name is '{0}'";
var actual = this.String.format(str, null);
expect(actual).toEqual("my name is 'null'");
});
it('true', function() {
var str = "my name is '{0}'";
var actual = this.String.format(str, true);
expect(actual).toEqual("my name is 'true'");
});
});
describe('字符串分割', function() {
it('split', function() {
var str = "周边 长途 户外";
var actuals = str.split(" ");
expect(actuals.join(",")).toEqual("周边,长途,户外");
var str = "周边 长途 户外";
var actuals = str.split(" ");
expect(actuals.join(",")).toEqual("周边,,长途,户外");
var str = "周边 长途 户外";
var actuals = str.split(" ");
actuals = _.filter(actuals, function(tag){ return !!tag; });
expect(actuals.join(",")).toEqual("周边,长途,户外");
expect(!'').toBe(true);
expect(!"").toBe(true);
expect(!0).toBe(true);
expect(!+'0').toBe(true);
expect(!null).toBe(true);
expect(!undefined).toBe(true);
expect(!{}).toBe(false);
expect(![]).toBe(false);
expect(!'0').toBe(false);
expect(!' ').toBe(false);
expect(+'').toBe(0);
expect(+null).toBe(0);
//expect(+undefined).toBe(0);
expect(+'2').toBe(2);
expect(!-1).toBe(false);
});
});
describe('cookie', function() {
it('空cookie', function() {
//console.log($.cookie('123'));
var cook = $.cookie('123');
expect(!cook).toBe(true);
});
});
describe('字符串长度', function() {
it('length', function() {
//console.log($.cookie('123'));
var str = '最多能';
expect(str.length).toBe(3);
});
});
}); |
const AnsiToHtml = require('ansi-to-html')
const { Writable } = require('stream')
const fakeWindow = require('../fakeWindow')
class BrowserWindowWritable extends Writable {
constructor(streamName) {
super()
const $fakeBrowserWindow = fakeWindow(
document,
streamName.toUpperCase(),
'cucumber-electron-terminal',
)
document.body.appendChild($fakeBrowserWindow)
this.$terminalElement = $fakeBrowserWindow.querySelector('.cucumber-electron-window-pane')
document.body.appendChild($fakeBrowserWindow)
this.ansiToHtml = new AnsiToHtml()
}
_write(chunk, encoding, callback) {
this.appendTag(this.escapeTags(chunk.toString('utf-8')))
callback()
}
escapeTags(argument) {
return argument.toString().replace(/</g, '<').replace(/>/g, '>')
}
appendTag(string) {
const pre = document.createElement('pre')
pre.innerHTML = this.ansiToHtml.toHtml(string)
this.$terminalElement.appendChild(pre)
}
}
module.exports = BrowserWindowWritable
|
/* */
'use strict';
function ZStream() {
/* next input byte */
this.input = null; // JS specific, because we have no pointers
this.next_in = 0;
/* number of bytes available at input */
this.avail_in = 0;
/* total number of input bytes read so far */
this.total_in = 0;
/* next output byte should be put there */
this.output = null; // JS specific, because we have no pointers
this.next_out = 0;
/* remaining free space at output */
this.avail_out = 0;
/* total number of bytes output so far */
this.total_out = 0;
/* last error message, NULL if no error */
this.msg = ''/*Z_NULL*/;
/* not visible by applications */
this.state = null;
/* best guess about the data type: binary or text */
this.data_type = 2/*Z_UNKNOWN*/;
/* adler32 value of the uncompressed data */
this.adler = 0;
}
module.exports = ZStream; |
/** @ignore */
import AbstractInstruction from './AbstractInstruction';
export default class InstructionWrapper extends AbstractInstruction {
constructor(instruction) {
super(instruction.methodInfo, instruction.idx, instruction.opcode);
this.instruction = instruction;
}
get size() {
return this.instruction.size;
}
read(buffer) {
this.instruction.read(buffer);
}
write(buffer) {
this.instruction.write(buffer);
}
}
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zM4 12c0-4.42 3.58-8 8-8 1.85 0 3.55.63 4.9 1.69L5.69 16.9C4.63 15.55 4 13.85 4 12zm8 8c-1.85 0-3.55-.63-4.9-1.69L18.31 7.1C19.37 8.45 20 10.15 20 12c0 4.42-3.58 8-8 8z"
}), 'BlockOutlined');
exports.default = _default; |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = require('babel-runtime/helpers/inherits');
var _inherits3 = _interopRequireDefault(_inherits2);
var _propTypes = require('prop-types');
var _propTypes2 = _interopRequireDefault(_propTypes);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
exports['default'] = function (componentName, defaultLocale) {
return function (Component) {
var ComponentWithStatics = Component;
return _a = function (_Component) {
(0, _inherits3['default'])(_a, _Component);
function _a() {
(0, _classCallCheck3['default'])(this, _a);
return (0, _possibleConstructorReturn3['default'])(this, (_a.__proto__ || Object.getPrototypeOf(_a)).apply(this, arguments));
}
(0, _createClass3['default'])(_a, [{
key: 'getLocale',
value: function getLocale() {
var antLocale = this.context.antLocale;
var localeFromContext = antLocale && antLocale[componentName];
var localeFromProps = this.props.locale || {};
return Object.assign({}, defaultLocale, localeFromContext || {}, localeFromProps);
}
}]);
return _a;
}(Component), _a.propTypes = ComponentWithStatics.propTypes, _a.defaultProps = ComponentWithStatics.defaultProps, _a.contextTypes = Object.assign({}, ComponentWithStatics.context || {}, { antLocale: _propTypes2['default'].object }), _a;
var _a;
};
};
module.exports = exports['default']; |
/* Controllers */
angular.module('core')
.controller('SigninCtrl', ['$rootScope', '$scope', '$location', '$window', '$timeout', 'Auth',
function ($rootScope, $scope, $location, $window, $timeout, Auth) {
$scope.display_forgot_icon = false;
$scope.hideForgotIconOnBlur = function () {
// How long it takes to process the click event ~ 200ms
$timeout( function () {
$scope.display_forgot_icon = false;
}, 200);
};
$scope.signin = function() {
$scope.$parent.error = false;
//Set loading to false for deactivate the entire loading animation
$scope.$parent.loading = true;
Auth.login({
email: $scope.username,
password: $scope.password
},function (res) {
$scope.$parent.error = false;
$scope.$parent.loading = false;
$location.path($rootScope.transition || '/');
},function (err) {
$scope.$parent.error = true;
$scope.$parent.loading = false;
});
};
$scope.loginOauth = function (provider) {
$window.location.href = '/auth/' + provider;
};
}
]); |
var apiUrl = process.env.CLOUD ?
'http://' + process.env.CLIENT_DOMAIN + process.env.CLIENT_API_PATH :
'http://' + process.env.CLIENT_DOMAIN + ':' + process.env.PORT + process.env.CLIENT_API_PATH;
exports = module.exports = {
environment: process.env.NODE_ENV,
port: process.env.PORT,
api: {
url: apiUrl
}
};
|
var Logger = require('./logger');
var logger = new Logger();
module.exports = logger;
|
'use strict';
angular.module('sv')
.controller('NavbarCtrl', function ($scope) {
$scope.date = new Date();
});
|
/**
* @license Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.add( 'floatpanel', {
requires: 'panel'
} );
( function() {
var panels = {};
function getPanel( editor, doc, parentElement, definition, level ) {
// Generates the panel key: docId-eleId-skinName-langDir[-uiColor][-CSSs][-level]
var key = CKEDITOR.tools.genKey( doc.getUniqueId(), parentElement.getUniqueId(), editor.lang.dir, editor.uiColor || '', definition.css || '', level || '' ),
panel = panels[ key ];
if ( !panel ) {
panel = panels[ key ] = new CKEDITOR.ui.panel( doc, definition );
panel.element = parentElement.append( CKEDITOR.dom.element.createFromHtml( panel.render( editor ), doc ) );
panel.element.setStyles( {
display: 'none',
position: 'absolute'
} );
}
return panel;
}
/**
* Represents a floating panel UI element.
*
* It is reused by rich combos, color combos, menus, etc.
* and it renders its content using {@link CKEDITOR.ui.panel}.
*
* @class
* @todo
*/
CKEDITOR.ui.floatPanel = CKEDITOR.tools.createClass( {
/**
* Creates a floatPanel class instance.
*
* @constructor
* @param {CKEDITOR.editor} editor
* @param {CKEDITOR.dom.element} parentElement
* @param {Object} definition Definition of the panel that will be floating.
* @param {Number} level
*/
$: function( editor, parentElement, definition, level ) {
definition.forceIFrame = 1;
// In case of editor with floating toolbar append panels that should float
// to the main UI element.
if ( definition.toolbarRelated && editor.elementMode == CKEDITOR.ELEMENT_MODE_INLINE )
parentElement = CKEDITOR.document.getById( 'cke_' + editor.name );
var doc = parentElement.getDocument(),
panel = getPanel( editor, doc, parentElement, definition, level || 0 ),
element = panel.element,
iframe = element.getFirst(),
that = this;
// Disable native browser menu. (http://dev.ckeditor.com/ticket/4825)
element.disableContextMenu();
this.element = element;
this._ = {
editor: editor,
// The panel that will be floating.
panel: panel,
parentElement: parentElement,
definition: definition,
document: doc,
iframe: iframe,
children: [],
dir: editor.lang.dir,
showBlockParams: null
};
editor.on( 'mode', hide );
editor.on( 'resize', hide );
// When resize of the window is triggered floatpanel should be repositioned according to new dimensions.
// http://dev.ckeditor.com/ticket/11724. Fixes issue with undesired panel hiding on Android and iOS.
doc.getWindow().on( 'resize', function() {
this.reposition();
}, this );
// We need a wrapper because events implementation doesn't allow to attach
// one listener more than once for the same event on the same object.
// Remember that floatPanel#hide is shared between all instances.
function hide() {
that.hide();
}
},
proto: {
/**
* @todo
*/
addBlock: function( name, block ) {
return this._.panel.addBlock( name, block );
},
/**
* @todo
*/
addListBlock: function( name, multiSelect ) {
return this._.panel.addListBlock( name, multiSelect );
},
/**
* @todo
*/
getBlock: function( name ) {
return this._.panel.getBlock( name );
},
/**
* Shows the panel block.
*
* @param {String} name
* @param {CKEDITOR.dom.element} offsetParent Positioned parent.
* @param {Number} corner
*
* * For LTR (left to right) oriented editor:
* * `1` = top-left
* * `2` = top-right
* * `3` = bottom-right
* * `4` = bottom-left
* * For RTL (right to left):
* * `1` = top-right
* * `2` = top-left
* * `3` = bottom-left
* * `4` = bottom-right
*
* @param {Number} [offsetX=0]
* @param {Number} [offsetY=0]
* @param {Function} [callback] A callback function executed when block positioning is done.
* @todo what do exactly these params mean (especially corner)?
*/
showBlock: function( name, offsetParent, corner, offsetX, offsetY, callback ) {
var panel = this._.panel,
block = panel.showBlock( name );
this._.showBlockParams = [].slice.call( arguments );
this.allowBlur( false );
// Record from where the focus is when open panel.
var editable = this._.editor.editable();
this._.returnFocus = editable.hasFocus ? editable : new CKEDITOR.dom.element( CKEDITOR.document.$.activeElement );
this._.hideTimeout = 0;
var element = this.element,
iframe = this._.iframe,
// Edge prefers iframe's window to the iframe, just like the rest of the browsers (http://dev.ckeditor.com/ticket/13143).
focused = CKEDITOR.env.ie && !CKEDITOR.env.edge ? iframe : new CKEDITOR.dom.window( iframe.$.contentWindow ),
doc = element.getDocument(),
positionedAncestor = this._.parentElement.getPositionedAncestor(),
position = offsetParent.getDocumentPosition( doc ),
positionedAncestorPosition = positionedAncestor ? positionedAncestor.getDocumentPosition( doc ) : { x: 0, y: 0 },
rtl = this._.dir == 'rtl',
left = position.x + ( offsetX || 0 ) - positionedAncestorPosition.x,
top = position.y + ( offsetY || 0 ) - positionedAncestorPosition.y;
// Floating panels are off by (-1px, 0px) in RTL mode. (http://dev.ckeditor.com/ticket/3438)
if ( rtl && ( corner == 1 || corner == 4 ) )
left += offsetParent.$.offsetWidth;
else if ( !rtl && ( corner == 2 || corner == 3 ) )
left += offsetParent.$.offsetWidth - 1;
if ( corner == 3 || corner == 4 )
top += offsetParent.$.offsetHeight - 1;
// Memorize offsetParent by it's ID.
this._.panel._.offsetParentId = offsetParent.getId();
element.setStyles( {
top: top + 'px',
left: 0,
display: ''
} );
// Don't use display or visibility style because we need to
// calculate the rendering layout later and focus the element.
element.setOpacity( 0 );
// To allow the context menu to decrease back their width
element.getFirst().removeStyle( 'width' );
// Report to focus manager.
this._.editor.focusManager.add( focused );
// Configure the IFrame blur event. Do that only once.
if ( !this._.blurSet ) {
// With addEventListener compatible browsers, we must
// useCapture when registering the focus/blur events to
// guarantee they will be firing in all situations. (http://dev.ckeditor.com/ticket/3068, http://dev.ckeditor.com/ticket/3222 )
CKEDITOR.event.useCapture = true;
focused.on( 'blur', function( ev ) {
// As we are using capture to register the listener,
// the blur event may get fired even when focusing
// inside the window itself, so we must ensure the
// target is out of it.
if ( !this.allowBlur() || ev.data.getPhase() != CKEDITOR.EVENT_PHASE_AT_TARGET )
return;
if ( this.visible && !this._.activeChild ) {
// [iOS] Allow hide to be prevented if touch is bound
// to any parent of the iframe blur happens before touch (http://dev.ckeditor.com/ticket/10714).
if ( CKEDITOR.env.iOS ) {
if ( !this._.hideTimeout )
this._.hideTimeout = CKEDITOR.tools.setTimeout( doHide, 0, this );
} else {
doHide.call( this );
}
}
function doHide() {
// Panel close is caused by user's navigating away the focus, e.g. click outside the panel.
// DO NOT restore focus in this case.
delete this._.returnFocus;
this.hide();
}
}, this );
focused.on( 'focus', function() {
this._.focused = true;
this.hideChild();
this.allowBlur( true );
}, this );
// [iOS] if touch is bound to any parent of the iframe blur
// happens twice before touchstart and before touchend (http://dev.ckeditor.com/ticket/10714).
if ( CKEDITOR.env.iOS ) {
// Prevent false hiding on blur.
// We don't need to return focus here because touchend will fire anyway.
// If user scrolls and pointer gets out of the panel area touchend will also fire.
focused.on( 'touchstart', function() {
clearTimeout( this._.hideTimeout );
}, this );
// Set focus back to handle blur and hide panel when needed.
focused.on( 'touchend', function() {
this._.hideTimeout = 0;
this.focus();
}, this );
}
CKEDITOR.event.useCapture = false;
this._.blurSet = 1;
}
panel.onEscape = CKEDITOR.tools.bind( function( keystroke ) {
if ( this.onEscape && this.onEscape( keystroke ) === false )
return false;
}, this );
CKEDITOR.tools.setTimeout( function() {
var panelLoad = CKEDITOR.tools.bind( function() {
var target = element;
// Reset panel width as the new content can be narrower
// than the old one. (http://dev.ckeditor.com/ticket/9355)
target.removeStyle( 'width' );
if ( block.autoSize ) {
var panelDoc = block.element.getDocument(),
width = ( ( CKEDITOR.env.webkit || CKEDITOR.env.edge ) ? block.element : panelDoc.getBody() ).$.scrollWidth;
// Account for extra height needed due to IE quirks box model bug:
// http://en.wikipedia.org/wiki/Internet_Explorer_box_model_bug
// (http://dev.ckeditor.com/ticket/3426)
if ( CKEDITOR.env.ie && CKEDITOR.env.quirks && width > 0 )
width += ( target.$.offsetWidth || 0 ) - ( target.$.clientWidth || 0 ) + 3;
// Add some extra pixels to improve the appearance.
width += 10;
target.setStyle( 'width', width + 'px' );
var height = block.element.$.scrollHeight;
// Account for extra height needed due to IE quirks box model bug:
// http://en.wikipedia.org/wiki/Internet_Explorer_box_model_bug
// (http://dev.ckeditor.com/ticket/3426)
if ( CKEDITOR.env.ie && CKEDITOR.env.quirks && height > 0 )
height += ( target.$.offsetHeight || 0 ) - ( target.$.clientHeight || 0 ) + 3;
target.setStyle( 'height', height + 'px' );
// Fix IE < 8 visibility.
panel._.currentBlock.element.setStyle( 'display', 'none' ).removeStyle( 'display' );
} else {
target.removeStyle( 'height' );
}
// Flip panel layout horizontally in RTL with known width.
if ( rtl )
left -= element.$.offsetWidth;
// Pop the style now for measurement.
element.setStyle( 'left', left + 'px' );
/* panel layout smartly fit the viewport size. */
var panelElement = panel.element,
panelWindow = panelElement.getWindow(),
rect = element.$.getBoundingClientRect(),
viewportSize = panelWindow.getViewPaneSize();
// Compensation for browsers that dont support "width" and "height".
var rectWidth = rect.width || rect.right - rect.left,
rectHeight = rect.height || rect.bottom - rect.top;
// Check if default horizontal layout is impossible.
var spaceAfter = rtl ? rect.right : viewportSize.width - rect.left,
spaceBefore = rtl ? viewportSize.width - rect.right : rect.left;
if ( rtl ) {
if ( spaceAfter < rectWidth ) {
// Flip to show on right.
if ( spaceBefore > rectWidth )
left += rectWidth;
// Align to window left.
else if ( viewportSize.width > rectWidth )
left = left - rect.left;
// Align to window right, never cutting the panel at right.
else
left = left - rect.right + viewportSize.width;
}
} else if ( spaceAfter < rectWidth ) {
// Flip to show on left.
if ( spaceBefore > rectWidth )
left -= rectWidth;
// Align to window right.
else if ( viewportSize.width > rectWidth )
left = left - rect.right + viewportSize.width;
// Align to window left, never cutting the panel at left.
else
left = left - rect.left;
}
// Check if the default vertical layout is possible.
var spaceBelow = viewportSize.height - rect.top,
spaceAbove = rect.top;
if ( spaceBelow < rectHeight ) {
// Flip to show above.
if ( spaceAbove > rectHeight )
top -= rectHeight;
// Align to window bottom.
else if ( viewportSize.height > rectHeight )
top = top - rect.bottom + viewportSize.height;
// Align to top, never cutting the panel at top.
else
top = top - rect.top;
}
// If IE is in RTL, we have troubles with absolute
// position and horizontal scrolls. Here we have a
// series of hacks to workaround it. (http://dev.ckeditor.com/ticket/6146)
if ( CKEDITOR.env.ie ) {
var offsetParent = new CKEDITOR.dom.element( element.$.offsetParent ),
scrollParent = offsetParent;
// Quirks returns <body>, but standards returns <html>.
if ( scrollParent.getName() == 'html' )
scrollParent = scrollParent.getDocument().getBody();
if ( scrollParent.getComputedStyle( 'direction' ) == 'rtl' ) {
// For IE8, there is not much logic on this, but it works.
if ( CKEDITOR.env.ie8Compat )
left -= element.getDocument().getDocumentElement().$.scrollLeft * 2;
else
left -= ( offsetParent.$.scrollWidth - offsetParent.$.clientWidth );
}
}
// Trigger the onHide event of the previously active panel to prevent
// incorrect styles from being applied (http://dev.ckeditor.com/ticket/6170)
var innerElement = element.getFirst(),
activePanel;
if ( ( activePanel = innerElement.getCustomData( 'activePanel' ) ) )
activePanel.onHide && activePanel.onHide.call( this, 1 );
innerElement.setCustomData( 'activePanel', this );
element.setStyles( {
top: top + 'px',
left: left + 'px'
} );
element.setOpacity( 1 );
callback && callback();
}, this );
panel.isLoaded ? panelLoad() : panel.onLoad = panelLoad;
CKEDITOR.tools.setTimeout( function() {
var scrollTop = CKEDITOR.env.webkit && CKEDITOR.document.getWindow().getScrollPosition().y;
// Focus the panel frame first, so blur gets fired.
this.focus();
// Focus the block now.
block.element.focus();
// http://dev.ckeditor.com/ticket/10623, http://dev.ckeditor.com/ticket/10951 - restore the viewport's scroll position after focusing list element.
if ( CKEDITOR.env.webkit )
CKEDITOR.document.getBody().$.scrollTop = scrollTop;
// We need this get fired manually because of unfired focus() function.
this.allowBlur( true );
// Ensure that the first item is focused (http://dev.ckeditor.com/ticket/16804).
if ( CKEDITOR.env.ie ) {
CKEDITOR.tools.setTimeout( function() {
block.markFirstDisplayed ? block.markFirstDisplayed() : block._.markFirstDisplayed();
}, 0 );
} else {
block.markFirstDisplayed ? block.markFirstDisplayed() : block._.markFirstDisplayed();
}
this._.editor.fire( 'panelShow', this );
}, 0, this );
}, CKEDITOR.env.air ? 200 : 0, this );
this.visible = 1;
if ( this.onShow )
this.onShow.call( this );
},
/**
* Repositions the panel with the same parameters that were used in the last {@link #showBlock} call.
*
* @since 4.5.4
*/
reposition: function() {
var blockParams = this._.showBlockParams;
if ( this.visible && this._.showBlockParams ) {
this.hide();
this.showBlock.apply( this, blockParams );
}
},
/**
* Restores the last focused element or simply focuses the panel window.
*/
focus: function() {
// Webkit requires to blur any previous focused page element, in
// order to properly fire the "focus" event.
if ( CKEDITOR.env.webkit ) {
var active = CKEDITOR.document.getActive();
active && !active.equals( this._.iframe ) && active.$.blur();
}
// Restore last focused element or simply focus panel window.
var focus = this._.lastFocused || this._.iframe.getFrameDocument().getWindow();
focus.focus();
},
/**
* @todo
*/
blur: function() {
var doc = this._.iframe.getFrameDocument(),
active = doc.getActive();
active && active.is( 'a' ) && ( this._.lastFocused = active );
},
/**
* Hides the panel.
*
* @todo
*/
hide: function( returnFocus ) {
if ( this.visible && ( !this.onHide || this.onHide.call( this ) !== true ) ) {
this.hideChild();
// Blur previously focused element. (http://dev.ckeditor.com/ticket/6671)
CKEDITOR.env.gecko && this._.iframe.getFrameDocument().$.activeElement.blur();
this.element.setStyle( 'display', 'none' );
this.visible = 0;
this.element.getFirst().removeCustomData( 'activePanel' );
// Return focus properly. (http://dev.ckeditor.com/ticket/6247)
var focusReturn = returnFocus && this._.returnFocus;
if ( focusReturn ) {
// Webkit requires focus moved out panel iframe first.
if ( CKEDITOR.env.webkit && focusReturn.type )
focusReturn.getWindow().$.focus();
focusReturn.focus();
}
delete this._.lastFocused;
this._.showBlockParams = null;
this._.editor.fire( 'panelHide', this );
}
},
/**
* @todo
*/
allowBlur: function( allow ) {
// Prevent editor from hiding the panel. (http://dev.ckeditor.com/ticket/3222)
var panel = this._.panel;
if ( allow !== undefined )
panel.allowBlur = allow;
return panel.allowBlur;
},
/**
* Shows the specified panel as a child of one block of this one.
*
* @param {CKEDITOR.ui.floatPanel} panel
* @param {String} blockName
* @param {CKEDITOR.dom.element} offsetParent Positioned parent.
* @param {Number} corner
*
* * For LTR (left to right) oriented editor:
* * `1` = top-left
* * `2` = top-right
* * `3` = bottom-right
* * `4` = bottom-left
* * For RTL (right to left):
* * `1` = top-right
* * `2` = top-left
* * `3` = bottom-left
* * `4` = bottom-right
*
* @param {Number} [offsetX=0]
* @param {Number} [offsetY=0]
* @todo
*/
showAsChild: function( panel, blockName, offsetParent, corner, offsetX, offsetY ) {
// Skip reshowing of child which is already visible.
if ( this._.activeChild == panel && panel._.panel._.offsetParentId == offsetParent.getId() )
return;
this.hideChild();
panel.onHide = CKEDITOR.tools.bind( function() {
// Use a timeout, so we give time for this menu to get
// potentially focused.
CKEDITOR.tools.setTimeout( function() {
if ( !this._.focused )
this.hide();
}, 0, this );
}, this );
this._.activeChild = panel;
this._.focused = false;
panel.showBlock( blockName, offsetParent, corner, offsetX, offsetY );
this.blur();
/* http://dev.ckeditor.com/ticket/3767 IE: Second level menu may not have borders */
if ( CKEDITOR.env.ie7Compat || CKEDITOR.env.ie6Compat ) {
setTimeout( function() {
panel.element.getChild( 0 ).$.style.cssText += '';
}, 100 );
}
},
/**
* @todo
*/
hideChild: function( restoreFocus ) {
var activeChild = this._.activeChild;
if ( activeChild ) {
delete activeChild.onHide;
delete this._.activeChild;
activeChild.hide();
// At this point focus should be moved back to parent panel.
restoreFocus && this.focus();
}
}
}
} );
CKEDITOR.on( 'instanceDestroyed', function() {
var isLastInstance = CKEDITOR.tools.isEmpty( CKEDITOR.instances );
for ( var i in panels ) {
var panel = panels[ i ];
// Safe to destroy it since there're no more instances.(http://dev.ckeditor.com/ticket/4241)
if ( isLastInstance )
panel.destroy();
// Panel might be used by other instances, just hide them.(http://dev.ckeditor.com/ticket/4552)
else
panel.element.hide();
}
// Remove the registration.
isLastInstance && ( panels = {} );
} );
} )();
|
function(page) {
var regex = /<img[^>]*src="(content\/formfield_files\/[^"]*)"/;
var match = regex.exec(page);
return match[1];
}
|
version https://git-lfs.github.com/spec/v1
oid sha256:3758b79412e0dd3334876feeab6044efed8d2dcf5aa48bcbff46cb708c93ace4
size 33861
|
import _curry3 from './internal/_curry3';
/**
* Makes a shallow clone of an object, setting or overriding the specified
* property with the given value. Note that this copies and flattens prototype
* properties onto the new object as well. All non-primitive properties are
* copied by reference.
*
* @func
* @memberOf R
* @since v0.8.0
* @category Object
* @sig String -> a -> {k: v} -> {k: v}
* @param {String} prop The property name to set
* @param {*} val The new value
* @param {Object} obj The object to clone
* @return {Object} A new object equivalent to the original except for the changed property.
* @see R.dissoc
* @example
*
* R.assoc('c', 3, {a: 1, b: 2}); //=> {a: 1, b: 2, c: 3}
*/
var assoc = _curry3(function assoc(prop, val, obj) {
var result = {};
for (var p in obj) {
result[p] = obj[p];
}
result[prop] = val;
return result;
});
export default assoc;
|
export { Card } from './Card.style'
export { CardActions } from './CardActions.style'
export { CardMedia } from './CardMedia.style'
export { CardMenu } from './CardMenu.style'
export { CardSubtitleText } from './CardSubtitleText.style'
export { CardSupportingText } from './CardSupportingText.style'
export { CardTitle } from './CardTitle.style'
export { CardTitleText } from './CardTitleText.style'
|
function makeData() {
"use strict";
var dataAustralia = [
{phoneType: "feature", demographic: "Male", value: 0.33},
{phoneType: "feature", demographic: "Female", value: 0.29},
{phoneType: "feature", demographic: "Ages 16-24", value: 0.19},
{phoneType: "feature", demographic: "Ages 25-34", value: 0.21},
{phoneType: "feature", demographic: "Ages 35-44", value: 0.28},
{phoneType: "feature", demographic: "Ages 45-64", value: 0.44},
{phoneType: "smart", demographic: "Male", value: 0.64},
{phoneType: "smart", demographic: "Female", value: 0.67},
{phoneType: "smart", demographic: "Ages 16-24", value: 0.77},
{phoneType: "smart", demographic: "Ages 25-34", value: 0.76},
{phoneType: "smart", demographic: "Ages 35-44", value: 0.69},
{phoneType: "smart", demographic: "Ages 45-64", value: 0.51}
];
var dataIndia = [
{phoneType: "feature", demographic: "Male", value: 0.76},
{phoneType: "feature", demographic: "Female", value: 0.85},
{phoneType: "feature", demographic: "Ages 16-24", value: 0.70},
{phoneType: "feature", demographic: "Ages 25-34", value: 0.80},
{phoneType: "feature", demographic: "Ages 35-44", value: 0.86},
{phoneType: "feature", demographic: "Ages 45-64", value: 0.87},
{phoneType: "smart", demographic: "Male", value: 0.13},
{phoneType: "smart", demographic: "Female", value: 0.07},
{phoneType: "smart", demographic: "Ages 16-24", value: 0.14},
{phoneType: "smart", demographic: "Ages 25-34", value: 0.12},
{phoneType: "smart", demographic: "Ages 35-44", value: 0.09},
{phoneType: "smart", demographic: "Ages 45-64", value: 0.06}
];
var dataRoK = [
{phoneType: "feature", demographic: "Male", value: 0.20},
{phoneType: "feature", demographic: "Female", value: 0.25},
{phoneType: "feature", demographic: "Ages 16-24", value: 0.08},
{phoneType: "feature", demographic: "Ages 25-34", value: 0.07},
{phoneType: "feature", demographic: "Ages 35-44", value: 0.21},
{phoneType: "feature", demographic: "Ages 45-64", value: 0.38},
{phoneType: "smart", demographic: "Male", value: 0.68},
{phoneType: "smart", demographic: "Female", value: 0.65},
{phoneType: "smart", demographic: "Ages 16-24", value: 0.86},
{phoneType: "smart", demographic: "Ages 25-34", value: 0.86},
{phoneType: "smart", demographic: "Ages 35-44", value: 0.66},
{phoneType: "smart", demographic: "Ages 45-64", value: 0.49}
];
return {
australia: dataAustralia,
india: dataIndia,
korea: dataRoK
};
}
function run(svg, data, Plottable) {
"use strict";
var AusColor = "#ff6969";
var IndColor = "#662a48";
var RoKColor = "#cc3300";
var colorScale = new Plottable.Scales.Color();
colorScale.domain(["Australia", "India", "South Korea"]);
colorScale.range([AusColor, IndColor, RoKColor]);
var legend = new Plottable.Components.Legend(colorScale)
.maxEntriesPerRow(3)
.xAlignment("left");
var AusDataset = new Plottable.Dataset(data.australia);
var IndDataset = new Plottable.Dataset(data.india);
var RoKDataset = new Plottable.Dataset(data.korea);
var xScale = new Plottable.Scales.Linear().domain([0, 1]);
var xScaleReverse = new Plottable.Scales.Linear().domain([1, 0]);
var yScale = new Plottable.Scales.Category();
var AusLabels = new Plottable.Axes.Category(yScale, "left")
.tickLength(0)
.endTickLength(0);
var IndLabels = new Plottable.Axes.Category(yScale, "left")
.tickLength(0)
.endTickLength(0);
var RoKLabels = new Plottable.Axes.Category(yScale, "left")
.tickLength(0)
.endTickLength(0);
var featureLabel = new Plottable.Components.Label("Feature Phones", 0);
var smartLabel = new Plottable.Components.Label("Smart Phones", 0);
var filterFeatureX = function(d){
if(d.phoneType === "feature"){
return d.value;
}
};
var filterFeatureY = function(d){
if(d.phoneType === "feature"){
return d.demographic;
}
};
var filterSmartX = function(d){
if(d.phoneType === "smart"){
return d.value;
}
};
var filterSmartY = function(d){
if(d.phoneType === "smart"){
return d.demographic;
}
};
var AusFeaturePlot = new Plottable.Plots.Bar("horizontal")
.addDataset(AusDataset)
.x(filterFeatureX, xScaleReverse)
.y(filterFeatureY, yScale)
.attr("fill", AusColor);
var AusSmartPlot = new Plottable.Plots.Bar("horizontal")
.addDataset(AusDataset)
.x(filterSmartX, xScale)
.y(filterSmartY, yScale)
.attr("fill", AusColor);
var IndFeaturePlot = new Plottable.Plots.Bar("horizontal")
.addDataset(IndDataset)
.x(filterFeatureX, xScaleReverse)
.y(filterFeatureY, yScale)
.attr("fill", IndColor);
var IndSmartPlot = new Plottable.Plots.Bar("horizontal")
.addDataset(IndDataset)
.x(filterSmartX, xScale)
.y(filterSmartY, yScale)
.attr("fill", IndColor);
var RoKFeaturePlot = new Plottable.Plots.Bar("horizontal")
.addDataset(RoKDataset)
.x(filterFeatureX, xScaleReverse)
.y(filterFeatureY, yScale)
.attr("fill", RoKColor);
var RoKSmartPlot = new Plottable.Plots.Bar("horizontal")
.addDataset(RoKDataset)
.x(filterSmartX, xScale)
.y(filterSmartY, yScale)
.attr("fill", RoKColor);
var table = new Plottable.Components.Table([[legend, null, null],
[featureLabel, null, smartLabel],
[AusFeaturePlot, AusLabels, AusSmartPlot],
[IndFeaturePlot, IndLabels, IndSmartPlot],
[RoKFeaturePlot, RoKLabels, RoKSmartPlot]]);
table.renderTo(svg);
}
|
var w = 960,
h = 500,
mouse = [null, null],
fill = d3.scale.linear().domain([0, 1e4]).range(["brown", "steelblue"]);
// Initialise boids.
var boids = d3.range(100).map(function() {
return boid()
.position([Math.random() * w, Math.random() * h])
.velocity([Math.random() * 2 - 1, Math.random() * 2 - 1])
.gravityCenter(mouse);
});
// Compute initial positions.
var vertices = boids.map(function(boid) {
return boid(boids);
});
d3.select(window).on("blur", nullGravity);
var svg = d3.select("#vis")
.append("svg")
.attr("width", w)
.attr("height", h)
.attr("class", "PiYG")
.on("mousemove", function() {
var m = d3.mouse(this);
mouse[0] = m[0];
mouse[1] = m[1];
})
.on("mouseout", nullGravity);
svg.selectAll("path")
.data(d3.geom.voronoi(vertices))
.enter().append("path")
.attr("class", function(d, i) { return i ? "q" + (i % 9) + "-9" : null; })
.attr("d", function(d) { return "M" + d.join("L") + "Z"; });
svg.selectAll("circle")
.data(vertices)
.enter().append("circle")
.attr("transform", function(d) { return "translate(" + d + ")"; })
.attr("r", 2);
d3.timer(function() {
// Update boid positions.
boids.forEach(function(boid, i) {
vertices[i] = boid(boids);
});
// Update circle positions.
svg.selectAll("circle")
.data(vertices)
.attr("transform", function(d) { return "translate(" + d + ")"; });
// Update voronoi diagram.
svg.selectAll("path")
.data(d3.geom.voronoi(vertices))
.attr("d", function(d) { return "M" + d.join("L") + "Z"; })
.style("fill", function(d) { return fill((d3.geom.polygon(d).area())); });
});
function nullGravity() {
mouse[0] = mouse[1] = null;
}
|
export default {
projections: {
DiagramLink: {
name: {
__caption__: 'name'
},
description: {
__caption__: 'description'
}
}
}
};
|
// @ts-nocheck
export const { Buffer } = require('buffer')
|
/** @jsx h */
import h from '../../../helpers/h'
export const input = (
<state>
<document>
<paragraph>
one
</paragraph>
</document>
</state>
)
export const output = {
kind: 'state',
document: {
kind: 'document',
data: {},
nodes: [
{
kind: 'block',
type: 'paragraph',
data: {},
isVoid: false,
nodes: [
{
kind: 'text',
leaves: [
{
kind: 'leaf',
text: 'one',
marks: [],
}
]
}
]
}
]
}
}
|
(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){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _src = require('../../src');
var _src2 = _interopRequireDefault(_src);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var handlerClasses = {
wrapper: 'react-resize-wrapper'
};
exports.default = function () {
return _react2.default.createElement(
'div',
null,
_react2.default.createElement(
_src2.default,
{
className: 'item',
width: '280',
height: '300',
minWidth: '240',
minHeight: '120',
maxWidth: '800',
maxHeight: '600',
handlerClasses: handlerClasses
},
_react2.default.createElement(
'div',
{ className: 'content' },
'Resize me!!',
_react2.default.createElement('br', null),
_react2.default.createElement(
'span',
{ style: { fontSize: '11px', fontFamily: 'Arial' } },
'max 800 * 600 / min 240 * 120'
)
)
)
);
};
},{"../../src":189,"react":188}],2:[function(require,module,exports){
'use strict';
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _reactDom = require('react-dom');
var _example = require('./example');
var _example2 = _interopRequireDefault(_example);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
(0, _reactDom.render)(_react2.default.createElement(_example2.default, null), document.querySelector('#content'));
},{"./example":1,"react":188,"react-dom":34}],3:[function(require,module,exports){
(function (process){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var _assign = require('object-assign');
var emptyObject = require('fbjs/lib/emptyObject');
var _invariant = require('fbjs/lib/invariant');
if (process.env.NODE_ENV !== 'production') {
var warning = require('fbjs/lib/warning');
}
var MIXINS_KEY = 'mixins';
// Helper function to allow the creation of anonymous functions which do not
// have .name set to the name of the variable being assigned to.
function identity(fn) {
return fn;
}
var ReactPropTypeLocationNames;
if (process.env.NODE_ENV !== 'production') {
ReactPropTypeLocationNames = {
prop: 'prop',
context: 'context',
childContext: 'child context'
};
} else {
ReactPropTypeLocationNames = {};
}
function factory(ReactComponent, isValidElement, ReactNoopUpdateQueue) {
/**
* Policies that describe methods in `ReactClassInterface`.
*/
var injectedMixins = [];
/**
* Composite components are higher-level components that compose other composite
* or host components.
*
* To create a new type of `ReactClass`, pass a specification of
* your new class to `React.createClass`. The only requirement of your class
* specification is that you implement a `render` method.
*
* var MyComponent = React.createClass({
* render: function() {
* return <div>Hello World</div>;
* }
* });
*
* The class specification supports a specific protocol of methods that have
* special meaning (e.g. `render`). See `ReactClassInterface` for
* more the comprehensive protocol. Any other properties and methods in the
* class specification will be available on the prototype.
*
* @interface ReactClassInterface
* @internal
*/
var ReactClassInterface = {
/**
* An array of Mixin objects to include when defining your component.
*
* @type {array}
* @optional
*/
mixins: 'DEFINE_MANY',
/**
* An object containing properties and methods that should be defined on
* the component's constructor instead of its prototype (static methods).
*
* @type {object}
* @optional
*/
statics: 'DEFINE_MANY',
/**
* Definition of prop types for this component.
*
* @type {object}
* @optional
*/
propTypes: 'DEFINE_MANY',
/**
* Definition of context types for this component.
*
* @type {object}
* @optional
*/
contextTypes: 'DEFINE_MANY',
/**
* Definition of context types this component sets for its children.
*
* @type {object}
* @optional
*/
childContextTypes: 'DEFINE_MANY',
// ==== Definition methods ====
/**
* Invoked when the component is mounted. Values in the mapping will be set on
* `this.props` if that prop is not specified (i.e. using an `in` check).
*
* This method is invoked before `getInitialState` and therefore cannot rely
* on `this.state` or use `this.setState`.
*
* @return {object}
* @optional
*/
getDefaultProps: 'DEFINE_MANY_MERGED',
/**
* Invoked once before the component is mounted. The return value will be used
* as the initial value of `this.state`.
*
* getInitialState: function() {
* return {
* isOn: false,
* fooBaz: new BazFoo()
* }
* }
*
* @return {object}
* @optional
*/
getInitialState: 'DEFINE_MANY_MERGED',
/**
* @return {object}
* @optional
*/
getChildContext: 'DEFINE_MANY_MERGED',
/**
* Uses props from `this.props` and state from `this.state` to render the
* structure of the component.
*
* No guarantees are made about when or how often this method is invoked, so
* it must not have side effects.
*
* render: function() {
* var name = this.props.name;
* return <div>Hello, {name}!</div>;
* }
*
* @return {ReactComponent}
* @required
*/
render: 'DEFINE_ONCE',
// ==== Delegate methods ====
/**
* Invoked when the component is initially created and about to be mounted.
* This may have side effects, but any external subscriptions or data created
* by this method must be cleaned up in `componentWillUnmount`.
*
* @optional
*/
componentWillMount: 'DEFINE_MANY',
/**
* Invoked when the component has been mounted and has a DOM representation.
* However, there is no guarantee that the DOM node is in the document.
*
* Use this as an opportunity to operate on the DOM when the component has
* been mounted (initialized and rendered) for the first time.
*
* @param {DOMElement} rootNode DOM element representing the component.
* @optional
*/
componentDidMount: 'DEFINE_MANY',
/**
* Invoked before the component receives new props.
*
* Use this as an opportunity to react to a prop transition by updating the
* state using `this.setState`. Current props are accessed via `this.props`.
*
* componentWillReceiveProps: function(nextProps, nextContext) {
* this.setState({
* likesIncreasing: nextProps.likeCount > this.props.likeCount
* });
* }
*
* NOTE: There is no equivalent `componentWillReceiveState`. An incoming prop
* transition may cause a state change, but the opposite is not true. If you
* need it, you are probably looking for `componentWillUpdate`.
*
* @param {object} nextProps
* @optional
*/
componentWillReceiveProps: 'DEFINE_MANY',
/**
* Invoked while deciding if the component should be updated as a result of
* receiving new props, state and/or context.
*
* Use this as an opportunity to `return false` when you're certain that the
* transition to the new props/state/context will not require a component
* update.
*
* shouldComponentUpdate: function(nextProps, nextState, nextContext) {
* return !equal(nextProps, this.props) ||
* !equal(nextState, this.state) ||
* !equal(nextContext, this.context);
* }
*
* @param {object} nextProps
* @param {?object} nextState
* @param {?object} nextContext
* @return {boolean} True if the component should update.
* @optional
*/
shouldComponentUpdate: 'DEFINE_ONCE',
/**
* Invoked when the component is about to update due to a transition from
* `this.props`, `this.state` and `this.context` to `nextProps`, `nextState`
* and `nextContext`.
*
* Use this as an opportunity to perform preparation before an update occurs.
*
* NOTE: You **cannot** use `this.setState()` in this method.
*
* @param {object} nextProps
* @param {?object} nextState
* @param {?object} nextContext
* @param {ReactReconcileTransaction} transaction
* @optional
*/
componentWillUpdate: 'DEFINE_MANY',
/**
* Invoked when the component's DOM representation has been updated.
*
* Use this as an opportunity to operate on the DOM when the component has
* been updated.
*
* @param {object} prevProps
* @param {?object} prevState
* @param {?object} prevContext
* @param {DOMElement} rootNode DOM element representing the component.
* @optional
*/
componentDidUpdate: 'DEFINE_MANY',
/**
* Invoked when the component is about to be removed from its parent and have
* its DOM representation destroyed.
*
* Use this as an opportunity to deallocate any external resources.
*
* NOTE: There is no `componentDidUnmount` since your component will have been
* destroyed by that point.
*
* @optional
*/
componentWillUnmount: 'DEFINE_MANY',
// ==== Advanced methods ====
/**
* Updates the component's currently mounted DOM representation.
*
* By default, this implements React's rendering and reconciliation algorithm.
* Sophisticated clients may wish to override this.
*
* @param {ReactReconcileTransaction} transaction
* @internal
* @overridable
*/
updateComponent: 'OVERRIDE_BASE'
};
/**
* Mapping from class specification keys to special processing functions.
*
* Although these are declared like instance properties in the specification
* when defining classes using `React.createClass`, they are actually static
* and are accessible on the constructor instead of the prototype. Despite
* being static, they must be defined outside of the "statics" key under
* which all other static methods are defined.
*/
var RESERVED_SPEC_KEYS = {
displayName: function(Constructor, displayName) {
Constructor.displayName = displayName;
},
mixins: function(Constructor, mixins) {
if (mixins) {
for (var i = 0; i < mixins.length; i++) {
mixSpecIntoComponent(Constructor, mixins[i]);
}
}
},
childContextTypes: function(Constructor, childContextTypes) {
if (process.env.NODE_ENV !== 'production') {
validateTypeDef(Constructor, childContextTypes, 'childContext');
}
Constructor.childContextTypes = _assign(
{},
Constructor.childContextTypes,
childContextTypes
);
},
contextTypes: function(Constructor, contextTypes) {
if (process.env.NODE_ENV !== 'production') {
validateTypeDef(Constructor, contextTypes, 'context');
}
Constructor.contextTypes = _assign(
{},
Constructor.contextTypes,
contextTypes
);
},
/**
* Special case getDefaultProps which should move into statics but requires
* automatic merging.
*/
getDefaultProps: function(Constructor, getDefaultProps) {
if (Constructor.getDefaultProps) {
Constructor.getDefaultProps = createMergedResultFunction(
Constructor.getDefaultProps,
getDefaultProps
);
} else {
Constructor.getDefaultProps = getDefaultProps;
}
},
propTypes: function(Constructor, propTypes) {
if (process.env.NODE_ENV !== 'production') {
validateTypeDef(Constructor, propTypes, 'prop');
}
Constructor.propTypes = _assign({}, Constructor.propTypes, propTypes);
},
statics: function(Constructor, statics) {
mixStaticSpecIntoComponent(Constructor, statics);
},
autobind: function() {}
};
function validateTypeDef(Constructor, typeDef, location) {
for (var propName in typeDef) {
if (typeDef.hasOwnProperty(propName)) {
// use a warning instead of an _invariant so components
// don't show up in prod but only in __DEV__
if (process.env.NODE_ENV !== 'production') {
warning(
typeof typeDef[propName] === 'function',
'%s: %s type `%s` is invalid; it must be a function, usually from ' +
'React.PropTypes.',
Constructor.displayName || 'ReactClass',
ReactPropTypeLocationNames[location],
propName
);
}
}
}
}
function validateMethodOverride(isAlreadyDefined, name) {
var specPolicy = ReactClassInterface.hasOwnProperty(name)
? ReactClassInterface[name]
: null;
// Disallow overriding of base class methods unless explicitly allowed.
if (ReactClassMixin.hasOwnProperty(name)) {
_invariant(
specPolicy === 'OVERRIDE_BASE',
'ReactClassInterface: You are attempting to override ' +
'`%s` from your class specification. Ensure that your method names ' +
'do not overlap with React methods.',
name
);
}
// Disallow defining methods more than once unless explicitly allowed.
if (isAlreadyDefined) {
_invariant(
specPolicy === 'DEFINE_MANY' || specPolicy === 'DEFINE_MANY_MERGED',
'ReactClassInterface: You are attempting to define ' +
'`%s` on your component more than once. This conflict may be due ' +
'to a mixin.',
name
);
}
}
/**
* Mixin helper which handles policy validation and reserved
* specification keys when building React classes.
*/
function mixSpecIntoComponent(Constructor, spec) {
if (!spec) {
if (process.env.NODE_ENV !== 'production') {
var typeofSpec = typeof spec;
var isMixinValid = typeofSpec === 'object' && spec !== null;
if (process.env.NODE_ENV !== 'production') {
warning(
isMixinValid,
"%s: You're attempting to include a mixin that is either null " +
'or not an object. Check the mixins included by the component, ' +
'as well as any mixins they include themselves. ' +
'Expected object but got %s.',
Constructor.displayName || 'ReactClass',
spec === null ? null : typeofSpec
);
}
}
return;
}
_invariant(
typeof spec !== 'function',
"ReactClass: You're attempting to " +
'use a component class or function as a mixin. Instead, just use a ' +
'regular object.'
);
_invariant(
!isValidElement(spec),
"ReactClass: You're attempting to " +
'use a component as a mixin. Instead, just use a regular object.'
);
var proto = Constructor.prototype;
var autoBindPairs = proto.__reactAutoBindPairs;
// By handling mixins before any other properties, we ensure the same
// chaining order is applied to methods with DEFINE_MANY policy, whether
// mixins are listed before or after these methods in the spec.
if (spec.hasOwnProperty(MIXINS_KEY)) {
RESERVED_SPEC_KEYS.mixins(Constructor, spec.mixins);
}
for (var name in spec) {
if (!spec.hasOwnProperty(name)) {
continue;
}
if (name === MIXINS_KEY) {
// We have already handled mixins in a special case above.
continue;
}
var property = spec[name];
var isAlreadyDefined = proto.hasOwnProperty(name);
validateMethodOverride(isAlreadyDefined, name);
if (RESERVED_SPEC_KEYS.hasOwnProperty(name)) {
RESERVED_SPEC_KEYS[name](Constructor, property);
} else {
// Setup methods on prototype:
// The following member methods should not be automatically bound:
// 1. Expected ReactClass methods (in the "interface").
// 2. Overridden methods (that were mixed in).
var isReactClassMethod = ReactClassInterface.hasOwnProperty(name);
var isFunction = typeof property === 'function';
var shouldAutoBind =
isFunction &&
!isReactClassMethod &&
!isAlreadyDefined &&
spec.autobind !== false;
if (shouldAutoBind) {
autoBindPairs.push(name, property);
proto[name] = property;
} else {
if (isAlreadyDefined) {
var specPolicy = ReactClassInterface[name];
// These cases should already be caught by validateMethodOverride.
_invariant(
isReactClassMethod &&
(specPolicy === 'DEFINE_MANY_MERGED' ||
specPolicy === 'DEFINE_MANY'),
'ReactClass: Unexpected spec policy %s for key %s ' +
'when mixing in component specs.',
specPolicy,
name
);
// For methods which are defined more than once, call the existing
// methods before calling the new property, merging if appropriate.
if (specPolicy === 'DEFINE_MANY_MERGED') {
proto[name] = createMergedResultFunction(proto[name], property);
} else if (specPolicy === 'DEFINE_MANY') {
proto[name] = createChainedFunction(proto[name], property);
}
} else {
proto[name] = property;
if (process.env.NODE_ENV !== 'production') {
// Add verbose displayName to the function, which helps when looking
// at profiling tools.
if (typeof property === 'function' && spec.displayName) {
proto[name].displayName = spec.displayName + '_' + name;
}
}
}
}
}
}
}
function mixStaticSpecIntoComponent(Constructor, statics) {
if (!statics) {
return;
}
for (var name in statics) {
var property = statics[name];
if (!statics.hasOwnProperty(name)) {
continue;
}
var isReserved = name in RESERVED_SPEC_KEYS;
_invariant(
!isReserved,
'ReactClass: You are attempting to define a reserved ' +
'property, `%s`, that shouldn\'t be on the "statics" key. Define it ' +
'as an instance property instead; it will still be accessible on the ' +
'constructor.',
name
);
var isInherited = name in Constructor;
_invariant(
!isInherited,
'ReactClass: You are attempting to define ' +
'`%s` on your component more than once. This conflict may be ' +
'due to a mixin.',
name
);
Constructor[name] = property;
}
}
/**
* Merge two objects, but throw if both contain the same key.
*
* @param {object} one The first object, which is mutated.
* @param {object} two The second object
* @return {object} one after it has been mutated to contain everything in two.
*/
function mergeIntoWithNoDuplicateKeys(one, two) {
_invariant(
one && two && typeof one === 'object' && typeof two === 'object',
'mergeIntoWithNoDuplicateKeys(): Cannot merge non-objects.'
);
for (var key in two) {
if (two.hasOwnProperty(key)) {
_invariant(
one[key] === undefined,
'mergeIntoWithNoDuplicateKeys(): ' +
'Tried to merge two objects with the same key: `%s`. This conflict ' +
'may be due to a mixin; in particular, this may be caused by two ' +
'getInitialState() or getDefaultProps() methods returning objects ' +
'with clashing keys.',
key
);
one[key] = two[key];
}
}
return one;
}
/**
* Creates a function that invokes two functions and merges their return values.
*
* @param {function} one Function to invoke first.
* @param {function} two Function to invoke second.
* @return {function} Function that invokes the two argument functions.
* @private
*/
function createMergedResultFunction(one, two) {
return function mergedResult() {
var a = one.apply(this, arguments);
var b = two.apply(this, arguments);
if (a == null) {
return b;
} else if (b == null) {
return a;
}
var c = {};
mergeIntoWithNoDuplicateKeys(c, a);
mergeIntoWithNoDuplicateKeys(c, b);
return c;
};
}
/**
* Creates a function that invokes two functions and ignores their return vales.
*
* @param {function} one Function to invoke first.
* @param {function} two Function to invoke second.
* @return {function} Function that invokes the two argument functions.
* @private
*/
function createChainedFunction(one, two) {
return function chainedFunction() {
one.apply(this, arguments);
two.apply(this, arguments);
};
}
/**
* Binds a method to the component.
*
* @param {object} component Component whose method is going to be bound.
* @param {function} method Method to be bound.
* @return {function} The bound method.
*/
function bindAutoBindMethod(component, method) {
var boundMethod = method.bind(component);
if (process.env.NODE_ENV !== 'production') {
boundMethod.__reactBoundContext = component;
boundMethod.__reactBoundMethod = method;
boundMethod.__reactBoundArguments = null;
var componentName = component.constructor.displayName;
var _bind = boundMethod.bind;
boundMethod.bind = function(newThis) {
for (
var _len = arguments.length,
args = Array(_len > 1 ? _len - 1 : 0),
_key = 1;
_key < _len;
_key++
) {
args[_key - 1] = arguments[_key];
}
// User is trying to bind() an autobound method; we effectively will
// ignore the value of "this" that the user is trying to use, so
// let's warn.
if (newThis !== component && newThis !== null) {
if (process.env.NODE_ENV !== 'production') {
warning(
false,
'bind(): React component methods may only be bound to the ' +
'component instance. See %s',
componentName
);
}
} else if (!args.length) {
if (process.env.NODE_ENV !== 'production') {
warning(
false,
'bind(): You are binding a component method to the component. ' +
'React does this for you automatically in a high-performance ' +
'way, so you can safely remove this call. See %s',
componentName
);
}
return boundMethod;
}
var reboundMethod = _bind.apply(boundMethod, arguments);
reboundMethod.__reactBoundContext = component;
reboundMethod.__reactBoundMethod = method;
reboundMethod.__reactBoundArguments = args;
return reboundMethod;
};
}
return boundMethod;
}
/**
* Binds all auto-bound methods in a component.
*
* @param {object} component Component whose method is going to be bound.
*/
function bindAutoBindMethods(component) {
var pairs = component.__reactAutoBindPairs;
for (var i = 0; i < pairs.length; i += 2) {
var autoBindKey = pairs[i];
var method = pairs[i + 1];
component[autoBindKey] = bindAutoBindMethod(component, method);
}
}
var IsMountedPreMixin = {
componentDidMount: function() {
this.__isMounted = true;
}
};
var IsMountedPostMixin = {
componentWillUnmount: function() {
this.__isMounted = false;
}
};
/**
* Add more to the ReactClass base class. These are all legacy features and
* therefore not already part of the modern ReactComponent.
*/
var ReactClassMixin = {
/**
* TODO: This will be deprecated because state should always keep a consistent
* type signature and the only use case for this, is to avoid that.
*/
replaceState: function(newState, callback) {
this.updater.enqueueReplaceState(this, newState, callback);
},
/**
* Checks whether or not this composite component is mounted.
* @return {boolean} True if mounted, false otherwise.
* @protected
* @final
*/
isMounted: function() {
if (process.env.NODE_ENV !== 'production') {
warning(
this.__didWarnIsMounted,
'%s: isMounted is deprecated. Instead, make sure to clean up ' +
'subscriptions and pending requests in componentWillUnmount to ' +
'prevent memory leaks.',
(this.constructor && this.constructor.displayName) ||
this.name ||
'Component'
);
this.__didWarnIsMounted = true;
}
return !!this.__isMounted;
}
};
var ReactClassComponent = function() {};
_assign(
ReactClassComponent.prototype,
ReactComponent.prototype,
ReactClassMixin
);
/**
* Creates a composite component class given a class specification.
* See https://facebook.github.io/react/docs/top-level-api.html#react.createclass
*
* @param {object} spec Class specification (which must define `render`).
* @return {function} Component constructor function.
* @public
*/
function createClass(spec) {
// To keep our warnings more understandable, we'll use a little hack here to
// ensure that Constructor.name !== 'Constructor'. This makes sure we don't
// unnecessarily identify a class without displayName as 'Constructor'.
var Constructor = identity(function(props, context, updater) {
// This constructor gets overridden by mocks. The argument is used
// by mocks to assert on what gets mounted.
if (process.env.NODE_ENV !== 'production') {
warning(
this instanceof Constructor,
'Something is calling a React component directly. Use a factory or ' +
'JSX instead. See: https://fb.me/react-legacyfactory'
);
}
// Wire up auto-binding
if (this.__reactAutoBindPairs.length) {
bindAutoBindMethods(this);
}
this.props = props;
this.context = context;
this.refs = emptyObject;
this.updater = updater || ReactNoopUpdateQueue;
this.state = null;
// ReactClasses doesn't have constructors. Instead, they use the
// getInitialState and componentWillMount methods for initialization.
var initialState = this.getInitialState ? this.getInitialState() : null;
if (process.env.NODE_ENV !== 'production') {
// We allow auto-mocks to proceed as if they're returning null.
if (
initialState === undefined &&
this.getInitialState._isMockFunction
) {
// This is probably bad practice. Consider warning here and
// deprecating this convenience.
initialState = null;
}
}
_invariant(
typeof initialState === 'object' && !Array.isArray(initialState),
'%s.getInitialState(): must return an object or null',
Constructor.displayName || 'ReactCompositeComponent'
);
this.state = initialState;
});
Constructor.prototype = new ReactClassComponent();
Constructor.prototype.constructor = Constructor;
Constructor.prototype.__reactAutoBindPairs = [];
injectedMixins.forEach(mixSpecIntoComponent.bind(null, Constructor));
mixSpecIntoComponent(Constructor, IsMountedPreMixin);
mixSpecIntoComponent(Constructor, spec);
mixSpecIntoComponent(Constructor, IsMountedPostMixin);
// Initialize the defaultProps property after all mixins have been merged.
if (Constructor.getDefaultProps) {
Constructor.defaultProps = Constructor.getDefaultProps();
}
if (process.env.NODE_ENV !== 'production') {
// This is a tag to indicate that the use of these method names is ok,
// since it's used with createClass. If it's not, then it's likely a
// mistake so we'll warn you to use the static property, property
// initializer or constructor respectively.
if (Constructor.getDefaultProps) {
Constructor.getDefaultProps.isReactClassApproved = {};
}
if (Constructor.prototype.getInitialState) {
Constructor.prototype.getInitialState.isReactClassApproved = {};
}
}
_invariant(
Constructor.prototype.render,
'createClass(...): Class specification must implement a `render` method.'
);
if (process.env.NODE_ENV !== 'production') {
warning(
!Constructor.prototype.componentShouldUpdate,
'%s has a method called ' +
'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' +
'The name is phrased as a question because the function is ' +
'expected to return a value.',
spec.displayName || 'A component'
);
warning(
!Constructor.prototype.componentWillRecieveProps,
'%s has a method called ' +
'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?',
spec.displayName || 'A component'
);
}
// Reduce time spent doing lookups by setting these on the prototype.
for (var methodName in ReactClassInterface) {
if (!Constructor.prototype[methodName]) {
Constructor.prototype[methodName] = null;
}
}
return Constructor;
}
return createClass;
}
module.exports = factory;
}).call(this,require('_process'))
},{"_process":29,"fbjs/lib/emptyObject":12,"fbjs/lib/invariant":19,"fbjs/lib/warning":26,"object-assign":28}],4:[function(require,module,exports){
(function (process){
'use strict';
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* 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.
*
* @typechecks
*/
var emptyFunction = require('./emptyFunction');
/**
* Upstream version of event listener. Does not take into account specific
* nature of platform.
*/
var EventListener = {
/**
* Listen to DOM events during the bubble phase.
*
* @param {DOMEventTarget} target DOM element to register listener on.
* @param {string} eventType Event type, e.g. 'click' or 'mouseover'.
* @param {function} callback Callback function.
* @return {object} Object with a `remove` method.
*/
listen: function listen(target, eventType, callback) {
if (target.addEventListener) {
target.addEventListener(eventType, callback, false);
return {
remove: function remove() {
target.removeEventListener(eventType, callback, false);
}
};
} else if (target.attachEvent) {
target.attachEvent('on' + eventType, callback);
return {
remove: function remove() {
target.detachEvent('on' + eventType, callback);
}
};
}
},
/**
* Listen to DOM events during the capture phase.
*
* @param {DOMEventTarget} target DOM element to register listener on.
* @param {string} eventType Event type, e.g. 'click' or 'mouseover'.
* @param {function} callback Callback function.
* @return {object} Object with a `remove` method.
*/
capture: function capture(target, eventType, callback) {
if (target.addEventListener) {
target.addEventListener(eventType, callback, true);
return {
remove: function remove() {
target.removeEventListener(eventType, callback, true);
}
};
} else {
if (process.env.NODE_ENV !== 'production') {
console.error('Attempted to listen to events during the capture phase on a ' + 'browser that does not support the capture phase. Your application ' + 'will not receive some events.');
}
return {
remove: emptyFunction
};
}
},
registerDefault: function registerDefault() {}
};
module.exports = EventListener;
}).call(this,require('_process'))
},{"./emptyFunction":11,"_process":29}],5:[function(require,module,exports){
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement);
/**
* Simple, lightweight module assisting with the detection and context of
* Worker. Helps avoid circular dependencies and allows code to reason about
* whether or not they are in a Worker, even if they never include the main
* `ReactWorker` dependency.
*/
var ExecutionEnvironment = {
canUseDOM: canUseDOM,
canUseWorkers: typeof Worker !== 'undefined',
canUseEventListeners: canUseDOM && !!(window.addEventListener || window.attachEvent),
canUseViewport: canUseDOM && !!window.screen,
isInWorker: !canUseDOM // For now, this is true - might change in the future.
};
module.exports = ExecutionEnvironment;
},{}],6:[function(require,module,exports){
"use strict";
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @typechecks
*/
var _hyphenPattern = /-(.)/g;
/**
* Camelcases a hyphenated string, for example:
*
* > camelize('background-color')
* < "backgroundColor"
*
* @param {string} string
* @return {string}
*/
function camelize(string) {
return string.replace(_hyphenPattern, function (_, character) {
return character.toUpperCase();
});
}
module.exports = camelize;
},{}],7:[function(require,module,exports){
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @typechecks
*/
'use strict';
var camelize = require('./camelize');
var msPattern = /^-ms-/;
/**
* Camelcases a hyphenated CSS property name, for example:
*
* > camelizeStyleName('background-color')
* < "backgroundColor"
* > camelizeStyleName('-moz-transition')
* < "MozTransition"
* > camelizeStyleName('-ms-transition')
* < "msTransition"
*
* As Andi Smith suggests
* (http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix
* is converted to lowercase `ms`.
*
* @param {string} string
* @return {string}
*/
function camelizeStyleName(string) {
return camelize(string.replace(msPattern, 'ms-'));
}
module.exports = camelizeStyleName;
},{"./camelize":6}],8:[function(require,module,exports){
'use strict';
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
var isTextNode = require('./isTextNode');
/*eslint-disable no-bitwise */
/**
* Checks if a given DOM node contains or is another DOM node.
*/
function containsNode(outerNode, innerNode) {
if (!outerNode || !innerNode) {
return false;
} else if (outerNode === innerNode) {
return true;
} else if (isTextNode(outerNode)) {
return false;
} else if (isTextNode(innerNode)) {
return containsNode(outerNode, innerNode.parentNode);
} else if ('contains' in outerNode) {
return outerNode.contains(innerNode);
} else if (outerNode.compareDocumentPosition) {
return !!(outerNode.compareDocumentPosition(innerNode) & 16);
} else {
return false;
}
}
module.exports = containsNode;
},{"./isTextNode":21}],9:[function(require,module,exports){
(function (process){
'use strict';
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @typechecks
*/
var invariant = require('./invariant');
/**
* Convert array-like objects to arrays.
*
* This API assumes the caller knows the contents of the data type. For less
* well defined inputs use createArrayFromMixed.
*
* @param {object|function|filelist} obj
* @return {array}
*/
function toArray(obj) {
var length = obj.length;
// Some browsers builtin objects can report typeof 'function' (e.g. NodeList
// in old versions of Safari).
!(!Array.isArray(obj) && (typeof obj === 'object' || typeof obj === 'function')) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'toArray: Array-like object expected') : invariant(false) : void 0;
!(typeof length === 'number') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'toArray: Object needs a length property') : invariant(false) : void 0;
!(length === 0 || length - 1 in obj) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'toArray: Object should have keys for indices') : invariant(false) : void 0;
!(typeof obj.callee !== 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'toArray: Object can\'t be `arguments`. Use rest params ' + '(function(...args) {}) or Array.from() instead.') : invariant(false) : void 0;
// Old IE doesn't give collections access to hasOwnProperty. Assume inputs
// without method will throw during the slice call and skip straight to the
// fallback.
if (obj.hasOwnProperty) {
try {
return Array.prototype.slice.call(obj);
} catch (e) {
// IE < 9 does not support Array#slice on collections objects
}
}
// Fall back to copying key by key. This assumes all keys have a value,
// so will not preserve sparsely populated inputs.
var ret = Array(length);
for (var ii = 0; ii < length; ii++) {
ret[ii] = obj[ii];
}
return ret;
}
/**
* Perform a heuristic test to determine if an object is "array-like".
*
* A monk asked Joshu, a Zen master, "Has a dog Buddha nature?"
* Joshu replied: "Mu."
*
* This function determines if its argument has "array nature": it returns
* true if the argument is an actual array, an `arguments' object, or an
* HTMLCollection (e.g. node.childNodes or node.getElementsByTagName()).
*
* It will return false for other array-like objects like Filelist.
*
* @param {*} obj
* @return {boolean}
*/
function hasArrayNature(obj) {
return (
// not null/false
!!obj && (
// arrays are objects, NodeLists are functions in Safari
typeof obj == 'object' || typeof obj == 'function') &&
// quacks like an array
'length' in obj &&
// not window
!('setInterval' in obj) &&
// no DOM node should be considered an array-like
// a 'select' element has 'length' and 'item' properties on IE8
typeof obj.nodeType != 'number' && (
// a real array
Array.isArray(obj) ||
// arguments
'callee' in obj ||
// HTMLCollection/NodeList
'item' in obj)
);
}
/**
* Ensure that the argument is an array by wrapping it in an array if it is not.
* Creates a copy of the argument if it is already an array.
*
* This is mostly useful idiomatically:
*
* var createArrayFromMixed = require('createArrayFromMixed');
*
* function takesOneOrMoreThings(things) {
* things = createArrayFromMixed(things);
* ...
* }
*
* This allows you to treat `things' as an array, but accept scalars in the API.
*
* If you need to convert an array-like object, like `arguments`, into an array
* use toArray instead.
*
* @param {*} obj
* @return {array}
*/
function createArrayFromMixed(obj) {
if (!hasArrayNature(obj)) {
return [obj];
} else if (Array.isArray(obj)) {
return obj.slice();
} else {
return toArray(obj);
}
}
module.exports = createArrayFromMixed;
}).call(this,require('_process'))
},{"./invariant":19,"_process":29}],10:[function(require,module,exports){
(function (process){
'use strict';
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @typechecks
*/
/*eslint-disable fb-www/unsafe-html*/
var ExecutionEnvironment = require('./ExecutionEnvironment');
var createArrayFromMixed = require('./createArrayFromMixed');
var getMarkupWrap = require('./getMarkupWrap');
var invariant = require('./invariant');
/**
* Dummy container used to render all markup.
*/
var dummyNode = ExecutionEnvironment.canUseDOM ? document.createElement('div') : null;
/**
* Pattern used by `getNodeName`.
*/
var nodeNamePattern = /^\s*<(\w+)/;
/**
* Extracts the `nodeName` of the first element in a string of markup.
*
* @param {string} markup String of markup.
* @return {?string} Node name of the supplied markup.
*/
function getNodeName(markup) {
var nodeNameMatch = markup.match(nodeNamePattern);
return nodeNameMatch && nodeNameMatch[1].toLowerCase();
}
/**
* Creates an array containing the nodes rendered from the supplied markup. The
* optionally supplied `handleScript` function will be invoked once for each
* <script> element that is rendered. If no `handleScript` function is supplied,
* an exception is thrown if any <script> elements are rendered.
*
* @param {string} markup A string of valid HTML markup.
* @param {?function} handleScript Invoked once for each rendered <script>.
* @return {array<DOMElement|DOMTextNode>} An array of rendered nodes.
*/
function createNodesFromMarkup(markup, handleScript) {
var node = dummyNode;
!!!dummyNode ? process.env.NODE_ENV !== 'production' ? invariant(false, 'createNodesFromMarkup dummy not initialized') : invariant(false) : void 0;
var nodeName = getNodeName(markup);
var wrap = nodeName && getMarkupWrap(nodeName);
if (wrap) {
node.innerHTML = wrap[1] + markup + wrap[2];
var wrapDepth = wrap[0];
while (wrapDepth--) {
node = node.lastChild;
}
} else {
node.innerHTML = markup;
}
var scripts = node.getElementsByTagName('script');
if (scripts.length) {
!handleScript ? process.env.NODE_ENV !== 'production' ? invariant(false, 'createNodesFromMarkup(...): Unexpected <script> element rendered.') : invariant(false) : void 0;
createArrayFromMixed(scripts).forEach(handleScript);
}
var nodes = Array.from(node.childNodes);
while (node.lastChild) {
node.removeChild(node.lastChild);
}
return nodes;
}
module.exports = createNodesFromMarkup;
}).call(this,require('_process'))
},{"./ExecutionEnvironment":5,"./createArrayFromMixed":9,"./getMarkupWrap":15,"./invariant":19,"_process":29}],11:[function(require,module,exports){
"use strict";
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
function makeEmptyFunction(arg) {
return function () {
return arg;
};
}
/**
* This function accepts and discards inputs; it has no side effects. This is
* primarily useful idiomatically for overridable function endpoints which
* always need to be callable, since JS lacks a null-call idiom ala Cocoa.
*/
var emptyFunction = function emptyFunction() {};
emptyFunction.thatReturns = makeEmptyFunction;
emptyFunction.thatReturnsFalse = makeEmptyFunction(false);
emptyFunction.thatReturnsTrue = makeEmptyFunction(true);
emptyFunction.thatReturnsNull = makeEmptyFunction(null);
emptyFunction.thatReturnsThis = function () {
return this;
};
emptyFunction.thatReturnsArgument = function (arg) {
return arg;
};
module.exports = emptyFunction;
},{}],12:[function(require,module,exports){
(function (process){
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var emptyObject = {};
if (process.env.NODE_ENV !== 'production') {
Object.freeze(emptyObject);
}
module.exports = emptyObject;
}).call(this,require('_process'))
},{"_process":29}],13:[function(require,module,exports){
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
/**
* @param {DOMElement} node input/textarea to focus
*/
function focusNode(node) {
// IE8 can throw "Can't move focus to the control because it is invisible,
// not enabled, or of a type that does not accept the focus." for all kinds of
// reasons that are too expensive and fragile to test.
try {
node.focus();
} catch (e) {}
}
module.exports = focusNode;
},{}],14:[function(require,module,exports){
'use strict';
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @typechecks
*/
/* eslint-disable fb-www/typeof-undefined */
/**
* Same as document.activeElement but wraps in a try-catch block. In IE it is
* not safe to call document.activeElement if there is nothing focused.
*
* The activeElement will be null only if the document or document body is not
* yet defined.
*
* @param {?DOMDocument} doc Defaults to current document.
* @return {?DOMElement}
*/
function getActiveElement(doc) /*?DOMElement*/{
doc = doc || (typeof document !== 'undefined' ? document : undefined);
if (typeof doc === 'undefined') {
return null;
}
try {
return doc.activeElement || doc.body;
} catch (e) {
return doc.body;
}
}
module.exports = getActiveElement;
},{}],15:[function(require,module,exports){
(function (process){
'use strict';
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
/*eslint-disable fb-www/unsafe-html */
var ExecutionEnvironment = require('./ExecutionEnvironment');
var invariant = require('./invariant');
/**
* Dummy container used to detect which wraps are necessary.
*/
var dummyNode = ExecutionEnvironment.canUseDOM ? document.createElement('div') : null;
/**
* Some browsers cannot use `innerHTML` to render certain elements standalone,
* so we wrap them, render the wrapped nodes, then extract the desired node.
*
* In IE8, certain elements cannot render alone, so wrap all elements ('*').
*/
var shouldWrap = {};
var selectWrap = [1, '<select multiple="true">', '</select>'];
var tableWrap = [1, '<table>', '</table>'];
var trWrap = [3, '<table><tbody><tr>', '</tr></tbody></table>'];
var svgWrap = [1, '<svg xmlns="http://www.w3.org/2000/svg">', '</svg>'];
var markupWrap = {
'*': [1, '?<div>', '</div>'],
'area': [1, '<map>', '</map>'],
'col': [2, '<table><tbody></tbody><colgroup>', '</colgroup></table>'],
'legend': [1, '<fieldset>', '</fieldset>'],
'param': [1, '<object>', '</object>'],
'tr': [2, '<table><tbody>', '</tbody></table>'],
'optgroup': selectWrap,
'option': selectWrap,
'caption': tableWrap,
'colgroup': tableWrap,
'tbody': tableWrap,
'tfoot': tableWrap,
'thead': tableWrap,
'td': trWrap,
'th': trWrap
};
// Initialize the SVG elements since we know they'll always need to be wrapped
// consistently. If they are created inside a <div> they will be initialized in
// the wrong namespace (and will not display).
var svgElements = ['circle', 'clipPath', 'defs', 'ellipse', 'g', 'image', 'line', 'linearGradient', 'mask', 'path', 'pattern', 'polygon', 'polyline', 'radialGradient', 'rect', 'stop', 'text', 'tspan'];
svgElements.forEach(function (nodeName) {
markupWrap[nodeName] = svgWrap;
shouldWrap[nodeName] = true;
});
/**
* Gets the markup wrap configuration for the supplied `nodeName`.
*
* NOTE: This lazily detects which wraps are necessary for the current browser.
*
* @param {string} nodeName Lowercase `nodeName`.
* @return {?array} Markup wrap configuration, if applicable.
*/
function getMarkupWrap(nodeName) {
!!!dummyNode ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Markup wrapping node not initialized') : invariant(false) : void 0;
if (!markupWrap.hasOwnProperty(nodeName)) {
nodeName = '*';
}
if (!shouldWrap.hasOwnProperty(nodeName)) {
if (nodeName === '*') {
dummyNode.innerHTML = '<link />';
} else {
dummyNode.innerHTML = '<' + nodeName + '></' + nodeName + '>';
}
shouldWrap[nodeName] = !dummyNode.firstChild;
}
return shouldWrap[nodeName] ? markupWrap[nodeName] : null;
}
module.exports = getMarkupWrap;
}).call(this,require('_process'))
},{"./ExecutionEnvironment":5,"./invariant":19,"_process":29}],16:[function(require,module,exports){
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @typechecks
*/
'use strict';
/**
* Gets the scroll position of the supplied element or window.
*
* The return values are unbounded, unlike `getScrollPosition`. This means they
* may be negative or exceed the element boundaries (which is possible using
* inertial scrolling).
*
* @param {DOMWindow|DOMElement} scrollable
* @return {object} Map with `x` and `y` keys.
*/
function getUnboundedScrollPosition(scrollable) {
if (scrollable.Window && scrollable instanceof scrollable.Window) {
return {
x: scrollable.pageXOffset || scrollable.document.documentElement.scrollLeft,
y: scrollable.pageYOffset || scrollable.document.documentElement.scrollTop
};
}
return {
x: scrollable.scrollLeft,
y: scrollable.scrollTop
};
}
module.exports = getUnboundedScrollPosition;
},{}],17:[function(require,module,exports){
'use strict';
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @typechecks
*/
var _uppercasePattern = /([A-Z])/g;
/**
* Hyphenates a camelcased string, for example:
*
* > hyphenate('backgroundColor')
* < "background-color"
*
* For CSS style names, use `hyphenateStyleName` instead which works properly
* with all vendor prefixes, including `ms`.
*
* @param {string} string
* @return {string}
*/
function hyphenate(string) {
return string.replace(_uppercasePattern, '-$1').toLowerCase();
}
module.exports = hyphenate;
},{}],18:[function(require,module,exports){
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @typechecks
*/
'use strict';
var hyphenate = require('./hyphenate');
var msPattern = /^ms-/;
/**
* Hyphenates a camelcased CSS property name, for example:
*
* > hyphenateStyleName('backgroundColor')
* < "background-color"
* > hyphenateStyleName('MozTransition')
* < "-moz-transition"
* > hyphenateStyleName('msTransition')
* < "-ms-transition"
*
* As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix
* is converted to `-ms-`.
*
* @param {string} string
* @return {string}
*/
function hyphenateStyleName(string) {
return hyphenate(string).replace(msPattern, '-ms-');
}
module.exports = hyphenateStyleName;
},{"./hyphenate":17}],19:[function(require,module,exports){
(function (process){
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
/**
* Use invariant() to assert state which your program assumes to be true.
*
* Provide sprintf-style format (only %s is supported) and arguments
* to provide information about what broke and what you were
* expecting.
*
* The invariant message will be stripped in production, but the invariant
* will remain to ensure logic does not differ in production.
*/
var validateFormat = function validateFormat(format) {};
if (process.env.NODE_ENV !== 'production') {
validateFormat = function validateFormat(format) {
if (format === undefined) {
throw new Error('invariant requires an error message argument');
}
};
}
function invariant(condition, format, a, b, c, d, e, f) {
validateFormat(format);
if (!condition) {
var error;
if (format === undefined) {
error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.');
} else {
var args = [a, b, c, d, e, f];
var argIndex = 0;
error = new Error(format.replace(/%s/g, function () {
return args[argIndex++];
}));
error.name = 'Invariant Violation';
}
error.framesToPop = 1; // we don't care about invariant's own frame
throw error;
}
}
module.exports = invariant;
}).call(this,require('_process'))
},{"_process":29}],20:[function(require,module,exports){
'use strict';
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @typechecks
*/
/**
* @param {*} object The object to check.
* @return {boolean} Whether or not the object is a DOM node.
*/
function isNode(object) {
var doc = object ? object.ownerDocument || object : document;
var defaultView = doc.defaultView || window;
return !!(object && (typeof defaultView.Node === 'function' ? object instanceof defaultView.Node : typeof object === 'object' && typeof object.nodeType === 'number' && typeof object.nodeName === 'string'));
}
module.exports = isNode;
},{}],21:[function(require,module,exports){
'use strict';
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @typechecks
*/
var isNode = require('./isNode');
/**
* @param {*} object The object to check.
* @return {boolean} Whether or not the object is a DOM text node.
*/
function isTextNode(object) {
return isNode(object) && object.nodeType == 3;
}
module.exports = isTextNode;
},{"./isNode":20}],22:[function(require,module,exports){
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
* @typechecks static-only
*/
'use strict';
/**
* Memoizes the return value of a function that accepts one string argument.
*/
function memoizeStringOnly(callback) {
var cache = {};
return function (string) {
if (!cache.hasOwnProperty(string)) {
cache[string] = callback.call(this, string);
}
return cache[string];
};
}
module.exports = memoizeStringOnly;
},{}],23:[function(require,module,exports){
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @typechecks
*/
'use strict';
var ExecutionEnvironment = require('./ExecutionEnvironment');
var performance;
if (ExecutionEnvironment.canUseDOM) {
performance = window.performance || window.msPerformance || window.webkitPerformance;
}
module.exports = performance || {};
},{"./ExecutionEnvironment":5}],24:[function(require,module,exports){
'use strict';
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @typechecks
*/
var performance = require('./performance');
var performanceNow;
/**
* Detect if we can use `window.performance.now()` and gracefully fallback to
* `Date.now()` if it doesn't exist. We need to support Firefox < 15 for now
* because of Facebook's testing infrastructure.
*/
if (performance.now) {
performanceNow = function performanceNow() {
return performance.now();
};
} else {
performanceNow = function performanceNow() {
return Date.now();
};
}
module.exports = performanceNow;
},{"./performance":23}],25:[function(require,module,exports){
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @typechecks
*
*/
/*eslint-disable no-self-compare */
'use strict';
var hasOwnProperty = Object.prototype.hasOwnProperty;
/**
* inlined Object.is polyfill to avoid requiring consumers ship their own
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
*/
function is(x, y) {
// SameValue algorithm
if (x === y) {
// Steps 1-5, 7-10
// Steps 6.b-6.e: +0 != -0
// Added the nonzero y check to make Flow happy, but it is redundant
return x !== 0 || y !== 0 || 1 / x === 1 / y;
} else {
// Step 6.a: NaN == NaN
return x !== x && y !== y;
}
}
/**
* Performs equality by iterating through keys on an object and returning false
* when any key has values which are not strictly equal between the arguments.
* Returns true when the values of all keys are strictly equal.
*/
function shallowEqual(objA, objB) {
if (is(objA, objB)) {
return true;
}
if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) {
return false;
}
var keysA = Object.keys(objA);
var keysB = Object.keys(objB);
if (keysA.length !== keysB.length) {
return false;
}
// Test for A's keys different from B.
for (var i = 0; i < keysA.length; i++) {
if (!hasOwnProperty.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) {
return false;
}
}
return true;
}
module.exports = shallowEqual;
},{}],26:[function(require,module,exports){
(function (process){
/**
* Copyright 2014-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var emptyFunction = require('./emptyFunction');
/**
* Similar to invariant but only logs a warning if the condition is not met.
* This can be used to log issues in development environments in critical
* paths. Removing the logging code for production environments will keep the
* same logic and follow the same code paths.
*/
var warning = emptyFunction;
if (process.env.NODE_ENV !== 'production') {
(function () {
var printWarning = function printWarning(format) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
var argIndex = 0;
var message = 'Warning: ' + format.replace(/%s/g, function () {
return args[argIndex++];
});
if (typeof console !== 'undefined') {
console.error(message);
}
try {
// --- Welcome to debugging React ---
// This error was thrown as a convenience so that you can use this stack
// to find the callsite that caused this warning to fire.
throw new Error(message);
} catch (x) {}
};
warning = function warning(condition, format) {
if (format === undefined) {
throw new Error('`warning(condition, format, ...args)` requires a warning ' + 'message argument');
}
if (format.indexOf('Failed Composite propType: ') === 0) {
return; // Ignore CompositeComponent proptype check.
}
if (!condition) {
for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
args[_key2 - 2] = arguments[_key2];
}
printWarning.apply(undefined, [format].concat(args));
}
};
})();
}
module.exports = warning;
}).call(this,require('_process'))
},{"./emptyFunction":11,"_process":29}],27:[function(require,module,exports){
(function (global){
/**
* Lodash (Custom Build) <https://lodash.com/>
* Build: `lodash modularize exports="npm" -o ./`
* Copyright JS Foundation and other contributors <https://js.foundation/>
* Released under MIT license <https://lodash.com/license>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
*/
/** Used as the size to enable large array optimizations. */
var LARGE_ARRAY_SIZE = 200;
/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1,
COMPARE_UNORDERED_FLAG = 2;
/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;
/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
arrayTag = '[object Array]',
asyncTag = '[object AsyncFunction]',
boolTag = '[object Boolean]',
dateTag = '[object Date]',
errorTag = '[object Error]',
funcTag = '[object Function]',
genTag = '[object GeneratorFunction]',
mapTag = '[object Map]',
numberTag = '[object Number]',
nullTag = '[object Null]',
objectTag = '[object Object]',
promiseTag = '[object Promise]',
proxyTag = '[object Proxy]',
regexpTag = '[object RegExp]',
setTag = '[object Set]',
stringTag = '[object String]',
symbolTag = '[object Symbol]',
undefinedTag = '[object Undefined]',
weakMapTag = '[object WeakMap]';
var arrayBufferTag = '[object ArrayBuffer]',
dataViewTag = '[object DataView]',
float32Tag = '[object Float32Array]',
float64Tag = '[object Float64Array]',
int8Tag = '[object Int8Array]',
int16Tag = '[object Int16Array]',
int32Tag = '[object Int32Array]',
uint8Tag = '[object Uint8Array]',
uint8ClampedTag = '[object Uint8ClampedArray]',
uint16Tag = '[object Uint16Array]',
uint32Tag = '[object Uint32Array]';
/**
* Used to match `RegExp`
* [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
*/
var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
/** Used to detect host constructors (Safari). */
var reIsHostCtor = /^\[object .+?Constructor\]$/;
/** Used to detect unsigned integer values. */
var reIsUint = /^(?:0|[1-9]\d*)$/;
/** Used to identify `toStringTag` values of typed arrays. */
var typedArrayTags = {};
typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
typedArrayTags[uint32Tag] = true;
typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =
typedArrayTags[errorTag] = typedArrayTags[funcTag] =
typedArrayTags[mapTag] = typedArrayTags[numberTag] =
typedArrayTags[objectTag] = typedArrayTags[regexpTag] =
typedArrayTags[setTag] = typedArrayTags[stringTag] =
typedArrayTags[weakMapTag] = false;
/** Detect free variable `global` from Node.js. */
var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
/** Detect free variable `self`. */
var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
/** Used as a reference to the global object. */
var root = freeGlobal || freeSelf || Function('return this')();
/** Detect free variable `exports`. */
var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
/** Detect free variable `module`. */
var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports = freeModule && freeModule.exports === freeExports;
/** Detect free variable `process` from Node.js. */
var freeProcess = moduleExports && freeGlobal.process;
/** Used to access faster Node.js helpers. */
var nodeUtil = (function() {
try {
return freeProcess && freeProcess.binding && freeProcess.binding('util');
} catch (e) {}
}());
/* Node.js helper references. */
var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;
/**
* A specialized version of `_.filter` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {Array} Returns the new filtered array.
*/
function arrayFilter(array, predicate) {
var index = -1,
length = array == null ? 0 : array.length,
resIndex = 0,
result = [];
while (++index < length) {
var value = array[index];
if (predicate(value, index, array)) {
result[resIndex++] = value;
}
}
return result;
}
/**
* Appends the elements of `values` to `array`.
*
* @private
* @param {Array} array The array to modify.
* @param {Array} values The values to append.
* @returns {Array} Returns `array`.
*/
function arrayPush(array, values) {
var index = -1,
length = values.length,
offset = array.length;
while (++index < length) {
array[offset + index] = values[index];
}
return array;
}
/**
* A specialized version of `_.some` for arrays without support for iteratee
* shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {boolean} Returns `true` if any element passes the predicate check,
* else `false`.
*/
function arraySome(array, predicate) {
var index = -1,
length = array == null ? 0 : array.length;
while (++index < length) {
if (predicate(array[index], index, array)) {
return true;
}
}
return false;
}
/**
* The base implementation of `_.times` without support for iteratee shorthands
* or max array length checks.
*
* @private
* @param {number} n The number of times to invoke `iteratee`.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the array of results.
*/
function baseTimes(n, iteratee) {
var index = -1,
result = Array(n);
while (++index < n) {
result[index] = iteratee(index);
}
return result;
}
/**
* The base implementation of `_.unary` without support for storing metadata.
*
* @private
* @param {Function} func The function to cap arguments for.
* @returns {Function} Returns the new capped function.
*/
function baseUnary(func) {
return function(value) {
return func(value);
};
}
/**
* Checks if a `cache` value for `key` exists.
*
* @private
* @param {Object} cache The cache to query.
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function cacheHas(cache, key) {
return cache.has(key);
}
/**
* Gets the value at `key` of `object`.
*
* @private
* @param {Object} [object] The object to query.
* @param {string} key The key of the property to get.
* @returns {*} Returns the property value.
*/
function getValue(object, key) {
return object == null ? undefined : object[key];
}
/**
* Converts `map` to its key-value pairs.
*
* @private
* @param {Object} map The map to convert.
* @returns {Array} Returns the key-value pairs.
*/
function mapToArray(map) {
var index = -1,
result = Array(map.size);
map.forEach(function(value, key) {
result[++index] = [key, value];
});
return result;
}
/**
* Creates a unary function that invokes `func` with its argument transformed.
*
* @private
* @param {Function} func The function to wrap.
* @param {Function} transform The argument transform.
* @returns {Function} Returns the new function.
*/
function overArg(func, transform) {
return function(arg) {
return func(transform(arg));
};
}
/**
* Converts `set` to an array of its values.
*
* @private
* @param {Object} set The set to convert.
* @returns {Array} Returns the values.
*/
function setToArray(set) {
var index = -1,
result = Array(set.size);
set.forEach(function(value) {
result[++index] = value;
});
return result;
}
/** Used for built-in method references. */
var arrayProto = Array.prototype,
funcProto = Function.prototype,
objectProto = Object.prototype;
/** Used to detect overreaching core-js shims. */
var coreJsData = root['__core-js_shared__'];
/** Used to resolve the decompiled source of functions. */
var funcToString = funcProto.toString;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/** Used to detect methods masquerading as native. */
var maskSrcKey = (function() {
var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
return uid ? ('Symbol(src)_1.' + uid) : '';
}());
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var nativeObjectToString = objectProto.toString;
/** Used to detect if a method is native. */
var reIsNative = RegExp('^' +
funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&')
.replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
);
/** Built-in value references. */
var Buffer = moduleExports ? root.Buffer : undefined,
Symbol = root.Symbol,
Uint8Array = root.Uint8Array,
propertyIsEnumerable = objectProto.propertyIsEnumerable,
splice = arrayProto.splice,
symToStringTag = Symbol ? Symbol.toStringTag : undefined;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeGetSymbols = Object.getOwnPropertySymbols,
nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined,
nativeKeys = overArg(Object.keys, Object);
/* Built-in method references that are verified to be native. */
var DataView = getNative(root, 'DataView'),
Map = getNative(root, 'Map'),
Promise = getNative(root, 'Promise'),
Set = getNative(root, 'Set'),
WeakMap = getNative(root, 'WeakMap'),
nativeCreate = getNative(Object, 'create');
/** Used to detect maps, sets, and weakmaps. */
var dataViewCtorString = toSource(DataView),
mapCtorString = toSource(Map),
promiseCtorString = toSource(Promise),
setCtorString = toSource(Set),
weakMapCtorString = toSource(WeakMap);
/** Used to convert symbols to primitives and strings. */
var symbolProto = Symbol ? Symbol.prototype : undefined,
symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;
/**
* Creates a hash object.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function Hash(entries) {
var index = -1,
length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
/**
* Removes all key-value entries from the hash.
*
* @private
* @name clear
* @memberOf Hash
*/
function hashClear() {
this.__data__ = nativeCreate ? nativeCreate(null) : {};
this.size = 0;
}
/**
* Removes `key` and its value from the hash.
*
* @private
* @name delete
* @memberOf Hash
* @param {Object} hash The hash to modify.
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function hashDelete(key) {
var result = this.has(key) && delete this.__data__[key];
this.size -= result ? 1 : 0;
return result;
}
/**
* Gets the hash value for `key`.
*
* @private
* @name get
* @memberOf Hash
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function hashGet(key) {
var data = this.__data__;
if (nativeCreate) {
var result = data[key];
return result === HASH_UNDEFINED ? undefined : result;
}
return hasOwnProperty.call(data, key) ? data[key] : undefined;
}
/**
* Checks if a hash value for `key` exists.
*
* @private
* @name has
* @memberOf Hash
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function hashHas(key) {
var data = this.__data__;
return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);
}
/**
* Sets the hash `key` to `value`.
*
* @private
* @name set
* @memberOf Hash
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the hash instance.
*/
function hashSet(key, value) {
var data = this.__data__;
this.size += this.has(key) ? 0 : 1;
data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;
return this;
}
// Add methods to `Hash`.
Hash.prototype.clear = hashClear;
Hash.prototype['delete'] = hashDelete;
Hash.prototype.get = hashGet;
Hash.prototype.has = hashHas;
Hash.prototype.set = hashSet;
/**
* Creates an list cache object.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function ListCache(entries) {
var index = -1,
length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
/**
* Removes all key-value entries from the list cache.
*
* @private
* @name clear
* @memberOf ListCache
*/
function listCacheClear() {
this.__data__ = [];
this.size = 0;
}
/**
* Removes `key` and its value from the list cache.
*
* @private
* @name delete
* @memberOf ListCache
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function listCacheDelete(key) {
var data = this.__data__,
index = assocIndexOf(data, key);
if (index < 0) {
return false;
}
var lastIndex = data.length - 1;
if (index == lastIndex) {
data.pop();
} else {
splice.call(data, index, 1);
}
--this.size;
return true;
}
/**
* Gets the list cache value for `key`.
*
* @private
* @name get
* @memberOf ListCache
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function listCacheGet(key) {
var data = this.__data__,
index = assocIndexOf(data, key);
return index < 0 ? undefined : data[index][1];
}
/**
* Checks if a list cache value for `key` exists.
*
* @private
* @name has
* @memberOf ListCache
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function listCacheHas(key) {
return assocIndexOf(this.__data__, key) > -1;
}
/**
* Sets the list cache `key` to `value`.
*
* @private
* @name set
* @memberOf ListCache
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the list cache instance.
*/
function listCacheSet(key, value) {
var data = this.__data__,
index = assocIndexOf(data, key);
if (index < 0) {
++this.size;
data.push([key, value]);
} else {
data[index][1] = value;
}
return this;
}
// Add methods to `ListCache`.
ListCache.prototype.clear = listCacheClear;
ListCache.prototype['delete'] = listCacheDelete;
ListCache.prototype.get = listCacheGet;
ListCache.prototype.has = listCacheHas;
ListCache.prototype.set = listCacheSet;
/**
* Creates a map cache object to store key-value pairs.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function MapCache(entries) {
var index = -1,
length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
/**
* Removes all key-value entries from the map.
*
* @private
* @name clear
* @memberOf MapCache
*/
function mapCacheClear() {
this.size = 0;
this.__data__ = {
'hash': new Hash,
'map': new (Map || ListCache),
'string': new Hash
};
}
/**
* Removes `key` and its value from the map.
*
* @private
* @name delete
* @memberOf MapCache
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function mapCacheDelete(key) {
var result = getMapData(this, key)['delete'](key);
this.size -= result ? 1 : 0;
return result;
}
/**
* Gets the map value for `key`.
*
* @private
* @name get
* @memberOf MapCache
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function mapCacheGet(key) {
return getMapData(this, key).get(key);
}
/**
* Checks if a map value for `key` exists.
*
* @private
* @name has
* @memberOf MapCache
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function mapCacheHas(key) {
return getMapData(this, key).has(key);
}
/**
* Sets the map `key` to `value`.
*
* @private
* @name set
* @memberOf MapCache
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the map cache instance.
*/
function mapCacheSet(key, value) {
var data = getMapData(this, key),
size = data.size;
data.set(key, value);
this.size += data.size == size ? 0 : 1;
return this;
}
// Add methods to `MapCache`.
MapCache.prototype.clear = mapCacheClear;
MapCache.prototype['delete'] = mapCacheDelete;
MapCache.prototype.get = mapCacheGet;
MapCache.prototype.has = mapCacheHas;
MapCache.prototype.set = mapCacheSet;
/**
*
* Creates an array cache object to store unique values.
*
* @private
* @constructor
* @param {Array} [values] The values to cache.
*/
function SetCache(values) {
var index = -1,
length = values == null ? 0 : values.length;
this.__data__ = new MapCache;
while (++index < length) {
this.add(values[index]);
}
}
/**
* Adds `value` to the array cache.
*
* @private
* @name add
* @memberOf SetCache
* @alias push
* @param {*} value The value to cache.
* @returns {Object} Returns the cache instance.
*/
function setCacheAdd(value) {
this.__data__.set(value, HASH_UNDEFINED);
return this;
}
/**
* Checks if `value` is in the array cache.
*
* @private
* @name has
* @memberOf SetCache
* @param {*} value The value to search for.
* @returns {number} Returns `true` if `value` is found, else `false`.
*/
function setCacheHas(value) {
return this.__data__.has(value);
}
// Add methods to `SetCache`.
SetCache.prototype.add = SetCache.prototype.push = setCacheAdd;
SetCache.prototype.has = setCacheHas;
/**
* Creates a stack cache object to store key-value pairs.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function Stack(entries) {
var data = this.__data__ = new ListCache(entries);
this.size = data.size;
}
/**
* Removes all key-value entries from the stack.
*
* @private
* @name clear
* @memberOf Stack
*/
function stackClear() {
this.__data__ = new ListCache;
this.size = 0;
}
/**
* Removes `key` and its value from the stack.
*
* @private
* @name delete
* @memberOf Stack
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function stackDelete(key) {
var data = this.__data__,
result = data['delete'](key);
this.size = data.size;
return result;
}
/**
* Gets the stack value for `key`.
*
* @private
* @name get
* @memberOf Stack
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function stackGet(key) {
return this.__data__.get(key);
}
/**
* Checks if a stack value for `key` exists.
*
* @private
* @name has
* @memberOf Stack
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function stackHas(key) {
return this.__data__.has(key);
}
/**
* Sets the stack `key` to `value`.
*
* @private
* @name set
* @memberOf Stack
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the stack cache instance.
*/
function stackSet(key, value) {
var data = this.__data__;
if (data instanceof ListCache) {
var pairs = data.__data__;
if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {
pairs.push([key, value]);
this.size = ++data.size;
return this;
}
data = this.__data__ = new MapCache(pairs);
}
data.set(key, value);
this.size = data.size;
return this;
}
// Add methods to `Stack`.
Stack.prototype.clear = stackClear;
Stack.prototype['delete'] = stackDelete;
Stack.prototype.get = stackGet;
Stack.prototype.has = stackHas;
Stack.prototype.set = stackSet;
/**
* Creates an array of the enumerable property names of the array-like `value`.
*
* @private
* @param {*} value The value to query.
* @param {boolean} inherited Specify returning inherited property names.
* @returns {Array} Returns the array of property names.
*/
function arrayLikeKeys(value, inherited) {
var isArr = isArray(value),
isArg = !isArr && isArguments(value),
isBuff = !isArr && !isArg && isBuffer(value),
isType = !isArr && !isArg && !isBuff && isTypedArray(value),
skipIndexes = isArr || isArg || isBuff || isType,
result = skipIndexes ? baseTimes(value.length, String) : [],
length = result.length;
for (var key in value) {
if ((inherited || hasOwnProperty.call(value, key)) &&
!(skipIndexes && (
// Safari 9 has enumerable `arguments.length` in strict mode.
key == 'length' ||
// Node.js 0.10 has enumerable non-index properties on buffers.
(isBuff && (key == 'offset' || key == 'parent')) ||
// PhantomJS 2 has enumerable non-index properties on typed arrays.
(isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||
// Skip index properties.
isIndex(key, length)
))) {
result.push(key);
}
}
return result;
}
/**
* Gets the index at which the `key` is found in `array` of key-value pairs.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} key The key to search for.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function assocIndexOf(array, key) {
var length = array.length;
while (length--) {
if (eq(array[length][0], key)) {
return length;
}
}
return -1;
}
/**
* The base implementation of `getAllKeys` and `getAllKeysIn` which uses
* `keysFunc` and `symbolsFunc` to get the enumerable property names and
* symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {Function} keysFunc The function to get the keys of `object`.
* @param {Function} symbolsFunc The function to get the symbols of `object`.
* @returns {Array} Returns the array of property names and symbols.
*/
function baseGetAllKeys(object, keysFunc, symbolsFunc) {
var result = keysFunc(object);
return isArray(object) ? result : arrayPush(result, symbolsFunc(object));
}
/**
* The base implementation of `getTag` without fallbacks for buggy environments.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the `toStringTag`.
*/
function baseGetTag(value) {
if (value == null) {
return value === undefined ? undefinedTag : nullTag;
}
return (symToStringTag && symToStringTag in Object(value))
? getRawTag(value)
: objectToString(value);
}
/**
* The base implementation of `_.isArguments`.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an `arguments` object,
*/
function baseIsArguments(value) {
return isObjectLike(value) && baseGetTag(value) == argsTag;
}
/**
* The base implementation of `_.isEqual` which supports partial comparisons
* and tracks traversed objects.
*
* @private
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @param {boolean} bitmask The bitmask flags.
* 1 - Unordered comparison
* 2 - Partial comparison
* @param {Function} [customizer] The function to customize comparisons.
* @param {Object} [stack] Tracks traversed `value` and `other` objects.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
*/
function baseIsEqual(value, other, bitmask, customizer, stack) {
if (value === other) {
return true;
}
if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) {
return value !== value && other !== other;
}
return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);
}
/**
* A specialized version of `baseIsEqual` for arrays and objects which performs
* deep comparisons and tracks traversed objects enabling objects with circular
* references to be compared.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} [stack] Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
var objIsArr = isArray(object),
othIsArr = isArray(other),
objTag = objIsArr ? arrayTag : getTag(object),
othTag = othIsArr ? arrayTag : getTag(other);
objTag = objTag == argsTag ? objectTag : objTag;
othTag = othTag == argsTag ? objectTag : othTag;
var objIsObj = objTag == objectTag,
othIsObj = othTag == objectTag,
isSameTag = objTag == othTag;
if (isSameTag && isBuffer(object)) {
if (!isBuffer(other)) {
return false;
}
objIsArr = true;
objIsObj = false;
}
if (isSameTag && !objIsObj) {
stack || (stack = new Stack);
return (objIsArr || isTypedArray(object))
? equalArrays(object, other, bitmask, customizer, equalFunc, stack)
: equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
}
if (!(bitmask & COMPARE_PARTIAL_FLAG)) {
var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');
if (objIsWrapped || othIsWrapped) {
var objUnwrapped = objIsWrapped ? object.value() : object,
othUnwrapped = othIsWrapped ? other.value() : other;
stack || (stack = new Stack);
return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
}
}
if (!isSameTag) {
return false;
}
stack || (stack = new Stack);
return equalObjects(object, other, bitmask, customizer, equalFunc, stack);
}
/**
* The base implementation of `_.isNative` without bad shim checks.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a native function,
* else `false`.
*/
function baseIsNative(value) {
if (!isObject(value) || isMasked(value)) {
return false;
}
var pattern = isFunction(value) ? reIsNative : reIsHostCtor;
return pattern.test(toSource(value));
}
/**
* The base implementation of `_.isTypedArray` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
*/
function baseIsTypedArray(value) {
return isObjectLike(value) &&
isLength(value.length) && !!typedArrayTags[baseGetTag(value)];
}
/**
* The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function baseKeys(object) {
if (!isPrototype(object)) {
return nativeKeys(object);
}
var result = [];
for (var key in Object(object)) {
if (hasOwnProperty.call(object, key) && key != 'constructor') {
result.push(key);
}
}
return result;
}
/**
* A specialized version of `baseIsEqualDeep` for arrays with support for
* partial deep comparisons.
*
* @private
* @param {Array} array The array to compare.
* @param {Array} other The other array to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} stack Tracks traversed `array` and `other` objects.
* @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
*/
function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {
var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
arrLength = array.length,
othLength = other.length;
if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
return false;
}
// Assume cyclic values are equal.
var stacked = stack.get(array);
if (stacked && stack.get(other)) {
return stacked == other;
}
var index = -1,
result = true,
seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined;
stack.set(array, other);
stack.set(other, array);
// Ignore non-index properties.
while (++index < arrLength) {
var arrValue = array[index],
othValue = other[index];
if (customizer) {
var compared = isPartial
? customizer(othValue, arrValue, index, other, array, stack)
: customizer(arrValue, othValue, index, array, other, stack);
}
if (compared !== undefined) {
if (compared) {
continue;
}
result = false;
break;
}
// Recursively compare arrays (susceptible to call stack limits).
if (seen) {
if (!arraySome(other, function(othValue, othIndex) {
if (!cacheHas(seen, othIndex) &&
(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
return seen.push(othIndex);
}
})) {
result = false;
break;
}
} else if (!(
arrValue === othValue ||
equalFunc(arrValue, othValue, bitmask, customizer, stack)
)) {
result = false;
break;
}
}
stack['delete'](array);
stack['delete'](other);
return result;
}
/**
* A specialized version of `baseIsEqualDeep` for comparing objects of
* the same `toStringTag`.
*
* **Note:** This function only supports comparing values with tags of
* `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {string} tag The `toStringTag` of the objects to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} stack Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
switch (tag) {
case dataViewTag:
if ((object.byteLength != other.byteLength) ||
(object.byteOffset != other.byteOffset)) {
return false;
}
object = object.buffer;
other = other.buffer;
case arrayBufferTag:
if ((object.byteLength != other.byteLength) ||
!equalFunc(new Uint8Array(object), new Uint8Array(other))) {
return false;
}
return true;
case boolTag:
case dateTag:
case numberTag:
// Coerce booleans to `1` or `0` and dates to milliseconds.
// Invalid dates are coerced to `NaN`.
return eq(+object, +other);
case errorTag:
return object.name == other.name && object.message == other.message;
case regexpTag:
case stringTag:
// Coerce regexes to strings and treat strings, primitives and objects,
// as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
// for more details.
return object == (other + '');
case mapTag:
var convert = mapToArray;
case setTag:
var isPartial = bitmask & COMPARE_PARTIAL_FLAG;
convert || (convert = setToArray);
if (object.size != other.size && !isPartial) {
return false;
}
// Assume cyclic values are equal.
var stacked = stack.get(object);
if (stacked) {
return stacked == other;
}
bitmask |= COMPARE_UNORDERED_FLAG;
// Recursively compare objects (susceptible to call stack limits).
stack.set(object, other);
var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
stack['delete'](object);
return result;
case symbolTag:
if (symbolValueOf) {
return symbolValueOf.call(object) == symbolValueOf.call(other);
}
}
return false;
}
/**
* A specialized version of `baseIsEqualDeep` for objects with support for
* partial deep comparisons.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} stack Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
objProps = getAllKeys(object),
objLength = objProps.length,
othProps = getAllKeys(other),
othLength = othProps.length;
if (objLength != othLength && !isPartial) {
return false;
}
var index = objLength;
while (index--) {
var key = objProps[index];
if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {
return false;
}
}
// Assume cyclic values are equal.
var stacked = stack.get(object);
if (stacked && stack.get(other)) {
return stacked == other;
}
var result = true;
stack.set(object, other);
stack.set(other, object);
var skipCtor = isPartial;
while (++index < objLength) {
key = objProps[index];
var objValue = object[key],
othValue = other[key];
if (customizer) {
var compared = isPartial
? customizer(othValue, objValue, key, other, object, stack)
: customizer(objValue, othValue, key, object, other, stack);
}
// Recursively compare objects (susceptible to call stack limits).
if (!(compared === undefined
? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))
: compared
)) {
result = false;
break;
}
skipCtor || (skipCtor = key == 'constructor');
}
if (result && !skipCtor) {
var objCtor = object.constructor,
othCtor = other.constructor;
// Non `Object` object instances with different constructors are not equal.
if (objCtor != othCtor &&
('constructor' in object && 'constructor' in other) &&
!(typeof objCtor == 'function' && objCtor instanceof objCtor &&
typeof othCtor == 'function' && othCtor instanceof othCtor)) {
result = false;
}
}
stack['delete'](object);
stack['delete'](other);
return result;
}
/**
* Creates an array of own enumerable property names and symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names and symbols.
*/
function getAllKeys(object) {
return baseGetAllKeys(object, keys, getSymbols);
}
/**
* Gets the data for `map`.
*
* @private
* @param {Object} map The map to query.
* @param {string} key The reference key.
* @returns {*} Returns the map data.
*/
function getMapData(map, key) {
var data = map.__data__;
return isKeyable(key)
? data[typeof key == 'string' ? 'string' : 'hash']
: data.map;
}
/**
* Gets the native function at `key` of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {string} key The key of the method to get.
* @returns {*} Returns the function if it's native, else `undefined`.
*/
function getNative(object, key) {
var value = getValue(object, key);
return baseIsNative(value) ? value : undefined;
}
/**
* A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the raw `toStringTag`.
*/
function getRawTag(value) {
var isOwn = hasOwnProperty.call(value, symToStringTag),
tag = value[symToStringTag];
try {
value[symToStringTag] = undefined;
var unmasked = true;
} catch (e) {}
var result = nativeObjectToString.call(value);
if (unmasked) {
if (isOwn) {
value[symToStringTag] = tag;
} else {
delete value[symToStringTag];
}
}
return result;
}
/**
* Creates an array of the own enumerable symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of symbols.
*/
var getSymbols = !nativeGetSymbols ? stubArray : function(object) {
if (object == null) {
return [];
}
object = Object(object);
return arrayFilter(nativeGetSymbols(object), function(symbol) {
return propertyIsEnumerable.call(object, symbol);
});
};
/**
* Gets the `toStringTag` of `value`.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the `toStringTag`.
*/
var getTag = baseGetTag;
// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.
if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||
(Map && getTag(new Map) != mapTag) ||
(Promise && getTag(Promise.resolve()) != promiseTag) ||
(Set && getTag(new Set) != setTag) ||
(WeakMap && getTag(new WeakMap) != weakMapTag)) {
getTag = function(value) {
var result = baseGetTag(value),
Ctor = result == objectTag ? value.constructor : undefined,
ctorString = Ctor ? toSource(Ctor) : '';
if (ctorString) {
switch (ctorString) {
case dataViewCtorString: return dataViewTag;
case mapCtorString: return mapTag;
case promiseCtorString: return promiseTag;
case setCtorString: return setTag;
case weakMapCtorString: return weakMapTag;
}
}
return result;
};
}
/**
* Checks if `value` is a valid array-like index.
*
* @private
* @param {*} value The value to check.
* @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
* @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
*/
function isIndex(value, length) {
length = length == null ? MAX_SAFE_INTEGER : length;
return !!length &&
(typeof value == 'number' || reIsUint.test(value)) &&
(value > -1 && value % 1 == 0 && value < length);
}
/**
* Checks if `value` is suitable for use as unique object key.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is suitable, else `false`.
*/
function isKeyable(value) {
var type = typeof value;
return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
? (value !== '__proto__')
: (value === null);
}
/**
* Checks if `func` has its source masked.
*
* @private
* @param {Function} func The function to check.
* @returns {boolean} Returns `true` if `func` is masked, else `false`.
*/
function isMasked(func) {
return !!maskSrcKey && (maskSrcKey in func);
}
/**
* Checks if `value` is likely a prototype object.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
*/
function isPrototype(value) {
var Ctor = value && value.constructor,
proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;
return value === proto;
}
/**
* Converts `value` to a string using `Object.prototype.toString`.
*
* @private
* @param {*} value The value to convert.
* @returns {string} Returns the converted string.
*/
function objectToString(value) {
return nativeObjectToString.call(value);
}
/**
* Converts `func` to its source code.
*
* @private
* @param {Function} func The function to convert.
* @returns {string} Returns the source code.
*/
function toSource(func) {
if (func != null) {
try {
return funcToString.call(func);
} catch (e) {}
try {
return (func + '');
} catch (e) {}
}
return '';
}
/**
* Performs a
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* comparison between two values to determine if they are equivalent.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* var object = { 'a': 1 };
* var other = { 'a': 1 };
*
* _.eq(object, object);
* // => true
*
* _.eq(object, other);
* // => false
*
* _.eq('a', 'a');
* // => true
*
* _.eq('a', Object('a'));
* // => false
*
* _.eq(NaN, NaN);
* // => true
*/
function eq(value, other) {
return value === other || (value !== value && other !== other);
}
/**
* Checks if `value` is likely an `arguments` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an `arguments` object,
* else `false`.
* @example
*
* _.isArguments(function() { return arguments; }());
* // => true
*
* _.isArguments([1, 2, 3]);
* // => false
*/
var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {
return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&
!propertyIsEnumerable.call(value, 'callee');
};
/**
* Checks if `value` is classified as an `Array` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array, else `false`.
* @example
*
* _.isArray([1, 2, 3]);
* // => true
*
* _.isArray(document.body.children);
* // => false
*
* _.isArray('abc');
* // => false
*
* _.isArray(_.noop);
* // => false
*/
var isArray = Array.isArray;
/**
* Checks if `value` is array-like. A value is considered array-like if it's
* not a function and has a `value.length` that's an integer greater than or
* equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is array-like, else `false`.
* @example
*
* _.isArrayLike([1, 2, 3]);
* // => true
*
* _.isArrayLike(document.body.children);
* // => true
*
* _.isArrayLike('abc');
* // => true
*
* _.isArrayLike(_.noop);
* // => false
*/
function isArrayLike(value) {
return value != null && isLength(value.length) && !isFunction(value);
}
/**
* Checks if `value` is a buffer.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
* @example
*
* _.isBuffer(new Buffer(2));
* // => true
*
* _.isBuffer(new Uint8Array(2));
* // => false
*/
var isBuffer = nativeIsBuffer || stubFalse;
/**
* Performs a deep comparison between two values to determine if they are
* equivalent.
*
* **Note:** This method supports comparing arrays, array buffers, booleans,
* date objects, error objects, maps, numbers, `Object` objects, regexes,
* sets, strings, symbols, and typed arrays. `Object` objects are compared
* by their own, not inherited, enumerable properties. Functions and DOM
* nodes are compared by strict equality, i.e. `===`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* var object = { 'a': 1 };
* var other = { 'a': 1 };
*
* _.isEqual(object, other);
* // => true
*
* object === other;
* // => false
*/
function isEqual(value, other) {
return baseIsEqual(value, other);
}
/**
* Checks if `value` is classified as a `Function` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a function, else `false`.
* @example
*
* _.isFunction(_);
* // => true
*
* _.isFunction(/abc/);
* // => false
*/
function isFunction(value) {
if (!isObject(value)) {
return false;
}
// The use of `Object#toString` avoids issues with the `typeof` operator
// in Safari 9 which returns 'object' for typed arrays and other constructors.
var tag = baseGetTag(value);
return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
}
/**
* Checks if `value` is a valid array-like length.
*
* **Note:** This method is loosely based on
* [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
* @example
*
* _.isLength(3);
* // => true
*
* _.isLength(Number.MIN_VALUE);
* // => false
*
* _.isLength(Infinity);
* // => false
*
* _.isLength('3');
* // => false
*/
function isLength(value) {
return typeof value == 'number' &&
value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}
/**
* Checks if `value` is the
* [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
* of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(_.noop);
* // => true
*
* _.isObject(null);
* // => false
*/
function isObject(value) {
var type = typeof value;
return value != null && (type == 'object' || type == 'function');
}
/**
* Checks if `value` is object-like. A value is object-like if it's not `null`
* and has a `typeof` result of "object".
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
* @example
*
* _.isObjectLike({});
* // => true
*
* _.isObjectLike([1, 2, 3]);
* // => true
*
* _.isObjectLike(_.noop);
* // => false
*
* _.isObjectLike(null);
* // => false
*/
function isObjectLike(value) {
return value != null && typeof value == 'object';
}
/**
* Checks if `value` is classified as a typed array.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
* @example
*
* _.isTypedArray(new Uint8Array);
* // => true
*
* _.isTypedArray([]);
* // => false
*/
var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;
/**
* Creates an array of the own enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects. See the
* [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
* for more details.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keys(new Foo);
* // => ['a', 'b'] (iteration order is not guaranteed)
*
* _.keys('hi');
* // => ['0', '1']
*/
function keys(object) {
return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
}
/**
* This method returns a new empty array.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {Array} Returns the new empty array.
* @example
*
* var arrays = _.times(2, _.stubArray);
*
* console.log(arrays);
* // => [[], []]
*
* console.log(arrays[0] === arrays[1]);
* // => false
*/
function stubArray() {
return [];
}
/**
* This method returns `false`.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {boolean} Returns `false`.
* @example
*
* _.times(2, _.stubFalse);
* // => [false, false]
*/
function stubFalse() {
return false;
}
module.exports = isEqual;
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],28:[function(require,module,exports){
/*
object-assign
(c) Sindre Sorhus
@license MIT
*/
'use strict';
/* eslint-disable no-unused-vars */
var getOwnPropertySymbols = Object.getOwnPropertySymbols;
var hasOwnProperty = Object.prototype.hasOwnProperty;
var propIsEnumerable = Object.prototype.propertyIsEnumerable;
function toObject(val) {
if (val === null || val === undefined) {
throw new TypeError('Object.assign cannot be called with null or undefined');
}
return Object(val);
}
function shouldUseNative() {
try {
if (!Object.assign) {
return false;
}
// Detect buggy property enumeration order in older V8 versions.
// https://bugs.chromium.org/p/v8/issues/detail?id=4118
var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
test1[5] = 'de';
if (Object.getOwnPropertyNames(test1)[0] === '5') {
return false;
}
// https://bugs.chromium.org/p/v8/issues/detail?id=3056
var test2 = {};
for (var i = 0; i < 10; i++) {
test2['_' + String.fromCharCode(i)] = i;
}
var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
return test2[n];
});
if (order2.join('') !== '0123456789') {
return false;
}
// https://bugs.chromium.org/p/v8/issues/detail?id=3056
var test3 = {};
'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
test3[letter] = letter;
});
if (Object.keys(Object.assign({}, test3)).join('') !==
'abcdefghijklmnopqrst') {
return false;
}
return true;
} catch (err) {
// We don't expect any of the above to throw, but better to be safe.
return false;
}
}
module.exports = shouldUseNative() ? Object.assign : function (target, source) {
var from;
var to = toObject(target);
var symbols;
for (var s = 1; s < arguments.length; s++) {
from = Object(arguments[s]);
for (var key in from) {
if (hasOwnProperty.call(from, key)) {
to[key] = from[key];
}
}
if (getOwnPropertySymbols) {
symbols = getOwnPropertySymbols(from);
for (var i = 0; i < symbols.length; i++) {
if (propIsEnumerable.call(from, symbols[i])) {
to[symbols[i]] = from[symbols[i]];
}
}
}
}
return to;
};
},{}],29:[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; };
},{}],30:[function(require,module,exports){
(function (process){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict';
if (process.env.NODE_ENV !== 'production') {
var invariant = require('fbjs/lib/invariant');
var warning = require('fbjs/lib/warning');
var ReactPropTypesSecret = require('./lib/ReactPropTypesSecret');
var loggedTypeFailures = {};
}
/**
* Assert that the values match with the type specs.
* Error messages are memorized and will only be shown once.
*
* @param {object} typeSpecs Map of name to a ReactPropType
* @param {object} values Runtime values that need to be type-checked
* @param {string} location e.g. "prop", "context", "child context"
* @param {string} componentName Name of the component for error messages.
* @param {?Function} getStack Returns the component stack.
* @private
*/
function checkPropTypes(typeSpecs, values, location, componentName, getStack) {
if (process.env.NODE_ENV !== 'production') {
for (var typeSpecName in typeSpecs) {
if (typeSpecs.hasOwnProperty(typeSpecName)) {
var error;
// Prop type validation may throw. In case they do, we don't want to
// fail the render phase where it didn't fail before. So we log it.
// After these have been cleaned up, we'll let them throw.
try {
// This is intentionally an invariant that gets caught. It's the same
// behavior as without this statement except with a better message.
invariant(typeof typeSpecs[typeSpecName] === 'function', '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'React.PropTypes.', componentName || 'React class', location, typeSpecName);
error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret);
} catch (ex) {
error = ex;
}
warning(!error || error instanceof Error, '%s: type specification of %s `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error);
if (error instanceof Error && !(error.message in loggedTypeFailures)) {
// Only monitor this failure once because there tends to be a lot of the
// same error.
loggedTypeFailures[error.message] = true;
var stack = getStack ? getStack() : '';
warning(false, 'Failed %s type: %s%s', location, error.message, stack != null ? stack : '');
}
}
}
}
}
module.exports = checkPropTypes;
}).call(this,require('_process'))
},{"./lib/ReactPropTypesSecret":33,"_process":29,"fbjs/lib/invariant":19,"fbjs/lib/warning":26}],31:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict';
// React 15.5 references this module, and assumes PropTypes are still callable in production.
// Therefore we re-export development-only version with all the PropTypes checks here.
// However if one is migrating to the `prop-types` npm library, they will go through the
// `index.js` entry point, and it will branch depending on the environment.
var factory = require('./factoryWithTypeCheckers');
module.exports = function(isValidElement) {
// It is still allowed in 15.5.
var throwOnDirectAccess = false;
return factory(isValidElement, throwOnDirectAccess);
};
},{"./factoryWithTypeCheckers":32}],32:[function(require,module,exports){
(function (process){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict';
var emptyFunction = require('fbjs/lib/emptyFunction');
var invariant = require('fbjs/lib/invariant');
var warning = require('fbjs/lib/warning');
var ReactPropTypesSecret = require('./lib/ReactPropTypesSecret');
var checkPropTypes = require('./checkPropTypes');
module.exports = function(isValidElement, throwOnDirectAccess) {
/* global Symbol */
var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec.
/**
* Returns the iterator method function contained on the iterable object.
*
* Be sure to invoke the function with the iterable as context:
*
* var iteratorFn = getIteratorFn(myIterable);
* if (iteratorFn) {
* var iterator = iteratorFn.call(myIterable);
* ...
* }
*
* @param {?object} maybeIterable
* @return {?function}
*/
function getIteratorFn(maybeIterable) {
var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]);
if (typeof iteratorFn === 'function') {
return iteratorFn;
}
}
/**
* Collection of methods that allow declaration and validation of props that are
* supplied to React components. Example usage:
*
* var Props = require('ReactPropTypes');
* var MyArticle = React.createClass({
* propTypes: {
* // An optional string prop named "description".
* description: Props.string,
*
* // A required enum prop named "category".
* category: Props.oneOf(['News','Photos']).isRequired,
*
* // A prop named "dialog" that requires an instance of Dialog.
* dialog: Props.instanceOf(Dialog).isRequired
* },
* render: function() { ... }
* });
*
* A more formal specification of how these methods are used:
*
* type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...)
* decl := ReactPropTypes.{type}(.isRequired)?
*
* Each and every declaration produces a function with the same signature. This
* allows the creation of custom validation functions. For example:
*
* var MyLink = React.createClass({
* propTypes: {
* // An optional string or URI prop named "href".
* href: function(props, propName, componentName) {
* var propValue = props[propName];
* if (propValue != null && typeof propValue !== 'string' &&
* !(propValue instanceof URI)) {
* return new Error(
* 'Expected a string or an URI for ' + propName + ' in ' +
* componentName
* );
* }
* }
* },
* render: function() {...}
* });
*
* @internal
*/
var ANONYMOUS = '<<anonymous>>';
// Important!
// Keep this list in sync with production version in `./factoryWithThrowingShims.js`.
var ReactPropTypes = {
array: createPrimitiveTypeChecker('array'),
bool: createPrimitiveTypeChecker('boolean'),
func: createPrimitiveTypeChecker('function'),
number: createPrimitiveTypeChecker('number'),
object: createPrimitiveTypeChecker('object'),
string: createPrimitiveTypeChecker('string'),
symbol: createPrimitiveTypeChecker('symbol'),
any: createAnyTypeChecker(),
arrayOf: createArrayOfTypeChecker,
element: createElementTypeChecker(),
instanceOf: createInstanceTypeChecker,
node: createNodeChecker(),
objectOf: createObjectOfTypeChecker,
oneOf: createEnumTypeChecker,
oneOfType: createUnionTypeChecker,
shape: createShapeTypeChecker
};
/**
* inlined Object.is polyfill to avoid requiring consumers ship their own
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
*/
/*eslint-disable no-self-compare*/
function is(x, y) {
// SameValue algorithm
if (x === y) {
// Steps 1-5, 7-10
// Steps 6.b-6.e: +0 != -0
return x !== 0 || 1 / x === 1 / y;
} else {
// Step 6.a: NaN == NaN
return x !== x && y !== y;
}
}
/*eslint-enable no-self-compare*/
/**
* We use an Error-like object for backward compatibility as people may call
* PropTypes directly and inspect their output. However, we don't use real
* Errors anymore. We don't inspect their stack anyway, and creating them
* is prohibitively expensive if they are created too often, such as what
* happens in oneOfType() for any type before the one that matched.
*/
function PropTypeError(message) {
this.message = message;
this.stack = '';
}
// Make `instanceof Error` still work for returned errors.
PropTypeError.prototype = Error.prototype;
function createChainableTypeChecker(validate) {
if (process.env.NODE_ENV !== 'production') {
var manualPropTypeCallCache = {};
var manualPropTypeWarningCount = 0;
}
function checkType(isRequired, props, propName, componentName, location, propFullName, secret) {
componentName = componentName || ANONYMOUS;
propFullName = propFullName || propName;
if (secret !== ReactPropTypesSecret) {
if (throwOnDirectAccess) {
// New behavior only for users of `prop-types` package
invariant(
false,
'Calling PropTypes validators directly is not supported by the `prop-types` package. ' +
'Use `PropTypes.checkPropTypes()` to call them. ' +
'Read more at http://fb.me/use-check-prop-types'
);
} else if (process.env.NODE_ENV !== 'production' && typeof console !== 'undefined') {
// Old behavior for people using React.PropTypes
var cacheKey = componentName + ':' + propName;
if (
!manualPropTypeCallCache[cacheKey] &&
// Avoid spamming the console because they are often not actionable except for lib authors
manualPropTypeWarningCount < 3
) {
warning(
false,
'You are manually calling a React.PropTypes validation ' +
'function for the `%s` prop on `%s`. This is deprecated ' +
'and will throw in the standalone `prop-types` package. ' +
'You may be seeing this warning due to a third-party PropTypes ' +
'library. See https://fb.me/react-warning-dont-call-proptypes ' + 'for details.',
propFullName,
componentName
);
manualPropTypeCallCache[cacheKey] = true;
manualPropTypeWarningCount++;
}
}
}
if (props[propName] == null) {
if (isRequired) {
if (props[propName] === null) {
return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required ' + ('in `' + componentName + '`, but its value is `null`.'));
}
return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required in ' + ('`' + componentName + '`, but its value is `undefined`.'));
}
return null;
} else {
return validate(props, propName, componentName, location, propFullName);
}
}
var chainedCheckType = checkType.bind(null, false);
chainedCheckType.isRequired = checkType.bind(null, true);
return chainedCheckType;
}
function createPrimitiveTypeChecker(expectedType) {
function validate(props, propName, componentName, location, propFullName, secret) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== expectedType) {
// `propValue` being instance of, say, date/regexp, pass the 'object'
// check, but we can offer a more precise error message here rather than
// 'of type `object`'.
var preciseType = getPreciseType(propValue);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createAnyTypeChecker() {
return createChainableTypeChecker(emptyFunction.thatReturnsNull);
}
function createArrayOfTypeChecker(typeChecker) {
function validate(props, propName, componentName, location, propFullName) {
if (typeof typeChecker !== 'function') {
return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside arrayOf.');
}
var propValue = props[propName];
if (!Array.isArray(propValue)) {
var propType = getPropType(propValue);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an array.'));
}
for (var i = 0; i < propValue.length; i++) {
var error = typeChecker(propValue, i, componentName, location, propFullName + '[' + i + ']', ReactPropTypesSecret);
if (error instanceof Error) {
return error;
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function createElementTypeChecker() {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
if (!isValidElement(propValue)) {
var propType = getPropType(propValue);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createInstanceTypeChecker(expectedClass) {
function validate(props, propName, componentName, location, propFullName) {
if (!(props[propName] instanceof expectedClass)) {
var expectedClassName = expectedClass.name || ANONYMOUS;
var actualClassName = getClassName(props[propName]);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + actualClassName + '` supplied to `' + componentName + '`, expected ') + ('instance of `' + expectedClassName + '`.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createEnumTypeChecker(expectedValues) {
if (!Array.isArray(expectedValues)) {
process.env.NODE_ENV !== 'production' ? warning(false, 'Invalid argument supplied to oneOf, expected an instance of array.') : void 0;
return emptyFunction.thatReturnsNull;
}
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
for (var i = 0; i < expectedValues.length; i++) {
if (is(propValue, expectedValues[i])) {
return null;
}
}
var valuesString = JSON.stringify(expectedValues);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of value `' + propValue + '` ' + ('supplied to `' + componentName + '`, expected one of ' + valuesString + '.'));
}
return createChainableTypeChecker(validate);
}
function createObjectOfTypeChecker(typeChecker) {
function validate(props, propName, componentName, location, propFullName) {
if (typeof typeChecker !== 'function') {
return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside objectOf.');
}
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== 'object') {
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an object.'));
}
for (var key in propValue) {
if (propValue.hasOwnProperty(key)) {
var error = typeChecker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret);
if (error instanceof Error) {
return error;
}
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function createUnionTypeChecker(arrayOfTypeCheckers) {
if (!Array.isArray(arrayOfTypeCheckers)) {
process.env.NODE_ENV !== 'production' ? warning(false, 'Invalid argument supplied to oneOfType, expected an instance of array.') : void 0;
return emptyFunction.thatReturnsNull;
}
for (var i = 0; i < arrayOfTypeCheckers.length; i++) {
var checker = arrayOfTypeCheckers[i];
if (typeof checker !== 'function') {
warning(
false,
'Invalid argument supplid to oneOfType. Expected an array of check functions, but ' +
'received %s at index %s.',
getPostfixForTypeWarning(checker),
i
);
return emptyFunction.thatReturnsNull;
}
}
function validate(props, propName, componentName, location, propFullName) {
for (var i = 0; i < arrayOfTypeCheckers.length; i++) {
var checker = arrayOfTypeCheckers[i];
if (checker(props, propName, componentName, location, propFullName, ReactPropTypesSecret) == null) {
return null;
}
}
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`.'));
}
return createChainableTypeChecker(validate);
}
function createNodeChecker() {
function validate(props, propName, componentName, location, propFullName) {
if (!isNode(props[propName])) {
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a ReactNode.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createShapeTypeChecker(shapeTypes) {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== 'object') {
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.'));
}
for (var key in shapeTypes) {
var checker = shapeTypes[key];
if (!checker) {
continue;
}
var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret);
if (error) {
return error;
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function isNode(propValue) {
switch (typeof propValue) {
case 'number':
case 'string':
case 'undefined':
return true;
case 'boolean':
return !propValue;
case 'object':
if (Array.isArray(propValue)) {
return propValue.every(isNode);
}
if (propValue === null || isValidElement(propValue)) {
return true;
}
var iteratorFn = getIteratorFn(propValue);
if (iteratorFn) {
var iterator = iteratorFn.call(propValue);
var step;
if (iteratorFn !== propValue.entries) {
while (!(step = iterator.next()).done) {
if (!isNode(step.value)) {
return false;
}
}
} else {
// Iterator will provide entry [k,v] tuples rather than values.
while (!(step = iterator.next()).done) {
var entry = step.value;
if (entry) {
if (!isNode(entry[1])) {
return false;
}
}
}
}
} else {
return false;
}
return true;
default:
return false;
}
}
function isSymbol(propType, propValue) {
// Native Symbol.
if (propType === 'symbol') {
return true;
}
// 19.4.3.5 Symbol.prototype[@@toStringTag] === 'Symbol'
if (propValue['@@toStringTag'] === 'Symbol') {
return true;
}
// Fallback for non-spec compliant Symbols which are polyfilled.
if (typeof Symbol === 'function' && propValue instanceof Symbol) {
return true;
}
return false;
}
// Equivalent of `typeof` but with special handling for array and regexp.
function getPropType(propValue) {
var propType = typeof propValue;
if (Array.isArray(propValue)) {
return 'array';
}
if (propValue instanceof RegExp) {
// Old webkits (at least until Android 4.0) return 'function' rather than
// 'object' for typeof a RegExp. We'll normalize this here so that /bla/
// passes PropTypes.object.
return 'object';
}
if (isSymbol(propType, propValue)) {
return 'symbol';
}
return propType;
}
// This handles more types than `getPropType`. Only used for error messages.
// See `createPrimitiveTypeChecker`.
function getPreciseType(propValue) {
if (typeof propValue === 'undefined' || propValue === null) {
return '' + propValue;
}
var propType = getPropType(propValue);
if (propType === 'object') {
if (propValue instanceof Date) {
return 'date';
} else if (propValue instanceof RegExp) {
return 'regexp';
}
}
return propType;
}
// Returns a string that is postfixed to a warning about an invalid type.
// For example, "undefined" or "of type array"
function getPostfixForTypeWarning(value) {
var type = getPreciseType(value);
switch (type) {
case 'array':
case 'object':
return 'an ' + type;
case 'boolean':
case 'date':
case 'regexp':
return 'a ' + type;
default:
return type;
}
}
// Returns class name of the object, if any.
function getClassName(propValue) {
if (!propValue.constructor || !propValue.constructor.name) {
return ANONYMOUS;
}
return propValue.constructor.name;
}
ReactPropTypes.checkPropTypes = checkPropTypes;
ReactPropTypes.PropTypes = ReactPropTypes;
return ReactPropTypes;
};
}).call(this,require('_process'))
},{"./checkPropTypes":30,"./lib/ReactPropTypesSecret":33,"_process":29,"fbjs/lib/emptyFunction":11,"fbjs/lib/invariant":19,"fbjs/lib/warning":26}],33:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict';
var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';
module.exports = ReactPropTypesSecret;
},{}],34:[function(require,module,exports){
'use strict';
module.exports = require('./lib/ReactDOM');
},{"./lib/ReactDOM":64}],35:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var ARIADOMPropertyConfig = {
Properties: {
// Global States and Properties
'aria-current': 0, // state
'aria-details': 0,
'aria-disabled': 0, // state
'aria-hidden': 0, // state
'aria-invalid': 0, // state
'aria-keyshortcuts': 0,
'aria-label': 0,
'aria-roledescription': 0,
// Widget Attributes
'aria-autocomplete': 0,
'aria-checked': 0,
'aria-expanded': 0,
'aria-haspopup': 0,
'aria-level': 0,
'aria-modal': 0,
'aria-multiline': 0,
'aria-multiselectable': 0,
'aria-orientation': 0,
'aria-placeholder': 0,
'aria-pressed': 0,
'aria-readonly': 0,
'aria-required': 0,
'aria-selected': 0,
'aria-sort': 0,
'aria-valuemax': 0,
'aria-valuemin': 0,
'aria-valuenow': 0,
'aria-valuetext': 0,
// Live Region Attributes
'aria-atomic': 0,
'aria-busy': 0,
'aria-live': 0,
'aria-relevant': 0,
// Drag-and-Drop Attributes
'aria-dropeffect': 0,
'aria-grabbed': 0,
// Relationship Attributes
'aria-activedescendant': 0,
'aria-colcount': 0,
'aria-colindex': 0,
'aria-colspan': 0,
'aria-controls': 0,
'aria-describedby': 0,
'aria-errormessage': 0,
'aria-flowto': 0,
'aria-labelledby': 0,
'aria-owns': 0,
'aria-posinset': 0,
'aria-rowcount': 0,
'aria-rowindex': 0,
'aria-rowspan': 0,
'aria-setsize': 0
},
DOMAttributeNames: {},
DOMPropertyNames: {}
};
module.exports = ARIADOMPropertyConfig;
},{}],36:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var ReactDOMComponentTree = require('./ReactDOMComponentTree');
var focusNode = require('fbjs/lib/focusNode');
var AutoFocusUtils = {
focusDOMComponent: function () {
focusNode(ReactDOMComponentTree.getNodeFromInstance(this));
}
};
module.exports = AutoFocusUtils;
},{"./ReactDOMComponentTree":67,"fbjs/lib/focusNode":13}],37:[function(require,module,exports){
/**
* Copyright 2013-present Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var EventPropagators = require('./EventPropagators');
var ExecutionEnvironment = require('fbjs/lib/ExecutionEnvironment');
var FallbackCompositionState = require('./FallbackCompositionState');
var SyntheticCompositionEvent = require('./SyntheticCompositionEvent');
var SyntheticInputEvent = require('./SyntheticInputEvent');
var END_KEYCODES = [9, 13, 27, 32]; // Tab, Return, Esc, Space
var START_KEYCODE = 229;
var canUseCompositionEvent = ExecutionEnvironment.canUseDOM && 'CompositionEvent' in window;
var documentMode = null;
if (ExecutionEnvironment.canUseDOM && 'documentMode' in document) {
documentMode = document.documentMode;
}
// Webkit offers a very useful `textInput` event that can be used to
// directly represent `beforeInput`. The IE `textinput` event is not as
// useful, so we don't use it.
var canUseTextInputEvent = ExecutionEnvironment.canUseDOM && 'TextEvent' in window && !documentMode && !isPresto();
// In IE9+, we have access to composition events, but the data supplied
// by the native compositionend event may be incorrect. Japanese ideographic
// spaces, for instance (\u3000) are not recorded correctly.
var useFallbackCompositionData = ExecutionEnvironment.canUseDOM && (!canUseCompositionEvent || documentMode && documentMode > 8 && documentMode <= 11);
/**
* Opera <= 12 includes TextEvent in window, but does not fire
* text input events. Rely on keypress instead.
*/
function isPresto() {
var opera = window.opera;
return typeof opera === 'object' && typeof opera.version === 'function' && parseInt(opera.version(), 10) <= 12;
}
var SPACEBAR_CODE = 32;
var SPACEBAR_CHAR = String.fromCharCode(SPACEBAR_CODE);
// Events and their corresponding property names.
var eventTypes = {
beforeInput: {
phasedRegistrationNames: {
bubbled: 'onBeforeInput',
captured: 'onBeforeInputCapture'
},
dependencies: ['topCompositionEnd', 'topKeyPress', 'topTextInput', 'topPaste']
},
compositionEnd: {
phasedRegistrationNames: {
bubbled: 'onCompositionEnd',
captured: 'onCompositionEndCapture'
},
dependencies: ['topBlur', 'topCompositionEnd', 'topKeyDown', 'topKeyPress', 'topKeyUp', 'topMouseDown']
},
compositionStart: {
phasedRegistrationNames: {
bubbled: 'onCompositionStart',
captured: 'onCompositionStartCapture'
},
dependencies: ['topBlur', 'topCompositionStart', 'topKeyDown', 'topKeyPress', 'topKeyUp', 'topMouseDown']
},
compositionUpdate: {
phasedRegistrationNames: {
bubbled: 'onCompositionUpdate',
captured: 'onCompositionUpdateCapture'
},
dependencies: ['topBlur', 'topCompositionUpdate', 'topKeyDown', 'topKeyPress', 'topKeyUp', 'topMouseDown']
}
};
// Track whether we've ever handled a keypress on the space key.
var hasSpaceKeypress = false;
/**
* Return whether a native keypress event is assumed to be a command.
* This is required because Firefox fires `keypress` events for key commands
* (cut, copy, select-all, etc.) even though no character is inserted.
*/
function isKeypressCommand(nativeEvent) {
return (nativeEvent.ctrlKey || nativeEvent.altKey || nativeEvent.metaKey) &&
// ctrlKey && altKey is equivalent to AltGr, and is not a command.
!(nativeEvent.ctrlKey && nativeEvent.altKey);
}
/**
* Translate native top level events into event types.
*
* @param {string} topLevelType
* @return {object}
*/
function getCompositionEventType(topLevelType) {
switch (topLevelType) {
case 'topCompositionStart':
return eventTypes.compositionStart;
case 'topCompositionEnd':
return eventTypes.compositionEnd;
case 'topCompositionUpdate':
return eventTypes.compositionUpdate;
}
}
/**
* Does our fallback best-guess model think this event signifies that
* composition has begun?
*
* @param {string} topLevelType
* @param {object} nativeEvent
* @return {boolean}
*/
function isFallbackCompositionStart(topLevelType, nativeEvent) {
return topLevelType === 'topKeyDown' && nativeEvent.keyCode === START_KEYCODE;
}
/**
* Does our fallback mode think that this event is the end of composition?
*
* @param {string} topLevelType
* @param {object} nativeEvent
* @return {boolean}
*/
function isFallbackCompositionEnd(topLevelType, nativeEvent) {
switch (topLevelType) {
case 'topKeyUp':
// Command keys insert or clear IME input.
return END_KEYCODES.indexOf(nativeEvent.keyCode) !== -1;
case 'topKeyDown':
// Expect IME keyCode on each keydown. If we get any other
// code we must have exited earlier.
return nativeEvent.keyCode !== START_KEYCODE;
case 'topKeyPress':
case 'topMouseDown':
case 'topBlur':
// Events are not possible without cancelling IME.
return true;
default:
return false;
}
}
/**
* Google Input Tools provides composition data via a CustomEvent,
* with the `data` property populated in the `detail` object. If this
* is available on the event object, use it. If not, this is a plain
* composition event and we have nothing special to extract.
*
* @param {object} nativeEvent
* @return {?string}
*/
function getDataFromCustomEvent(nativeEvent) {
var detail = nativeEvent.detail;
if (typeof detail === 'object' && 'data' in detail) {
return detail.data;
}
return null;
}
// Track the current IME composition fallback object, if any.
var currentComposition = null;
/**
* @return {?object} A SyntheticCompositionEvent.
*/
function extractCompositionEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget) {
var eventType;
var fallbackData;
if (canUseCompositionEvent) {
eventType = getCompositionEventType(topLevelType);
} else if (!currentComposition) {
if (isFallbackCompositionStart(topLevelType, nativeEvent)) {
eventType = eventTypes.compositionStart;
}
} else if (isFallbackCompositionEnd(topLevelType, nativeEvent)) {
eventType = eventTypes.compositionEnd;
}
if (!eventType) {
return null;
}
if (useFallbackCompositionData) {
// The current composition is stored statically and must not be
// overwritten while composition continues.
if (!currentComposition && eventType === eventTypes.compositionStart) {
currentComposition = FallbackCompositionState.getPooled(nativeEventTarget);
} else if (eventType === eventTypes.compositionEnd) {
if (currentComposition) {
fallbackData = currentComposition.getData();
}
}
}
var event = SyntheticCompositionEvent.getPooled(eventType, targetInst, nativeEvent, nativeEventTarget);
if (fallbackData) {
// Inject data generated from fallback path into the synthetic event.
// This matches the property of native CompositionEventInterface.
event.data = fallbackData;
} else {
var customData = getDataFromCustomEvent(nativeEvent);
if (customData !== null) {
event.data = customData;
}
}
EventPropagators.accumulateTwoPhaseDispatches(event);
return event;
}
/**
* @param {string} topLevelType Record from `EventConstants`.
* @param {object} nativeEvent Native browser event.
* @return {?string} The string corresponding to this `beforeInput` event.
*/
function getNativeBeforeInputChars(topLevelType, nativeEvent) {
switch (topLevelType) {
case 'topCompositionEnd':
return getDataFromCustomEvent(nativeEvent);
case 'topKeyPress':
/**
* If native `textInput` events are available, our goal is to make
* use of them. However, there is a special case: the spacebar key.
* In Webkit, preventing default on a spacebar `textInput` event
* cancels character insertion, but it *also* causes the browser
* to fall back to its default spacebar behavior of scrolling the
* page.
*
* Tracking at:
* https://code.google.com/p/chromium/issues/detail?id=355103
*
* To avoid this issue, use the keypress event as if no `textInput`
* event is available.
*/
var which = nativeEvent.which;
if (which !== SPACEBAR_CODE) {
return null;
}
hasSpaceKeypress = true;
return SPACEBAR_CHAR;
case 'topTextInput':
// Record the characters to be added to the DOM.
var chars = nativeEvent.data;
// If it's a spacebar character, assume that we have already handled
// it at the keypress level and bail immediately. Android Chrome
// doesn't give us keycodes, so we need to blacklist it.
if (chars === SPACEBAR_CHAR && hasSpaceKeypress) {
return null;
}
return chars;
default:
// For other native event types, do nothing.
return null;
}
}
/**
* For browsers that do not provide the `textInput` event, extract the
* appropriate string to use for SyntheticInputEvent.
*
* @param {string} topLevelType Record from `EventConstants`.
* @param {object} nativeEvent Native browser event.
* @return {?string} The fallback string for this `beforeInput` event.
*/
function getFallbackBeforeInputChars(topLevelType, nativeEvent) {
// If we are currently composing (IME) and using a fallback to do so,
// try to extract the composed characters from the fallback object.
// If composition event is available, we extract a string only at
// compositionevent, otherwise extract it at fallback events.
if (currentComposition) {
if (topLevelType === 'topCompositionEnd' || !canUseCompositionEvent && isFallbackCompositionEnd(topLevelType, nativeEvent)) {
var chars = currentComposition.getData();
FallbackCompositionState.release(currentComposition);
currentComposition = null;
return chars;
}
return null;
}
switch (topLevelType) {
case 'topPaste':
// If a paste event occurs after a keypress, throw out the input
// chars. Paste events should not lead to BeforeInput events.
return null;
case 'topKeyPress':
/**
* As of v27, Firefox may fire keypress events even when no character
* will be inserted. A few possibilities:
*
* - `which` is `0`. Arrow keys, Esc key, etc.
*
* - `which` is the pressed key code, but no char is available.
* Ex: 'AltGr + d` in Polish. There is no modified character for
* this key combination and no character is inserted into the
* document, but FF fires the keypress for char code `100` anyway.
* No `input` event will occur.
*
* - `which` is the pressed key code, but a command combination is
* being used. Ex: `Cmd+C`. No character is inserted, and no
* `input` event will occur.
*/
if (nativeEvent.which && !isKeypressCommand(nativeEvent)) {
return String.fromCharCode(nativeEvent.which);
}
return null;
case 'topCompositionEnd':
return useFallbackCompositionData ? null : nativeEvent.data;
default:
return null;
}
}
/**
* Extract a SyntheticInputEvent for `beforeInput`, based on either native
* `textInput` or fallback behavior.
*
* @return {?object} A SyntheticInputEvent.
*/
function extractBeforeInputEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget) {
var chars;
if (canUseTextInputEvent) {
chars = getNativeBeforeInputChars(topLevelType, nativeEvent);
} else {
chars = getFallbackBeforeInputChars(topLevelType, nativeEvent);
}
// If no characters are being inserted, no BeforeInput event should
// be fired.
if (!chars) {
return null;
}
var event = SyntheticInputEvent.getPooled(eventTypes.beforeInput, targetInst, nativeEvent, nativeEventTarget);
event.data = chars;
EventPropagators.accumulateTwoPhaseDispatches(event);
return event;
}
/**
* Create an `onBeforeInput` event to match
* http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105/#events-inputevents.
*
* This event plugin is based on the native `textInput` event
* available in Chrome, Safari, Opera, and IE. This event fires after
* `onKeyPress` and `onCompositionEnd`, but before `onInput`.
*
* `beforeInput` is spec'd but not implemented in any browsers, and
* the `input` event does not provide any useful information about what has
* actually been added, contrary to the spec. Thus, `textInput` is the best
* available event to identify the characters that have actually been inserted
* into the target node.
*
* This plugin is also responsible for emitting `composition` events, thus
* allowing us to share composition fallback code for both `beforeInput` and
* `composition` event types.
*/
var BeforeInputEventPlugin = {
eventTypes: eventTypes,
extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) {
return [extractCompositionEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget), extractBeforeInputEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget)];
}
};
module.exports = BeforeInputEventPlugin;
},{"./EventPropagators":53,"./FallbackCompositionState":54,"./SyntheticCompositionEvent":118,"./SyntheticInputEvent":122,"fbjs/lib/ExecutionEnvironment":5}],38:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
/**
* CSS properties which accept numbers but are not in units of "px".
*/
var isUnitlessNumber = {
animationIterationCount: true,
borderImageOutset: true,
borderImageSlice: true,
borderImageWidth: true,
boxFlex: true,
boxFlexGroup: true,
boxOrdinalGroup: true,
columnCount: true,
flex: true,
flexGrow: true,
flexPositive: true,
flexShrink: true,
flexNegative: true,
flexOrder: true,
gridRow: true,
gridColumn: true,
fontWeight: true,
lineClamp: true,
lineHeight: true,
opacity: true,
order: true,
orphans: true,
tabSize: true,
widows: true,
zIndex: true,
zoom: true,
// SVG-related properties
fillOpacity: true,
floodOpacity: true,
stopOpacity: true,
strokeDasharray: true,
strokeDashoffset: true,
strokeMiterlimit: true,
strokeOpacity: true,
strokeWidth: true
};
/**
* @param {string} prefix vendor-specific prefix, eg: Webkit
* @param {string} key style name, eg: transitionDuration
* @return {string} style name prefixed with `prefix`, properly camelCased, eg:
* WebkitTransitionDuration
*/
function prefixKey(prefix, key) {
return prefix + key.charAt(0).toUpperCase() + key.substring(1);
}
/**
* Support style names that may come passed in prefixed by adding permutations
* of vendor prefixes.
*/
var prefixes = ['Webkit', 'ms', 'Moz', 'O'];
// Using Object.keys here, or else the vanilla for-in loop makes IE8 go into an
// infinite loop, because it iterates over the newly added props too.
Object.keys(isUnitlessNumber).forEach(function (prop) {
prefixes.forEach(function (prefix) {
isUnitlessNumber[prefixKey(prefix, prop)] = isUnitlessNumber[prop];
});
});
/**
* Most style properties can be unset by doing .style[prop] = '' but IE8
* doesn't like doing that with shorthand properties so for the properties that
* IE8 breaks on, which are listed here, we instead unset each of the
* individual properties. See http://bugs.jquery.com/ticket/12385.
* The 4-value 'clock' properties like margin, padding, border-width seem to
* behave without any problems. Curiously, list-style works too without any
* special prodding.
*/
var shorthandPropertyExpansions = {
background: {
backgroundAttachment: true,
backgroundColor: true,
backgroundImage: true,
backgroundPositionX: true,
backgroundPositionY: true,
backgroundRepeat: true
},
backgroundPosition: {
backgroundPositionX: true,
backgroundPositionY: true
},
border: {
borderWidth: true,
borderStyle: true,
borderColor: true
},
borderBottom: {
borderBottomWidth: true,
borderBottomStyle: true,
borderBottomColor: true
},
borderLeft: {
borderLeftWidth: true,
borderLeftStyle: true,
borderLeftColor: true
},
borderRight: {
borderRightWidth: true,
borderRightStyle: true,
borderRightColor: true
},
borderTop: {
borderTopWidth: true,
borderTopStyle: true,
borderTopColor: true
},
font: {
fontStyle: true,
fontVariant: true,
fontWeight: true,
fontSize: true,
lineHeight: true,
fontFamily: true
},
outline: {
outlineWidth: true,
outlineStyle: true,
outlineColor: true
}
};
var CSSProperty = {
isUnitlessNumber: isUnitlessNumber,
shorthandPropertyExpansions: shorthandPropertyExpansions
};
module.exports = CSSProperty;
},{}],39:[function(require,module,exports){
(function (process){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var CSSProperty = require('./CSSProperty');
var ExecutionEnvironment = require('fbjs/lib/ExecutionEnvironment');
var ReactInstrumentation = require('./ReactInstrumentation');
var camelizeStyleName = require('fbjs/lib/camelizeStyleName');
var dangerousStyleValue = require('./dangerousStyleValue');
var hyphenateStyleName = require('fbjs/lib/hyphenateStyleName');
var memoizeStringOnly = require('fbjs/lib/memoizeStringOnly');
var warning = require('fbjs/lib/warning');
var processStyleName = memoizeStringOnly(function (styleName) {
return hyphenateStyleName(styleName);
});
var hasShorthandPropertyBug = false;
var styleFloatAccessor = 'cssFloat';
if (ExecutionEnvironment.canUseDOM) {
var tempStyle = document.createElement('div').style;
try {
// IE8 throws "Invalid argument." if resetting shorthand style properties.
tempStyle.font = '';
} catch (e) {
hasShorthandPropertyBug = true;
}
// IE8 only supports accessing cssFloat (standard) as styleFloat
if (document.documentElement.style.cssFloat === undefined) {
styleFloatAccessor = 'styleFloat';
}
}
if (process.env.NODE_ENV !== 'production') {
// 'msTransform' is correct, but the other prefixes should be capitalized
var badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/;
// style values shouldn't contain a semicolon
var badStyleValueWithSemicolonPattern = /;\s*$/;
var warnedStyleNames = {};
var warnedStyleValues = {};
var warnedForNaNValue = false;
var warnHyphenatedStyleName = function (name, owner) {
if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
return;
}
warnedStyleNames[name] = true;
process.env.NODE_ENV !== 'production' ? warning(false, 'Unsupported style property %s. Did you mean %s?%s', name, camelizeStyleName(name), checkRenderMessage(owner)) : void 0;
};
var warnBadVendoredStyleName = function (name, owner) {
if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
return;
}
warnedStyleNames[name] = true;
process.env.NODE_ENV !== 'production' ? warning(false, 'Unsupported vendor-prefixed style property %s. Did you mean %s?%s', name, name.charAt(0).toUpperCase() + name.slice(1), checkRenderMessage(owner)) : void 0;
};
var warnStyleValueWithSemicolon = function (name, value, owner) {
if (warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value]) {
return;
}
warnedStyleValues[value] = true;
process.env.NODE_ENV !== 'production' ? warning(false, 'Style property values shouldn\'t contain a semicolon.%s ' + 'Try "%s: %s" instead.', checkRenderMessage(owner), name, value.replace(badStyleValueWithSemicolonPattern, '')) : void 0;
};
var warnStyleValueIsNaN = function (name, value, owner) {
if (warnedForNaNValue) {
return;
}
warnedForNaNValue = true;
process.env.NODE_ENV !== 'production' ? warning(false, '`NaN` is an invalid value for the `%s` css style property.%s', name, checkRenderMessage(owner)) : void 0;
};
var checkRenderMessage = function (owner) {
if (owner) {
var name = owner.getName();
if (name) {
return ' Check the render method of `' + name + '`.';
}
}
return '';
};
/**
* @param {string} name
* @param {*} value
* @param {ReactDOMComponent} component
*/
var warnValidStyle = function (name, value, component) {
var owner;
if (component) {
owner = component._currentElement._owner;
}
if (name.indexOf('-') > -1) {
warnHyphenatedStyleName(name, owner);
} else if (badVendoredStyleNamePattern.test(name)) {
warnBadVendoredStyleName(name, owner);
} else if (badStyleValueWithSemicolonPattern.test(value)) {
warnStyleValueWithSemicolon(name, value, owner);
}
if (typeof value === 'number' && isNaN(value)) {
warnStyleValueIsNaN(name, value, owner);
}
};
}
/**
* Operations for dealing with CSS properties.
*/
var CSSPropertyOperations = {
/**
* Serializes a mapping of style properties for use as inline styles:
*
* > createMarkupForStyles({width: '200px', height: 0})
* "width:200px;height:0;"
*
* Undefined values are ignored so that declarative programming is easier.
* The result should be HTML-escaped before insertion into the DOM.
*
* @param {object} styles
* @param {ReactDOMComponent} component
* @return {?string}
*/
createMarkupForStyles: function (styles, component) {
var serialized = '';
for (var styleName in styles) {
if (!styles.hasOwnProperty(styleName)) {
continue;
}
var styleValue = styles[styleName];
if (process.env.NODE_ENV !== 'production') {
warnValidStyle(styleName, styleValue, component);
}
if (styleValue != null) {
serialized += processStyleName(styleName) + ':';
serialized += dangerousStyleValue(styleName, styleValue, component) + ';';
}
}
return serialized || null;
},
/**
* Sets the value for multiple styles on a node. If a value is specified as
* '' (empty string), the corresponding style property will be unset.
*
* @param {DOMElement} node
* @param {object} styles
* @param {ReactDOMComponent} component
*/
setValueForStyles: function (node, styles, component) {
if (process.env.NODE_ENV !== 'production') {
ReactInstrumentation.debugTool.onHostOperation({
instanceID: component._debugID,
type: 'update styles',
payload: styles
});
}
var style = node.style;
for (var styleName in styles) {
if (!styles.hasOwnProperty(styleName)) {
continue;
}
if (process.env.NODE_ENV !== 'production') {
warnValidStyle(styleName, styles[styleName], component);
}
var styleValue = dangerousStyleValue(styleName, styles[styleName], component);
if (styleName === 'float' || styleName === 'cssFloat') {
styleName = styleFloatAccessor;
}
if (styleValue) {
style[styleName] = styleValue;
} else {
var expansion = hasShorthandPropertyBug && CSSProperty.shorthandPropertyExpansions[styleName];
if (expansion) {
// Shorthand property that IE8 won't like unsetting, so unset each
// component to placate it
for (var individualStyleName in expansion) {
style[individualStyleName] = '';
}
} else {
style[styleName] = '';
}
}
}
}
};
module.exports = CSSPropertyOperations;
}).call(this,require('_process'))
},{"./CSSProperty":38,"./ReactInstrumentation":96,"./dangerousStyleValue":135,"_process":29,"fbjs/lib/ExecutionEnvironment":5,"fbjs/lib/camelizeStyleName":7,"fbjs/lib/hyphenateStyleName":18,"fbjs/lib/memoizeStringOnly":22,"fbjs/lib/warning":26}],40:[function(require,module,exports){
(function (process){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
'use strict';
var _prodInvariant = require('./reactProdInvariant');
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var PooledClass = require('./PooledClass');
var invariant = require('fbjs/lib/invariant');
/**
* A specialized pseudo-event module to help keep track of components waiting to
* be notified when their DOM representations are available for use.
*
* This implements `PooledClass`, so you should never need to instantiate this.
* Instead, use `CallbackQueue.getPooled()`.
*
* @class ReactMountReady
* @implements PooledClass
* @internal
*/
var CallbackQueue = function () {
function CallbackQueue(arg) {
_classCallCheck(this, CallbackQueue);
this._callbacks = null;
this._contexts = null;
this._arg = arg;
}
/**
* Enqueues a callback to be invoked when `notifyAll` is invoked.
*
* @param {function} callback Invoked when `notifyAll` is invoked.
* @param {?object} context Context to call `callback` with.
* @internal
*/
CallbackQueue.prototype.enqueue = function enqueue(callback, context) {
this._callbacks = this._callbacks || [];
this._callbacks.push(callback);
this._contexts = this._contexts || [];
this._contexts.push(context);
};
/**
* Invokes all enqueued callbacks and clears the queue. This is invoked after
* the DOM representation of a component has been created or updated.
*
* @internal
*/
CallbackQueue.prototype.notifyAll = function notifyAll() {
var callbacks = this._callbacks;
var contexts = this._contexts;
var arg = this._arg;
if (callbacks && contexts) {
!(callbacks.length === contexts.length) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Mismatched list of contexts in callback queue') : _prodInvariant('24') : void 0;
this._callbacks = null;
this._contexts = null;
for (var i = 0; i < callbacks.length; i++) {
callbacks[i].call(contexts[i], arg);
}
callbacks.length = 0;
contexts.length = 0;
}
};
CallbackQueue.prototype.checkpoint = function checkpoint() {
return this._callbacks ? this._callbacks.length : 0;
};
CallbackQueue.prototype.rollback = function rollback(len) {
if (this._callbacks && this._contexts) {
this._callbacks.length = len;
this._contexts.length = len;
}
};
/**
* Resets the internal queue.
*
* @internal
*/
CallbackQueue.prototype.reset = function reset() {
this._callbacks = null;
this._contexts = null;
};
/**
* `PooledClass` looks for this.
*/
CallbackQueue.prototype.destructor = function destructor() {
this.reset();
};
return CallbackQueue;
}();
module.exports = PooledClass.addPoolingTo(CallbackQueue);
}).call(this,require('_process'))
},{"./PooledClass":58,"./reactProdInvariant":153,"_process":29,"fbjs/lib/invariant":19}],41:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var EventPluginHub = require('./EventPluginHub');
var EventPropagators = require('./EventPropagators');
var ExecutionEnvironment = require('fbjs/lib/ExecutionEnvironment');
var ReactDOMComponentTree = require('./ReactDOMComponentTree');
var ReactUpdates = require('./ReactUpdates');
var SyntheticEvent = require('./SyntheticEvent');
var getEventTarget = require('./getEventTarget');
var isEventSupported = require('./isEventSupported');
var isTextInputElement = require('./isTextInputElement');
var eventTypes = {
change: {
phasedRegistrationNames: {
bubbled: 'onChange',
captured: 'onChangeCapture'
},
dependencies: ['topBlur', 'topChange', 'topClick', 'topFocus', 'topInput', 'topKeyDown', 'topKeyUp', 'topSelectionChange']
}
};
/**
* For IE shims
*/
var activeElement = null;
var activeElementInst = null;
var activeElementValue = null;
var activeElementValueProp = null;
/**
* SECTION: handle `change` event
*/
function shouldUseChangeEvent(elem) {
var nodeName = elem.nodeName && elem.nodeName.toLowerCase();
return nodeName === 'select' || nodeName === 'input' && elem.type === 'file';
}
var doesChangeEventBubble = false;
if (ExecutionEnvironment.canUseDOM) {
// See `handleChange` comment below
doesChangeEventBubble = isEventSupported('change') && (!document.documentMode || document.documentMode > 8);
}
function manualDispatchChangeEvent(nativeEvent) {
var event = SyntheticEvent.getPooled(eventTypes.change, activeElementInst, nativeEvent, getEventTarget(nativeEvent));
EventPropagators.accumulateTwoPhaseDispatches(event);
// If change and propertychange bubbled, we'd just bind to it like all the
// other events and have it go through ReactBrowserEventEmitter. Since it
// doesn't, we manually listen for the events and so we have to enqueue and
// process the abstract event manually.
//
// Batching is necessary here in order to ensure that all event handlers run
// before the next rerender (including event handlers attached to ancestor
// elements instead of directly on the input). Without this, controlled
// components don't work properly in conjunction with event bubbling because
// the component is rerendered and the value reverted before all the event
// handlers can run. See https://github.com/facebook/react/issues/708.
ReactUpdates.batchedUpdates(runEventInBatch, event);
}
function runEventInBatch(event) {
EventPluginHub.enqueueEvents(event);
EventPluginHub.processEventQueue(false);
}
function startWatchingForChangeEventIE8(target, targetInst) {
activeElement = target;
activeElementInst = targetInst;
activeElement.attachEvent('onchange', manualDispatchChangeEvent);
}
function stopWatchingForChangeEventIE8() {
if (!activeElement) {
return;
}
activeElement.detachEvent('onchange', manualDispatchChangeEvent);
activeElement = null;
activeElementInst = null;
}
function getTargetInstForChangeEvent(topLevelType, targetInst) {
if (topLevelType === 'topChange') {
return targetInst;
}
}
function handleEventsForChangeEventIE8(topLevelType, target, targetInst) {
if (topLevelType === 'topFocus') {
// stopWatching() should be a noop here but we call it just in case we
// missed a blur event somehow.
stopWatchingForChangeEventIE8();
startWatchingForChangeEventIE8(target, targetInst);
} else if (topLevelType === 'topBlur') {
stopWatchingForChangeEventIE8();
}
}
/**
* SECTION: handle `input` event
*/
var isInputEventSupported = false;
if (ExecutionEnvironment.canUseDOM) {
// IE9 claims to support the input event but fails to trigger it when
// deleting text, so we ignore its input events.
// IE10+ fire input events to often, such when a placeholder
// changes or when an input with a placeholder is focused.
isInputEventSupported = isEventSupported('input') && (!document.documentMode || document.documentMode > 11);
}
/**
* (For IE <=11) Replacement getter/setter for the `value` property that gets
* set on the active element.
*/
var newValueProp = {
get: function () {
return activeElementValueProp.get.call(this);
},
set: function (val) {
// Cast to a string so we can do equality checks.
activeElementValue = '' + val;
activeElementValueProp.set.call(this, val);
}
};
/**
* (For IE <=11) Starts tracking propertychange events on the passed-in element
* and override the value property so that we can distinguish user events from
* value changes in JS.
*/
function startWatchingForValueChange(target, targetInst) {
activeElement = target;
activeElementInst = targetInst;
activeElementValue = target.value;
activeElementValueProp = Object.getOwnPropertyDescriptor(target.constructor.prototype, 'value');
// Not guarded in a canDefineProperty check: IE8 supports defineProperty only
// on DOM elements
Object.defineProperty(activeElement, 'value', newValueProp);
if (activeElement.attachEvent) {
activeElement.attachEvent('onpropertychange', handlePropertyChange);
} else {
activeElement.addEventListener('propertychange', handlePropertyChange, false);
}
}
/**
* (For IE <=11) Removes the event listeners from the currently-tracked element,
* if any exists.
*/
function stopWatchingForValueChange() {
if (!activeElement) {
return;
}
// delete restores the original property definition
delete activeElement.value;
if (activeElement.detachEvent) {
activeElement.detachEvent('onpropertychange', handlePropertyChange);
} else {
activeElement.removeEventListener('propertychange', handlePropertyChange, false);
}
activeElement = null;
activeElementInst = null;
activeElementValue = null;
activeElementValueProp = null;
}
/**
* (For IE <=11) Handles a propertychange event, sending a `change` event if
* the value of the active element has changed.
*/
function handlePropertyChange(nativeEvent) {
if (nativeEvent.propertyName !== 'value') {
return;
}
var value = nativeEvent.srcElement.value;
if (value === activeElementValue) {
return;
}
activeElementValue = value;
manualDispatchChangeEvent(nativeEvent);
}
/**
* If a `change` event should be fired, returns the target's ID.
*/
function getTargetInstForInputEvent(topLevelType, targetInst) {
if (topLevelType === 'topInput') {
// In modern browsers (i.e., not IE8 or IE9), the input event is exactly
// what we want so fall through here and trigger an abstract event
return targetInst;
}
}
function handleEventsForInputEventIE(topLevelType, target, targetInst) {
if (topLevelType === 'topFocus') {
// In IE8, we can capture almost all .value changes by adding a
// propertychange handler and looking for events with propertyName
// equal to 'value'
// In IE9-11, propertychange fires for most input events but is buggy and
// doesn't fire when text is deleted, but conveniently, selectionchange
// appears to fire in all of the remaining cases so we catch those and
// forward the event if the value has changed
// In either case, we don't want to call the event handler if the value
// is changed from JS so we redefine a setter for `.value` that updates
// our activeElementValue variable, allowing us to ignore those changes
//
// stopWatching() should be a noop here but we call it just in case we
// missed a blur event somehow.
stopWatchingForValueChange();
startWatchingForValueChange(target, targetInst);
} else if (topLevelType === 'topBlur') {
stopWatchingForValueChange();
}
}
// For IE8 and IE9.
function getTargetInstForInputEventIE(topLevelType, targetInst) {
if (topLevelType === 'topSelectionChange' || topLevelType === 'topKeyUp' || topLevelType === 'topKeyDown') {
// On the selectionchange event, the target is just document which isn't
// helpful for us so just check activeElement instead.
//
// 99% of the time, keydown and keyup aren't necessary. IE8 fails to fire
// propertychange on the first input event after setting `value` from a
// script and fires only keydown, keypress, keyup. Catching keyup usually
// gets it and catching keydown lets us fire an event for the first
// keystroke if user does a key repeat (it'll be a little delayed: right
// before the second keystroke). Other input methods (e.g., paste) seem to
// fire selectionchange normally.
if (activeElement && activeElement.value !== activeElementValue) {
activeElementValue = activeElement.value;
return activeElementInst;
}
}
}
/**
* SECTION: handle `click` event
*/
function shouldUseClickEvent(elem) {
// Use the `click` event to detect changes to checkbox and radio inputs.
// This approach works across all browsers, whereas `change` does not fire
// until `blur` in IE8.
return elem.nodeName && elem.nodeName.toLowerCase() === 'input' && (elem.type === 'checkbox' || elem.type === 'radio');
}
function getTargetInstForClickEvent(topLevelType, targetInst) {
if (topLevelType === 'topClick') {
return targetInst;
}
}
function handleControlledInputBlur(inst, node) {
// TODO: In IE, inst is occasionally null. Why?
if (inst == null) {
return;
}
// Fiber and ReactDOM keep wrapper state in separate places
var state = inst._wrapperState || node._wrapperState;
if (!state || !state.controlled || node.type !== 'number') {
return;
}
// If controlled, assign the value attribute to the current value on blur
var value = '' + node.value;
if (node.getAttribute('value') !== value) {
node.setAttribute('value', value);
}
}
/**
* This plugin creates an `onChange` event that normalizes change events
* across form elements. This event fires at a time when it's possible to
* change the element's value without seeing a flicker.
*
* Supported elements are:
* - input (see `isTextInputElement`)
* - textarea
* - select
*/
var ChangeEventPlugin = {
eventTypes: eventTypes,
extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) {
var targetNode = targetInst ? ReactDOMComponentTree.getNodeFromInstance(targetInst) : window;
var getTargetInstFunc, handleEventFunc;
if (shouldUseChangeEvent(targetNode)) {
if (doesChangeEventBubble) {
getTargetInstFunc = getTargetInstForChangeEvent;
} else {
handleEventFunc = handleEventsForChangeEventIE8;
}
} else if (isTextInputElement(targetNode)) {
if (isInputEventSupported) {
getTargetInstFunc = getTargetInstForInputEvent;
} else {
getTargetInstFunc = getTargetInstForInputEventIE;
handleEventFunc = handleEventsForInputEventIE;
}
} else if (shouldUseClickEvent(targetNode)) {
getTargetInstFunc = getTargetInstForClickEvent;
}
if (getTargetInstFunc) {
var inst = getTargetInstFunc(topLevelType, targetInst);
if (inst) {
var event = SyntheticEvent.getPooled(eventTypes.change, inst, nativeEvent, nativeEventTarget);
event.type = 'change';
EventPropagators.accumulateTwoPhaseDispatches(event);
return event;
}
}
if (handleEventFunc) {
handleEventFunc(topLevelType, targetNode, targetInst);
}
// When blurring, set the value attribute for number inputs
if (topLevelType === 'topBlur') {
handleControlledInputBlur(targetInst, targetNode);
}
}
};
module.exports = ChangeEventPlugin;
},{"./EventPluginHub":50,"./EventPropagators":53,"./ReactDOMComponentTree":67,"./ReactUpdates":111,"./SyntheticEvent":120,"./getEventTarget":143,"./isEventSupported":150,"./isTextInputElement":151,"fbjs/lib/ExecutionEnvironment":5}],42:[function(require,module,exports){
(function (process){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var DOMLazyTree = require('./DOMLazyTree');
var Danger = require('./Danger');
var ReactDOMComponentTree = require('./ReactDOMComponentTree');
var ReactInstrumentation = require('./ReactInstrumentation');
var createMicrosoftUnsafeLocalFunction = require('./createMicrosoftUnsafeLocalFunction');
var setInnerHTML = require('./setInnerHTML');
var setTextContent = require('./setTextContent');
function getNodeAfter(parentNode, node) {
// Special case for text components, which return [open, close] comments
// from getHostNode.
if (Array.isArray(node)) {
node = node[1];
}
return node ? node.nextSibling : parentNode.firstChild;
}
/**
* Inserts `childNode` as a child of `parentNode` at the `index`.
*
* @param {DOMElement} parentNode Parent node in which to insert.
* @param {DOMElement} childNode Child node to insert.
* @param {number} index Index at which to insert the child.
* @internal
*/
var insertChildAt = createMicrosoftUnsafeLocalFunction(function (parentNode, childNode, referenceNode) {
// We rely exclusively on `insertBefore(node, null)` instead of also using
// `appendChild(node)`. (Using `undefined` is not allowed by all browsers so
// we are careful to use `null`.)
parentNode.insertBefore(childNode, referenceNode);
});
function insertLazyTreeChildAt(parentNode, childTree, referenceNode) {
DOMLazyTree.insertTreeBefore(parentNode, childTree, referenceNode);
}
function moveChild(parentNode, childNode, referenceNode) {
if (Array.isArray(childNode)) {
moveDelimitedText(parentNode, childNode[0], childNode[1], referenceNode);
} else {
insertChildAt(parentNode, childNode, referenceNode);
}
}
function removeChild(parentNode, childNode) {
if (Array.isArray(childNode)) {
var closingComment = childNode[1];
childNode = childNode[0];
removeDelimitedText(parentNode, childNode, closingComment);
parentNode.removeChild(closingComment);
}
parentNode.removeChild(childNode);
}
function moveDelimitedText(parentNode, openingComment, closingComment, referenceNode) {
var node = openingComment;
while (true) {
var nextNode = node.nextSibling;
insertChildAt(parentNode, node, referenceNode);
if (node === closingComment) {
break;
}
node = nextNode;
}
}
function removeDelimitedText(parentNode, startNode, closingComment) {
while (true) {
var node = startNode.nextSibling;
if (node === closingComment) {
// The closing comment is removed by ReactMultiChild.
break;
} else {
parentNode.removeChild(node);
}
}
}
function replaceDelimitedText(openingComment, closingComment, stringText) {
var parentNode = openingComment.parentNode;
var nodeAfterComment = openingComment.nextSibling;
if (nodeAfterComment === closingComment) {
// There are no text nodes between the opening and closing comments; insert
// a new one if stringText isn't empty.
if (stringText) {
insertChildAt(parentNode, document.createTextNode(stringText), nodeAfterComment);
}
} else {
if (stringText) {
// Set the text content of the first node after the opening comment, and
// remove all following nodes up until the closing comment.
setTextContent(nodeAfterComment, stringText);
removeDelimitedText(parentNode, nodeAfterComment, closingComment);
} else {
removeDelimitedText(parentNode, openingComment, closingComment);
}
}
if (process.env.NODE_ENV !== 'production') {
ReactInstrumentation.debugTool.onHostOperation({
instanceID: ReactDOMComponentTree.getInstanceFromNode(openingComment)._debugID,
type: 'replace text',
payload: stringText
});
}
}
var dangerouslyReplaceNodeWithMarkup = Danger.dangerouslyReplaceNodeWithMarkup;
if (process.env.NODE_ENV !== 'production') {
dangerouslyReplaceNodeWithMarkup = function (oldChild, markup, prevInstance) {
Danger.dangerouslyReplaceNodeWithMarkup(oldChild, markup);
if (prevInstance._debugID !== 0) {
ReactInstrumentation.debugTool.onHostOperation({
instanceID: prevInstance._debugID,
type: 'replace with',
payload: markup.toString()
});
} else {
var nextInstance = ReactDOMComponentTree.getInstanceFromNode(markup.node);
if (nextInstance._debugID !== 0) {
ReactInstrumentation.debugTool.onHostOperation({
instanceID: nextInstance._debugID,
type: 'mount',
payload: markup.toString()
});
}
}
};
}
/**
* Operations for updating with DOM children.
*/
var DOMChildrenOperations = {
dangerouslyReplaceNodeWithMarkup: dangerouslyReplaceNodeWithMarkup,
replaceDelimitedText: replaceDelimitedText,
/**
* Updates a component's children by processing a series of updates. The
* update configurations are each expected to have a `parentNode` property.
*
* @param {array<object>} updates List of update configurations.
* @internal
*/
processUpdates: function (parentNode, updates) {
if (process.env.NODE_ENV !== 'production') {
var parentNodeDebugID = ReactDOMComponentTree.getInstanceFromNode(parentNode)._debugID;
}
for (var k = 0; k < updates.length; k++) {
var update = updates[k];
switch (update.type) {
case 'INSERT_MARKUP':
insertLazyTreeChildAt(parentNode, update.content, getNodeAfter(parentNode, update.afterNode));
if (process.env.NODE_ENV !== 'production') {
ReactInstrumentation.debugTool.onHostOperation({
instanceID: parentNodeDebugID,
type: 'insert child',
payload: { toIndex: update.toIndex, content: update.content.toString() }
});
}
break;
case 'MOVE_EXISTING':
moveChild(parentNode, update.fromNode, getNodeAfter(parentNode, update.afterNode));
if (process.env.NODE_ENV !== 'production') {
ReactInstrumentation.debugTool.onHostOperation({
instanceID: parentNodeDebugID,
type: 'move child',
payload: { fromIndex: update.fromIndex, toIndex: update.toIndex }
});
}
break;
case 'SET_MARKUP':
setInnerHTML(parentNode, update.content);
if (process.env.NODE_ENV !== 'production') {
ReactInstrumentation.debugTool.onHostOperation({
instanceID: parentNodeDebugID,
type: 'replace children',
payload: update.content.toString()
});
}
break;
case 'TEXT_CONTENT':
setTextContent(parentNode, update.content);
if (process.env.NODE_ENV !== 'production') {
ReactInstrumentation.debugTool.onHostOperation({
instanceID: parentNodeDebugID,
type: 'replace text',
payload: update.content.toString()
});
}
break;
case 'REMOVE_NODE':
removeChild(parentNode, update.fromNode);
if (process.env.NODE_ENV !== 'production') {
ReactInstrumentation.debugTool.onHostOperation({
instanceID: parentNodeDebugID,
type: 'remove child',
payload: { fromIndex: update.fromIndex }
});
}
break;
}
}
}
};
module.exports = DOMChildrenOperations;
}).call(this,require('_process'))
},{"./DOMLazyTree":43,"./Danger":47,"./ReactDOMComponentTree":67,"./ReactInstrumentation":96,"./createMicrosoftUnsafeLocalFunction":134,"./setInnerHTML":155,"./setTextContent":156,"_process":29}],43:[function(require,module,exports){
/**
* Copyright 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var DOMNamespaces = require('./DOMNamespaces');
var setInnerHTML = require('./setInnerHTML');
var createMicrosoftUnsafeLocalFunction = require('./createMicrosoftUnsafeLocalFunction');
var setTextContent = require('./setTextContent');
var ELEMENT_NODE_TYPE = 1;
var DOCUMENT_FRAGMENT_NODE_TYPE = 11;
/**
* In IE (8-11) and Edge, appending nodes with no children is dramatically
* faster than appending a full subtree, so we essentially queue up the
* .appendChild calls here and apply them so each node is added to its parent
* before any children are added.
*
* In other browsers, doing so is slower or neutral compared to the other order
* (in Firefox, twice as slow) so we only do this inversion in IE.
*
* See https://github.com/spicyj/innerhtml-vs-createelement-vs-clonenode.
*/
var enableLazy = typeof document !== 'undefined' && typeof document.documentMode === 'number' || typeof navigator !== 'undefined' && typeof navigator.userAgent === 'string' && /\bEdge\/\d/.test(navigator.userAgent);
function insertTreeChildren(tree) {
if (!enableLazy) {
return;
}
var node = tree.node;
var children = tree.children;
if (children.length) {
for (var i = 0; i < children.length; i++) {
insertTreeBefore(node, children[i], null);
}
} else if (tree.html != null) {
setInnerHTML(node, tree.html);
} else if (tree.text != null) {
setTextContent(node, tree.text);
}
}
var insertTreeBefore = createMicrosoftUnsafeLocalFunction(function (parentNode, tree, referenceNode) {
// DocumentFragments aren't actually part of the DOM after insertion so
// appending children won't update the DOM. We need to ensure the fragment
// is properly populated first, breaking out of our lazy approach for just
// this level. Also, some <object> plugins (like Flash Player) will read
// <param> nodes immediately upon insertion into the DOM, so <object>
// must also be populated prior to insertion into the DOM.
if (tree.node.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE || tree.node.nodeType === ELEMENT_NODE_TYPE && tree.node.nodeName.toLowerCase() === 'object' && (tree.node.namespaceURI == null || tree.node.namespaceURI === DOMNamespaces.html)) {
insertTreeChildren(tree);
parentNode.insertBefore(tree.node, referenceNode);
} else {
parentNode.insertBefore(tree.node, referenceNode);
insertTreeChildren(tree);
}
});
function replaceChildWithTree(oldNode, newTree) {
oldNode.parentNode.replaceChild(newTree.node, oldNode);
insertTreeChildren(newTree);
}
function queueChild(parentTree, childTree) {
if (enableLazy) {
parentTree.children.push(childTree);
} else {
parentTree.node.appendChild(childTree.node);
}
}
function queueHTML(tree, html) {
if (enableLazy) {
tree.html = html;
} else {
setInnerHTML(tree.node, html);
}
}
function queueText(tree, text) {
if (enableLazy) {
tree.text = text;
} else {
setTextContent(tree.node, text);
}
}
function toString() {
return this.node.nodeName;
}
function DOMLazyTree(node) {
return {
node: node,
children: [],
html: null,
text: null,
toString: toString
};
}
DOMLazyTree.insertTreeBefore = insertTreeBefore;
DOMLazyTree.replaceChildWithTree = replaceChildWithTree;
DOMLazyTree.queueChild = queueChild;
DOMLazyTree.queueHTML = queueHTML;
DOMLazyTree.queueText = queueText;
module.exports = DOMLazyTree;
},{"./DOMNamespaces":44,"./createMicrosoftUnsafeLocalFunction":134,"./setInnerHTML":155,"./setTextContent":156}],44:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var DOMNamespaces = {
html: 'http://www.w3.org/1999/xhtml',
mathml: 'http://www.w3.org/1998/Math/MathML',
svg: 'http://www.w3.org/2000/svg'
};
module.exports = DOMNamespaces;
},{}],45:[function(require,module,exports){
(function (process){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var _prodInvariant = require('./reactProdInvariant');
var invariant = require('fbjs/lib/invariant');
function checkMask(value, bitmask) {
return (value & bitmask) === bitmask;
}
var DOMPropertyInjection = {
/**
* Mapping from normalized, camelcased property names to a configuration that
* specifies how the associated DOM property should be accessed or rendered.
*/
MUST_USE_PROPERTY: 0x1,
HAS_BOOLEAN_VALUE: 0x4,
HAS_NUMERIC_VALUE: 0x8,
HAS_POSITIVE_NUMERIC_VALUE: 0x10 | 0x8,
HAS_OVERLOADED_BOOLEAN_VALUE: 0x20,
/**
* Inject some specialized knowledge about the DOM. This takes a config object
* with the following properties:
*
* isCustomAttribute: function that given an attribute name will return true
* if it can be inserted into the DOM verbatim. Useful for data-* or aria-*
* attributes where it's impossible to enumerate all of the possible
* attribute names,
*
* Properties: object mapping DOM property name to one of the
* DOMPropertyInjection constants or null. If your attribute isn't in here,
* it won't get written to the DOM.
*
* DOMAttributeNames: object mapping React attribute name to the DOM
* attribute name. Attribute names not specified use the **lowercase**
* normalized name.
*
* DOMAttributeNamespaces: object mapping React attribute name to the DOM
* attribute namespace URL. (Attribute names not specified use no namespace.)
*
* DOMPropertyNames: similar to DOMAttributeNames but for DOM properties.
* Property names not specified use the normalized name.
*
* DOMMutationMethods: Properties that require special mutation methods. If
* `value` is undefined, the mutation method should unset the property.
*
* @param {object} domPropertyConfig the config as described above.
*/
injectDOMPropertyConfig: function (domPropertyConfig) {
var Injection = DOMPropertyInjection;
var Properties = domPropertyConfig.Properties || {};
var DOMAttributeNamespaces = domPropertyConfig.DOMAttributeNamespaces || {};
var DOMAttributeNames = domPropertyConfig.DOMAttributeNames || {};
var DOMPropertyNames = domPropertyConfig.DOMPropertyNames || {};
var DOMMutationMethods = domPropertyConfig.DOMMutationMethods || {};
if (domPropertyConfig.isCustomAttribute) {
DOMProperty._isCustomAttributeFunctions.push(domPropertyConfig.isCustomAttribute);
}
for (var propName in Properties) {
!!DOMProperty.properties.hasOwnProperty(propName) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'injectDOMPropertyConfig(...): You\'re trying to inject DOM property \'%s\' which has already been injected. You may be accidentally injecting the same DOM property config twice, or you may be injecting two configs that have conflicting property names.', propName) : _prodInvariant('48', propName) : void 0;
var lowerCased = propName.toLowerCase();
var propConfig = Properties[propName];
var propertyInfo = {
attributeName: lowerCased,
attributeNamespace: null,
propertyName: propName,
mutationMethod: null,
mustUseProperty: checkMask(propConfig, Injection.MUST_USE_PROPERTY),
hasBooleanValue: checkMask(propConfig, Injection.HAS_BOOLEAN_VALUE),
hasNumericValue: checkMask(propConfig, Injection.HAS_NUMERIC_VALUE),
hasPositiveNumericValue: checkMask(propConfig, Injection.HAS_POSITIVE_NUMERIC_VALUE),
hasOverloadedBooleanValue: checkMask(propConfig, Injection.HAS_OVERLOADED_BOOLEAN_VALUE)
};
!(propertyInfo.hasBooleanValue + propertyInfo.hasNumericValue + propertyInfo.hasOverloadedBooleanValue <= 1) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'DOMProperty: Value can be one of boolean, overloaded boolean, or numeric value, but not a combination: %s', propName) : _prodInvariant('50', propName) : void 0;
if (process.env.NODE_ENV !== 'production') {
DOMProperty.getPossibleStandardName[lowerCased] = propName;
}
if (DOMAttributeNames.hasOwnProperty(propName)) {
var attributeName = DOMAttributeNames[propName];
propertyInfo.attributeName = attributeName;
if (process.env.NODE_ENV !== 'production') {
DOMProperty.getPossibleStandardName[attributeName] = propName;
}
}
if (DOMAttributeNamespaces.hasOwnProperty(propName)) {
propertyInfo.attributeNamespace = DOMAttributeNamespaces[propName];
}
if (DOMPropertyNames.hasOwnProperty(propName)) {
propertyInfo.propertyName = DOMPropertyNames[propName];
}
if (DOMMutationMethods.hasOwnProperty(propName)) {
propertyInfo.mutationMethod = DOMMutationMethods[propName];
}
DOMProperty.properties[propName] = propertyInfo;
}
}
};
/* eslint-disable max-len */
var ATTRIBUTE_NAME_START_CHAR = ':A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD';
/* eslint-enable max-len */
/**
* DOMProperty exports lookup objects that can be used like functions:
*
* > DOMProperty.isValid['id']
* true
* > DOMProperty.isValid['foobar']
* undefined
*
* Although this may be confusing, it performs better in general.
*
* @see http://jsperf.com/key-exists
* @see http://jsperf.com/key-missing
*/
var DOMProperty = {
ID_ATTRIBUTE_NAME: 'data-reactid',
ROOT_ATTRIBUTE_NAME: 'data-reactroot',
ATTRIBUTE_NAME_START_CHAR: ATTRIBUTE_NAME_START_CHAR,
ATTRIBUTE_NAME_CHAR: ATTRIBUTE_NAME_START_CHAR + '\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040',
/**
* Map from property "standard name" to an object with info about how to set
* the property in the DOM. Each object contains:
*
* attributeName:
* Used when rendering markup or with `*Attribute()`.
* attributeNamespace
* propertyName:
* Used on DOM node instances. (This includes properties that mutate due to
* external factors.)
* mutationMethod:
* If non-null, used instead of the property or `setAttribute()` after
* initial render.
* mustUseProperty:
* Whether the property must be accessed and mutated as an object property.
* hasBooleanValue:
* Whether the property should be removed when set to a falsey value.
* hasNumericValue:
* Whether the property must be numeric or parse as a numeric and should be
* removed when set to a falsey value.
* hasPositiveNumericValue:
* Whether the property must be positive numeric or parse as a positive
* numeric and should be removed when set to a falsey value.
* hasOverloadedBooleanValue:
* Whether the property can be used as a flag as well as with a value.
* Removed when strictly equal to false; present without a value when
* strictly equal to true; present with a value otherwise.
*/
properties: {},
/**
* Mapping from lowercase property names to the properly cased version, used
* to warn in the case of missing properties. Available only in __DEV__.
*
* autofocus is predefined, because adding it to the property whitelist
* causes unintended side effects.
*
* @type {Object}
*/
getPossibleStandardName: process.env.NODE_ENV !== 'production' ? { autofocus: 'autoFocus' } : null,
/**
* All of the isCustomAttribute() functions that have been injected.
*/
_isCustomAttributeFunctions: [],
/**
* Checks whether a property name is a custom attribute.
* @method
*/
isCustomAttribute: function (attributeName) {
for (var i = 0; i < DOMProperty._isCustomAttributeFunctions.length; i++) {
var isCustomAttributeFn = DOMProperty._isCustomAttributeFunctions[i];
if (isCustomAttributeFn(attributeName)) {
return true;
}
}
return false;
},
injection: DOMPropertyInjection
};
module.exports = DOMProperty;
}).call(this,require('_process'))
},{"./reactProdInvariant":153,"_process":29,"fbjs/lib/invariant":19}],46:[function(require,module,exports){
(function (process){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var DOMProperty = require('./DOMProperty');
var ReactDOMComponentTree = require('./ReactDOMComponentTree');
var ReactInstrumentation = require('./ReactInstrumentation');
var quoteAttributeValueForBrowser = require('./quoteAttributeValueForBrowser');
var warning = require('fbjs/lib/warning');
var VALID_ATTRIBUTE_NAME_REGEX = new RegExp('^[' + DOMProperty.ATTRIBUTE_NAME_START_CHAR + '][' + DOMProperty.ATTRIBUTE_NAME_CHAR + ']*$');
var illegalAttributeNameCache = {};
var validatedAttributeNameCache = {};
function isAttributeNameSafe(attributeName) {
if (validatedAttributeNameCache.hasOwnProperty(attributeName)) {
return true;
}
if (illegalAttributeNameCache.hasOwnProperty(attributeName)) {
return false;
}
if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) {
validatedAttributeNameCache[attributeName] = true;
return true;
}
illegalAttributeNameCache[attributeName] = true;
process.env.NODE_ENV !== 'production' ? warning(false, 'Invalid attribute name: `%s`', attributeName) : void 0;
return false;
}
function shouldIgnoreValue(propertyInfo, value) {
return value == null || propertyInfo.hasBooleanValue && !value || propertyInfo.hasNumericValue && isNaN(value) || propertyInfo.hasPositiveNumericValue && value < 1 || propertyInfo.hasOverloadedBooleanValue && value === false;
}
/**
* Operations for dealing with DOM properties.
*/
var DOMPropertyOperations = {
/**
* Creates markup for the ID property.
*
* @param {string} id Unescaped ID.
* @return {string} Markup string.
*/
createMarkupForID: function (id) {
return DOMProperty.ID_ATTRIBUTE_NAME + '=' + quoteAttributeValueForBrowser(id);
},
setAttributeForID: function (node, id) {
node.setAttribute(DOMProperty.ID_ATTRIBUTE_NAME, id);
},
createMarkupForRoot: function () {
return DOMProperty.ROOT_ATTRIBUTE_NAME + '=""';
},
setAttributeForRoot: function (node) {
node.setAttribute(DOMProperty.ROOT_ATTRIBUTE_NAME, '');
},
/**
* Creates markup for a property.
*
* @param {string} name
* @param {*} value
* @return {?string} Markup string, or null if the property was invalid.
*/
createMarkupForProperty: function (name, value) {
var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? DOMProperty.properties[name] : null;
if (propertyInfo) {
if (shouldIgnoreValue(propertyInfo, value)) {
return '';
}
var attributeName = propertyInfo.attributeName;
if (propertyInfo.hasBooleanValue || propertyInfo.hasOverloadedBooleanValue && value === true) {
return attributeName + '=""';
}
return attributeName + '=' + quoteAttributeValueForBrowser(value);
} else if (DOMProperty.isCustomAttribute(name)) {
if (value == null) {
return '';
}
return name + '=' + quoteAttributeValueForBrowser(value);
}
return null;
},
/**
* Creates markup for a custom property.
*
* @param {string} name
* @param {*} value
* @return {string} Markup string, or empty string if the property was invalid.
*/
createMarkupForCustomAttribute: function (name, value) {
if (!isAttributeNameSafe(name) || value == null) {
return '';
}
return name + '=' + quoteAttributeValueForBrowser(value);
},
/**
* Sets the value for a property on a node.
*
* @param {DOMElement} node
* @param {string} name
* @param {*} value
*/
setValueForProperty: function (node, name, value) {
var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? DOMProperty.properties[name] : null;
if (propertyInfo) {
var mutationMethod = propertyInfo.mutationMethod;
if (mutationMethod) {
mutationMethod(node, value);
} else if (shouldIgnoreValue(propertyInfo, value)) {
this.deleteValueForProperty(node, name);
return;
} else if (propertyInfo.mustUseProperty) {
// Contrary to `setAttribute`, object properties are properly
// `toString`ed by IE8/9.
node[propertyInfo.propertyName] = value;
} else {
var attributeName = propertyInfo.attributeName;
var namespace = propertyInfo.attributeNamespace;
// `setAttribute` with objects becomes only `[object]` in IE8/9,
// ('' + value) makes it output the correct toString()-value.
if (namespace) {
node.setAttributeNS(namespace, attributeName, '' + value);
} else if (propertyInfo.hasBooleanValue || propertyInfo.hasOverloadedBooleanValue && value === true) {
node.setAttribute(attributeName, '');
} else {
node.setAttribute(attributeName, '' + value);
}
}
} else if (DOMProperty.isCustomAttribute(name)) {
DOMPropertyOperations.setValueForAttribute(node, name, value);
return;
}
if (process.env.NODE_ENV !== 'production') {
var payload = {};
payload[name] = value;
ReactInstrumentation.debugTool.onHostOperation({
instanceID: ReactDOMComponentTree.getInstanceFromNode(node)._debugID,
type: 'update attribute',
payload: payload
});
}
},
setValueForAttribute: function (node, name, value) {
if (!isAttributeNameSafe(name)) {
return;
}
if (value == null) {
node.removeAttribute(name);
} else {
node.setAttribute(name, '' + value);
}
if (process.env.NODE_ENV !== 'production') {
var payload = {};
payload[name] = value;
ReactInstrumentation.debugTool.onHostOperation({
instanceID: ReactDOMComponentTree.getInstanceFromNode(node)._debugID,
type: 'update attribute',
payload: payload
});
}
},
/**
* Deletes an attributes from a node.
*
* @param {DOMElement} node
* @param {string} name
*/
deleteValueForAttribute: function (node, name) {
node.removeAttribute(name);
if (process.env.NODE_ENV !== 'production') {
ReactInstrumentation.debugTool.onHostOperation({
instanceID: ReactDOMComponentTree.getInstanceFromNode(node)._debugID,
type: 'remove attribute',
payload: name
});
}
},
/**
* Deletes the value for a property on a node.
*
* @param {DOMElement} node
* @param {string} name
*/
deleteValueForProperty: function (node, name) {
var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? DOMProperty.properties[name] : null;
if (propertyInfo) {
var mutationMethod = propertyInfo.mutationMethod;
if (mutationMethod) {
mutationMethod(node, undefined);
} else if (propertyInfo.mustUseProperty) {
var propName = propertyInfo.propertyName;
if (propertyInfo.hasBooleanValue) {
node[propName] = false;
} else {
node[propName] = '';
}
} else {
node.removeAttribute(propertyInfo.attributeName);
}
} else if (DOMProperty.isCustomAttribute(name)) {
node.removeAttribute(name);
}
if (process.env.NODE_ENV !== 'production') {
ReactInstrumentation.debugTool.onHostOperation({
instanceID: ReactDOMComponentTree.getInstanceFromNode(node)._debugID,
type: 'remove attribute',
payload: name
});
}
}
};
module.exports = DOMPropertyOperations;
}).call(this,require('_process'))
},{"./DOMProperty":45,"./ReactDOMComponentTree":67,"./ReactInstrumentation":96,"./quoteAttributeValueForBrowser":152,"_process":29,"fbjs/lib/warning":26}],47:[function(require,module,exports){
(function (process){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var _prodInvariant = require('./reactProdInvariant');
var DOMLazyTree = require('./DOMLazyTree');
var ExecutionEnvironment = require('fbjs/lib/ExecutionEnvironment');
var createNodesFromMarkup = require('fbjs/lib/createNodesFromMarkup');
var emptyFunction = require('fbjs/lib/emptyFunction');
var invariant = require('fbjs/lib/invariant');
var Danger = {
/**
* Replaces a node with a string of markup at its current position within its
* parent. The markup must render into a single root node.
*
* @param {DOMElement} oldChild Child node to replace.
* @param {string} markup Markup to render in place of the child node.
* @internal
*/
dangerouslyReplaceNodeWithMarkup: function (oldChild, markup) {
!ExecutionEnvironment.canUseDOM ? process.env.NODE_ENV !== 'production' ? invariant(false, 'dangerouslyReplaceNodeWithMarkup(...): Cannot render markup in a worker thread. Make sure `window` and `document` are available globally before requiring React when unit testing or use ReactDOMServer.renderToString() for server rendering.') : _prodInvariant('56') : void 0;
!markup ? process.env.NODE_ENV !== 'production' ? invariant(false, 'dangerouslyReplaceNodeWithMarkup(...): Missing markup.') : _prodInvariant('57') : void 0;
!(oldChild.nodeName !== 'HTML') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'dangerouslyReplaceNodeWithMarkup(...): Cannot replace markup of the <html> node. This is because browser quirks make this unreliable and/or slow. If you want to render to the root you must use server rendering. See ReactDOMServer.renderToString().') : _prodInvariant('58') : void 0;
if (typeof markup === 'string') {
var newChild = createNodesFromMarkup(markup, emptyFunction)[0];
oldChild.parentNode.replaceChild(newChild, oldChild);
} else {
DOMLazyTree.replaceChildWithTree(oldChild, markup);
}
}
};
module.exports = Danger;
}).call(this,require('_process'))
},{"./DOMLazyTree":43,"./reactProdInvariant":153,"_process":29,"fbjs/lib/ExecutionEnvironment":5,"fbjs/lib/createNodesFromMarkup":10,"fbjs/lib/emptyFunction":11,"fbjs/lib/invariant":19}],48:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
/**
* Module that is injectable into `EventPluginHub`, that specifies a
* deterministic ordering of `EventPlugin`s. A convenient way to reason about
* plugins, without having to package every one of them. This is better than
* having plugins be ordered in the same order that they are injected because
* that ordering would be influenced by the packaging order.
* `ResponderEventPlugin` must occur before `SimpleEventPlugin` so that
* preventing default on events is convenient in `SimpleEventPlugin` handlers.
*/
var DefaultEventPluginOrder = ['ResponderEventPlugin', 'SimpleEventPlugin', 'TapEventPlugin', 'EnterLeaveEventPlugin', 'ChangeEventPlugin', 'SelectEventPlugin', 'BeforeInputEventPlugin'];
module.exports = DefaultEventPluginOrder;
},{}],49:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var EventPropagators = require('./EventPropagators');
var ReactDOMComponentTree = require('./ReactDOMComponentTree');
var SyntheticMouseEvent = require('./SyntheticMouseEvent');
var eventTypes = {
mouseEnter: {
registrationName: 'onMouseEnter',
dependencies: ['topMouseOut', 'topMouseOver']
},
mouseLeave: {
registrationName: 'onMouseLeave',
dependencies: ['topMouseOut', 'topMouseOver']
}
};
var EnterLeaveEventPlugin = {
eventTypes: eventTypes,
/**
* For almost every interaction we care about, there will be both a top-level
* `mouseover` and `mouseout` event that occurs. Only use `mouseout` so that
* we do not extract duplicate events. However, moving the mouse into the
* browser from outside will not fire a `mouseout` event. In this case, we use
* the `mouseover` top-level event.
*/
extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) {
if (topLevelType === 'topMouseOver' && (nativeEvent.relatedTarget || nativeEvent.fromElement)) {
return null;
}
if (topLevelType !== 'topMouseOut' && topLevelType !== 'topMouseOver') {
// Must not be a mouse in or mouse out - ignoring.
return null;
}
var win;
if (nativeEventTarget.window === nativeEventTarget) {
// `nativeEventTarget` is probably a window object.
win = nativeEventTarget;
} else {
// TODO: Figure out why `ownerDocument` is sometimes undefined in IE8.
var doc = nativeEventTarget.ownerDocument;
if (doc) {
win = doc.defaultView || doc.parentWindow;
} else {
win = window;
}
}
var from;
var to;
if (topLevelType === 'topMouseOut') {
from = targetInst;
var related = nativeEvent.relatedTarget || nativeEvent.toElement;
to = related ? ReactDOMComponentTree.getClosestInstanceFromNode(related) : null;
} else {
// Moving to a node from outside the window.
from = null;
to = targetInst;
}
if (from === to) {
// Nothing pertains to our managed components.
return null;
}
var fromNode = from == null ? win : ReactDOMComponentTree.getNodeFromInstance(from);
var toNode = to == null ? win : ReactDOMComponentTree.getNodeFromInstance(to);
var leave = SyntheticMouseEvent.getPooled(eventTypes.mouseLeave, from, nativeEvent, nativeEventTarget);
leave.type = 'mouseleave';
leave.target = fromNode;
leave.relatedTarget = toNode;
var enter = SyntheticMouseEvent.getPooled(eventTypes.mouseEnter, to, nativeEvent, nativeEventTarget);
enter.type = 'mouseenter';
enter.target = toNode;
enter.relatedTarget = fromNode;
EventPropagators.accumulateEnterLeaveDispatches(leave, enter, from, to);
return [leave, enter];
}
};
module.exports = EnterLeaveEventPlugin;
},{"./EventPropagators":53,"./ReactDOMComponentTree":67,"./SyntheticMouseEvent":124}],50:[function(require,module,exports){
(function (process){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var _prodInvariant = require('./reactProdInvariant');
var EventPluginRegistry = require('./EventPluginRegistry');
var EventPluginUtils = require('./EventPluginUtils');
var ReactErrorUtils = require('./ReactErrorUtils');
var accumulateInto = require('./accumulateInto');
var forEachAccumulated = require('./forEachAccumulated');
var invariant = require('fbjs/lib/invariant');
/**
* Internal store for event listeners
*/
var listenerBank = {};
/**
* Internal queue of events that have accumulated their dispatches and are
* waiting to have their dispatches executed.
*/
var eventQueue = null;
/**
* Dispatches an event and releases it back into the pool, unless persistent.
*
* @param {?object} event Synthetic event to be dispatched.
* @param {boolean} simulated If the event is simulated (changes exn behavior)
* @private
*/
var executeDispatchesAndRelease = function (event, simulated) {
if (event) {
EventPluginUtils.executeDispatchesInOrder(event, simulated);
if (!event.isPersistent()) {
event.constructor.release(event);
}
}
};
var executeDispatchesAndReleaseSimulated = function (e) {
return executeDispatchesAndRelease(e, true);
};
var executeDispatchesAndReleaseTopLevel = function (e) {
return executeDispatchesAndRelease(e, false);
};
var getDictionaryKey = function (inst) {
// Prevents V8 performance issue:
// https://github.com/facebook/react/pull/7232
return '.' + inst._rootNodeID;
};
function isInteractive(tag) {
return tag === 'button' || tag === 'input' || tag === 'select' || tag === 'textarea';
}
function shouldPreventMouseEvent(name, type, props) {
switch (name) {
case 'onClick':
case 'onClickCapture':
case 'onDoubleClick':
case 'onDoubleClickCapture':
case 'onMouseDown':
case 'onMouseDownCapture':
case 'onMouseMove':
case 'onMouseMoveCapture':
case 'onMouseUp':
case 'onMouseUpCapture':
return !!(props.disabled && isInteractive(type));
default:
return false;
}
}
/**
* This is a unified interface for event plugins to be installed and configured.
*
* Event plugins can implement the following properties:
*
* `extractEvents` {function(string, DOMEventTarget, string, object): *}
* Required. When a top-level event is fired, this method is expected to
* extract synthetic events that will in turn be queued and dispatched.
*
* `eventTypes` {object}
* Optional, plugins that fire events must publish a mapping of registration
* names that are used to register listeners. Values of this mapping must
* be objects that contain `registrationName` or `phasedRegistrationNames`.
*
* `executeDispatch` {function(object, function, string)}
* Optional, allows plugins to override how an event gets dispatched. By
* default, the listener is simply invoked.
*
* Each plugin that is injected into `EventsPluginHub` is immediately operable.
*
* @public
*/
var EventPluginHub = {
/**
* Methods for injecting dependencies.
*/
injection: {
/**
* @param {array} InjectedEventPluginOrder
* @public
*/
injectEventPluginOrder: EventPluginRegistry.injectEventPluginOrder,
/**
* @param {object} injectedNamesToPlugins Map from names to plugin modules.
*/
injectEventPluginsByName: EventPluginRegistry.injectEventPluginsByName
},
/**
* Stores `listener` at `listenerBank[registrationName][key]`. Is idempotent.
*
* @param {object} inst The instance, which is the source of events.
* @param {string} registrationName Name of listener (e.g. `onClick`).
* @param {function} listener The callback to store.
*/
putListener: function (inst, registrationName, listener) {
!(typeof listener === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected %s listener to be a function, instead got type %s', registrationName, typeof listener) : _prodInvariant('94', registrationName, typeof listener) : void 0;
var key = getDictionaryKey(inst);
var bankForRegistrationName = listenerBank[registrationName] || (listenerBank[registrationName] = {});
bankForRegistrationName[key] = listener;
var PluginModule = EventPluginRegistry.registrationNameModules[registrationName];
if (PluginModule && PluginModule.didPutListener) {
PluginModule.didPutListener(inst, registrationName, listener);
}
},
/**
* @param {object} inst The instance, which is the source of events.
* @param {string} registrationName Name of listener (e.g. `onClick`).
* @return {?function} The stored callback.
*/
getListener: function (inst, registrationName) {
// TODO: shouldPreventMouseEvent is DOM-specific and definitely should not
// live here; needs to be moved to a better place soon
var bankForRegistrationName = listenerBank[registrationName];
if (shouldPreventMouseEvent(registrationName, inst._currentElement.type, inst._currentElement.props)) {
return null;
}
var key = getDictionaryKey(inst);
return bankForRegistrationName && bankForRegistrationName[key];
},
/**
* Deletes a listener from the registration bank.
*
* @param {object} inst The instance, which is the source of events.
* @param {string} registrationName Name of listener (e.g. `onClick`).
*/
deleteListener: function (inst, registrationName) {
var PluginModule = EventPluginRegistry.registrationNameModules[registrationName];
if (PluginModule && PluginModule.willDeleteListener) {
PluginModule.willDeleteListener(inst, registrationName);
}
var bankForRegistrationName = listenerBank[registrationName];
// TODO: This should never be null -- when is it?
if (bankForRegistrationName) {
var key = getDictionaryKey(inst);
delete bankForRegistrationName[key];
}
},
/**
* Deletes all listeners for the DOM element with the supplied ID.
*
* @param {object} inst The instance, which is the source of events.
*/
deleteAllListeners: function (inst) {
var key = getDictionaryKey(inst);
for (var registrationName in listenerBank) {
if (!listenerBank.hasOwnProperty(registrationName)) {
continue;
}
if (!listenerBank[registrationName][key]) {
continue;
}
var PluginModule = EventPluginRegistry.registrationNameModules[registrationName];
if (PluginModule && PluginModule.willDeleteListener) {
PluginModule.willDeleteListener(inst, registrationName);
}
delete listenerBank[registrationName][key];
}
},
/**
* Allows registered plugins an opportunity to extract events from top-level
* native browser events.
*
* @return {*} An accumulation of synthetic events.
* @internal
*/
extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) {
var events;
var plugins = EventPluginRegistry.plugins;
for (var i = 0; i < plugins.length; i++) {
// Not every plugin in the ordering may be loaded at runtime.
var possiblePlugin = plugins[i];
if (possiblePlugin) {
var extractedEvents = possiblePlugin.extractEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget);
if (extractedEvents) {
events = accumulateInto(events, extractedEvents);
}
}
}
return events;
},
/**
* Enqueues a synthetic event that should be dispatched when
* `processEventQueue` is invoked.
*
* @param {*} events An accumulation of synthetic events.
* @internal
*/
enqueueEvents: function (events) {
if (events) {
eventQueue = accumulateInto(eventQueue, events);
}
},
/**
* Dispatches all synthetic events on the event queue.
*
* @internal
*/
processEventQueue: function (simulated) {
// Set `eventQueue` to null before processing it so that we can tell if more
// events get enqueued while processing.
var processingEventQueue = eventQueue;
eventQueue = null;
if (simulated) {
forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseSimulated);
} else {
forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseTopLevel);
}
!!eventQueue ? process.env.NODE_ENV !== 'production' ? invariant(false, 'processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented.') : _prodInvariant('95') : void 0;
// This would be a good time to rethrow if any of the event handlers threw.
ReactErrorUtils.rethrowCaughtError();
},
/**
* These are needed for tests only. Do not use!
*/
__purge: function () {
listenerBank = {};
},
__getListenerBank: function () {
return listenerBank;
}
};
module.exports = EventPluginHub;
}).call(this,require('_process'))
},{"./EventPluginRegistry":51,"./EventPluginUtils":52,"./ReactErrorUtils":87,"./accumulateInto":131,"./forEachAccumulated":139,"./reactProdInvariant":153,"_process":29,"fbjs/lib/invariant":19}],51:[function(require,module,exports){
(function (process){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
'use strict';
var _prodInvariant = require('./reactProdInvariant');
var invariant = require('fbjs/lib/invariant');
/**
* Injectable ordering of event plugins.
*/
var eventPluginOrder = null;
/**
* Injectable mapping from names to event plugin modules.
*/
var namesToPlugins = {};
/**
* Recomputes the plugin list using the injected plugins and plugin ordering.
*
* @private
*/
function recomputePluginOrdering() {
if (!eventPluginOrder) {
// Wait until an `eventPluginOrder` is injected.
return;
}
for (var pluginName in namesToPlugins) {
var pluginModule = namesToPlugins[pluginName];
var pluginIndex = eventPluginOrder.indexOf(pluginName);
!(pluginIndex > -1) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `%s`.', pluginName) : _prodInvariant('96', pluginName) : void 0;
if (EventPluginRegistry.plugins[pluginIndex]) {
continue;
}
!pluginModule.extractEvents ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `%s` does not.', pluginName) : _prodInvariant('97', pluginName) : void 0;
EventPluginRegistry.plugins[pluginIndex] = pluginModule;
var publishedEvents = pluginModule.eventTypes;
for (var eventName in publishedEvents) {
!publishEventForPlugin(publishedEvents[eventName], pluginModule, eventName) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginRegistry: Failed to publish event `%s` for plugin `%s`.', eventName, pluginName) : _prodInvariant('98', eventName, pluginName) : void 0;
}
}
}
/**
* Publishes an event so that it can be dispatched by the supplied plugin.
*
* @param {object} dispatchConfig Dispatch configuration for the event.
* @param {object} PluginModule Plugin publishing the event.
* @return {boolean} True if the event was successfully published.
* @private
*/
function publishEventForPlugin(dispatchConfig, pluginModule, eventName) {
!!EventPluginRegistry.eventNameDispatchConfigs.hasOwnProperty(eventName) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginHub: More than one plugin attempted to publish the same event name, `%s`.', eventName) : _prodInvariant('99', eventName) : void 0;
EventPluginRegistry.eventNameDispatchConfigs[eventName] = dispatchConfig;
var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames;
if (phasedRegistrationNames) {
for (var phaseName in phasedRegistrationNames) {
if (phasedRegistrationNames.hasOwnProperty(phaseName)) {
var phasedRegistrationName = phasedRegistrationNames[phaseName];
publishRegistrationName(phasedRegistrationName, pluginModule, eventName);
}
}
return true;
} else if (dispatchConfig.registrationName) {
publishRegistrationName(dispatchConfig.registrationName, pluginModule, eventName);
return true;
}
return false;
}
/**
* Publishes a registration name that is used to identify dispatched events and
* can be used with `EventPluginHub.putListener` to register listeners.
*
* @param {string} registrationName Registration name to add.
* @param {object} PluginModule Plugin publishing the event.
* @private
*/
function publishRegistrationName(registrationName, pluginModule, eventName) {
!!EventPluginRegistry.registrationNameModules[registrationName] ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginHub: More than one plugin attempted to publish the same registration name, `%s`.', registrationName) : _prodInvariant('100', registrationName) : void 0;
EventPluginRegistry.registrationNameModules[registrationName] = pluginModule;
EventPluginRegistry.registrationNameDependencies[registrationName] = pluginModule.eventTypes[eventName].dependencies;
if (process.env.NODE_ENV !== 'production') {
var lowerCasedName = registrationName.toLowerCase();
EventPluginRegistry.possibleRegistrationNames[lowerCasedName] = registrationName;
if (registrationName === 'onDoubleClick') {
EventPluginRegistry.possibleRegistrationNames.ondblclick = registrationName;
}
}
}
/**
* Registers plugins so that they can extract and dispatch events.
*
* @see {EventPluginHub}
*/
var EventPluginRegistry = {
/**
* Ordered list of injected plugins.
*/
plugins: [],
/**
* Mapping from event name to dispatch config
*/
eventNameDispatchConfigs: {},
/**
* Mapping from registration name to plugin module
*/
registrationNameModules: {},
/**
* Mapping from registration name to event name
*/
registrationNameDependencies: {},
/**
* Mapping from lowercase registration names to the properly cased version,
* used to warn in the case of missing event handlers. Available
* only in __DEV__.
* @type {Object}
*/
possibleRegistrationNames: process.env.NODE_ENV !== 'production' ? {} : null,
// Trust the developer to only use possibleRegistrationNames in __DEV__
/**
* Injects an ordering of plugins (by plugin name). This allows the ordering
* to be decoupled from injection of the actual plugins so that ordering is
* always deterministic regardless of packaging, on-the-fly injection, etc.
*
* @param {array} InjectedEventPluginOrder
* @internal
* @see {EventPluginHub.injection.injectEventPluginOrder}
*/
injectEventPluginOrder: function (injectedEventPluginOrder) {
!!eventPluginOrder ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginRegistry: Cannot inject event plugin ordering more than once. You are likely trying to load more than one copy of React.') : _prodInvariant('101') : void 0;
// Clone the ordering so it cannot be dynamically mutated.
eventPluginOrder = Array.prototype.slice.call(injectedEventPluginOrder);
recomputePluginOrdering();
},
/**
* Injects plugins to be used by `EventPluginHub`. The plugin names must be
* in the ordering injected by `injectEventPluginOrder`.
*
* Plugins can be injected as part of page initialization or on-the-fly.
*
* @param {object} injectedNamesToPlugins Map from names to plugin modules.
* @internal
* @see {EventPluginHub.injection.injectEventPluginsByName}
*/
injectEventPluginsByName: function (injectedNamesToPlugins) {
var isOrderingDirty = false;
for (var pluginName in injectedNamesToPlugins) {
if (!injectedNamesToPlugins.hasOwnProperty(pluginName)) {
continue;
}
var pluginModule = injectedNamesToPlugins[pluginName];
if (!namesToPlugins.hasOwnProperty(pluginName) || namesToPlugins[pluginName] !== pluginModule) {
!!namesToPlugins[pluginName] ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginRegistry: Cannot inject two different event plugins using the same name, `%s`.', pluginName) : _prodInvariant('102', pluginName) : void 0;
namesToPlugins[pluginName] = pluginModule;
isOrderingDirty = true;
}
}
if (isOrderingDirty) {
recomputePluginOrdering();
}
},
/**
* Looks up the plugin for the supplied event.
*
* @param {object} event A synthetic event.
* @return {?object} The plugin that created the supplied event.
* @internal
*/
getPluginModuleForEvent: function (event) {
var dispatchConfig = event.dispatchConfig;
if (dispatchConfig.registrationName) {
return EventPluginRegistry.registrationNameModules[dispatchConfig.registrationName] || null;
}
if (dispatchConfig.phasedRegistrationNames !== undefined) {
// pulling phasedRegistrationNames out of dispatchConfig helps Flow see
// that it is not undefined.
var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames;
for (var phase in phasedRegistrationNames) {
if (!phasedRegistrationNames.hasOwnProperty(phase)) {
continue;
}
var pluginModule = EventPluginRegistry.registrationNameModules[phasedRegistrationNames[phase]];
if (pluginModule) {
return pluginModule;
}
}
}
return null;
},
/**
* Exposed for unit testing.
* @private
*/
_resetEventPlugins: function () {
eventPluginOrder = null;
for (var pluginName in namesToPlugins) {
if (namesToPlugins.hasOwnProperty(pluginName)) {
delete namesToPlugins[pluginName];
}
}
EventPluginRegistry.plugins.length = 0;
var eventNameDispatchConfigs = EventPluginRegistry.eventNameDispatchConfigs;
for (var eventName in eventNameDispatchConfigs) {
if (eventNameDispatchConfigs.hasOwnProperty(eventName)) {
delete eventNameDispatchConfigs[eventName];
}
}
var registrationNameModules = EventPluginRegistry.registrationNameModules;
for (var registrationName in registrationNameModules) {
if (registrationNameModules.hasOwnProperty(registrationName)) {
delete registrationNameModules[registrationName];
}
}
if (process.env.NODE_ENV !== 'production') {
var possibleRegistrationNames = EventPluginRegistry.possibleRegistrationNames;
for (var lowerCasedName in possibleRegistrationNames) {
if (possibleRegistrationNames.hasOwnProperty(lowerCasedName)) {
delete possibleRegistrationNames[lowerCasedName];
}
}
}
}
};
module.exports = EventPluginRegistry;
}).call(this,require('_process'))
},{"./reactProdInvariant":153,"_process":29,"fbjs/lib/invariant":19}],52:[function(require,module,exports){
(function (process){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var _prodInvariant = require('./reactProdInvariant');
var ReactErrorUtils = require('./ReactErrorUtils');
var invariant = require('fbjs/lib/invariant');
var warning = require('fbjs/lib/warning');
/**
* Injected dependencies:
*/
/**
* - `ComponentTree`: [required] Module that can convert between React instances
* and actual node references.
*/
var ComponentTree;
var TreeTraversal;
var injection = {
injectComponentTree: function (Injected) {
ComponentTree = Injected;
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(Injected && Injected.getNodeFromInstance && Injected.getInstanceFromNode, 'EventPluginUtils.injection.injectComponentTree(...): Injected ' + 'module is missing getNodeFromInstance or getInstanceFromNode.') : void 0;
}
},
injectTreeTraversal: function (Injected) {
TreeTraversal = Injected;
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(Injected && Injected.isAncestor && Injected.getLowestCommonAncestor, 'EventPluginUtils.injection.injectTreeTraversal(...): Injected ' + 'module is missing isAncestor or getLowestCommonAncestor.') : void 0;
}
}
};
function isEndish(topLevelType) {
return topLevelType === 'topMouseUp' || topLevelType === 'topTouchEnd' || topLevelType === 'topTouchCancel';
}
function isMoveish(topLevelType) {
return topLevelType === 'topMouseMove' || topLevelType === 'topTouchMove';
}
function isStartish(topLevelType) {
return topLevelType === 'topMouseDown' || topLevelType === 'topTouchStart';
}
var validateEventDispatches;
if (process.env.NODE_ENV !== 'production') {
validateEventDispatches = function (event) {
var dispatchListeners = event._dispatchListeners;
var dispatchInstances = event._dispatchInstances;
var listenersIsArr = Array.isArray(dispatchListeners);
var listenersLen = listenersIsArr ? dispatchListeners.length : dispatchListeners ? 1 : 0;
var instancesIsArr = Array.isArray(dispatchInstances);
var instancesLen = instancesIsArr ? dispatchInstances.length : dispatchInstances ? 1 : 0;
process.env.NODE_ENV !== 'production' ? warning(instancesIsArr === listenersIsArr && instancesLen === listenersLen, 'EventPluginUtils: Invalid `event`.') : void 0;
};
}
/**
* Dispatch the event to the listener.
* @param {SyntheticEvent} event SyntheticEvent to handle
* @param {boolean} simulated If the event is simulated (changes exn behavior)
* @param {function} listener Application-level callback
* @param {*} inst Internal component instance
*/
function executeDispatch(event, simulated, listener, inst) {
var type = event.type || 'unknown-event';
event.currentTarget = EventPluginUtils.getNodeFromInstance(inst);
if (simulated) {
ReactErrorUtils.invokeGuardedCallbackWithCatch(type, listener, event);
} else {
ReactErrorUtils.invokeGuardedCallback(type, listener, event);
}
event.currentTarget = null;
}
/**
* Standard/simple iteration through an event's collected dispatches.
*/
function executeDispatchesInOrder(event, simulated) {
var dispatchListeners = event._dispatchListeners;
var dispatchInstances = event._dispatchInstances;
if (process.env.NODE_ENV !== 'production') {
validateEventDispatches(event);
}
if (Array.isArray(dispatchListeners)) {
for (var i = 0; i < dispatchListeners.length; i++) {
if (event.isPropagationStopped()) {
break;
}
// Listeners and Instances are two parallel arrays that are always in sync.
executeDispatch(event, simulated, dispatchListeners[i], dispatchInstances[i]);
}
} else if (dispatchListeners) {
executeDispatch(event, simulated, dispatchListeners, dispatchInstances);
}
event._dispatchListeners = null;
event._dispatchInstances = null;
}
/**
* Standard/simple iteration through an event's collected dispatches, but stops
* at the first dispatch execution returning true, and returns that id.
*
* @return {?string} id of the first dispatch execution who's listener returns
* true, or null if no listener returned true.
*/
function executeDispatchesInOrderStopAtTrueImpl(event) {
var dispatchListeners = event._dispatchListeners;
var dispatchInstances = event._dispatchInstances;
if (process.env.NODE_ENV !== 'production') {
validateEventDispatches(event);
}
if (Array.isArray(dispatchListeners)) {
for (var i = 0; i < dispatchListeners.length; i++) {
if (event.isPropagationStopped()) {
break;
}
// Listeners and Instances are two parallel arrays that are always in sync.
if (dispatchListeners[i](event, dispatchInstances[i])) {
return dispatchInstances[i];
}
}
} else if (dispatchListeners) {
if (dispatchListeners(event, dispatchInstances)) {
return dispatchInstances;
}
}
return null;
}
/**
* @see executeDispatchesInOrderStopAtTrueImpl
*/
function executeDispatchesInOrderStopAtTrue(event) {
var ret = executeDispatchesInOrderStopAtTrueImpl(event);
event._dispatchInstances = null;
event._dispatchListeners = null;
return ret;
}
/**
* Execution of a "direct" dispatch - there must be at most one dispatch
* accumulated on the event or it is considered an error. It doesn't really make
* sense for an event with multiple dispatches (bubbled) to keep track of the
* return values at each dispatch execution, but it does tend to make sense when
* dealing with "direct" dispatches.
*
* @return {*} The return value of executing the single dispatch.
*/
function executeDirectDispatch(event) {
if (process.env.NODE_ENV !== 'production') {
validateEventDispatches(event);
}
var dispatchListener = event._dispatchListeners;
var dispatchInstance = event._dispatchInstances;
!!Array.isArray(dispatchListener) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'executeDirectDispatch(...): Invalid `event`.') : _prodInvariant('103') : void 0;
event.currentTarget = dispatchListener ? EventPluginUtils.getNodeFromInstance(dispatchInstance) : null;
var res = dispatchListener ? dispatchListener(event) : null;
event.currentTarget = null;
event._dispatchListeners = null;
event._dispatchInstances = null;
return res;
}
/**
* @param {SyntheticEvent} event
* @return {boolean} True iff number of dispatches accumulated is greater than 0.
*/
function hasDispatches(event) {
return !!event._dispatchListeners;
}
/**
* General utilities that are useful in creating custom Event Plugins.
*/
var EventPluginUtils = {
isEndish: isEndish,
isMoveish: isMoveish,
isStartish: isStartish,
executeDirectDispatch: executeDirectDispatch,
executeDispatchesInOrder: executeDispatchesInOrder,
executeDispatchesInOrderStopAtTrue: executeDispatchesInOrderStopAtTrue,
hasDispatches: hasDispatches,
getInstanceFromNode: function (node) {
return ComponentTree.getInstanceFromNode(node);
},
getNodeFromInstance: function (node) {
return ComponentTree.getNodeFromInstance(node);
},
isAncestor: function (a, b) {
return TreeTraversal.isAncestor(a, b);
},
getLowestCommonAncestor: function (a, b) {
return TreeTraversal.getLowestCommonAncestor(a, b);
},
getParentInstance: function (inst) {
return TreeTraversal.getParentInstance(inst);
},
traverseTwoPhase: function (target, fn, arg) {
return TreeTraversal.traverseTwoPhase(target, fn, arg);
},
traverseEnterLeave: function (from, to, fn, argFrom, argTo) {
return TreeTraversal.traverseEnterLeave(from, to, fn, argFrom, argTo);
},
injection: injection
};
module.exports = EventPluginUtils;
}).call(this,require('_process'))
},{"./ReactErrorUtils":87,"./reactProdInvariant":153,"_process":29,"fbjs/lib/invariant":19,"fbjs/lib/warning":26}],53:[function(require,module,exports){
(function (process){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var EventPluginHub = require('./EventPluginHub');
var EventPluginUtils = require('./EventPluginUtils');
var accumulateInto = require('./accumulateInto');
var forEachAccumulated = require('./forEachAccumulated');
var warning = require('fbjs/lib/warning');
var getListener = EventPluginHub.getListener;
/**
* Some event types have a notion of different registration names for different
* "phases" of propagation. This finds listeners by a given phase.
*/
function listenerAtPhase(inst, event, propagationPhase) {
var registrationName = event.dispatchConfig.phasedRegistrationNames[propagationPhase];
return getListener(inst, registrationName);
}
/**
* Tags a `SyntheticEvent` with dispatched listeners. Creating this function
* here, allows us to not have to bind or create functions for each event.
* Mutating the event's members allows us to not have to create a wrapping
* "dispatch" object that pairs the event with the listener.
*/
function accumulateDirectionalDispatches(inst, phase, event) {
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(inst, 'Dispatching inst must not be null') : void 0;
}
var listener = listenerAtPhase(inst, event, phase);
if (listener) {
event._dispatchListeners = accumulateInto(event._dispatchListeners, listener);
event._dispatchInstances = accumulateInto(event._dispatchInstances, inst);
}
}
/**
* Collect dispatches (must be entirely collected before dispatching - see unit
* tests). Lazily allocate the array to conserve memory. We must loop through
* each event and perform the traversal for each one. We cannot perform a
* single traversal for the entire collection of events because each event may
* have a different target.
*/
function accumulateTwoPhaseDispatchesSingle(event) {
if (event && event.dispatchConfig.phasedRegistrationNames) {
EventPluginUtils.traverseTwoPhase(event._targetInst, accumulateDirectionalDispatches, event);
}
}
/**
* Same as `accumulateTwoPhaseDispatchesSingle`, but skips over the targetID.
*/
function accumulateTwoPhaseDispatchesSingleSkipTarget(event) {
if (event && event.dispatchConfig.phasedRegistrationNames) {
var targetInst = event._targetInst;
var parentInst = targetInst ? EventPluginUtils.getParentInstance(targetInst) : null;
EventPluginUtils.traverseTwoPhase(parentInst, accumulateDirectionalDispatches, event);
}
}
/**
* Accumulates without regard to direction, does not look for phased
* registration names. Same as `accumulateDirectDispatchesSingle` but without
* requiring that the `dispatchMarker` be the same as the dispatched ID.
*/
function accumulateDispatches(inst, ignoredDirection, event) {
if (event && event.dispatchConfig.registrationName) {
var registrationName = event.dispatchConfig.registrationName;
var listener = getListener(inst, registrationName);
if (listener) {
event._dispatchListeners = accumulateInto(event._dispatchListeners, listener);
event._dispatchInstances = accumulateInto(event._dispatchInstances, inst);
}
}
}
/**
* Accumulates dispatches on an `SyntheticEvent`, but only for the
* `dispatchMarker`.
* @param {SyntheticEvent} event
*/
function accumulateDirectDispatchesSingle(event) {
if (event && event.dispatchConfig.registrationName) {
accumulateDispatches(event._targetInst, null, event);
}
}
function accumulateTwoPhaseDispatches(events) {
forEachAccumulated(events, accumulateTwoPhaseDispatchesSingle);
}
function accumulateTwoPhaseDispatchesSkipTarget(events) {
forEachAccumulated(events, accumulateTwoPhaseDispatchesSingleSkipTarget);
}
function accumulateEnterLeaveDispatches(leave, enter, from, to) {
EventPluginUtils.traverseEnterLeave(from, to, accumulateDispatches, leave, enter);
}
function accumulateDirectDispatches(events) {
forEachAccumulated(events, accumulateDirectDispatchesSingle);
}
/**
* A small set of propagation patterns, each of which will accept a small amount
* of information, and generate a set of "dispatch ready event objects" - which
* are sets of events that have already been annotated with a set of dispatched
* listener functions/ids. The API is designed this way to discourage these
* propagation strategies from actually executing the dispatches, since we
* always want to collect the entire set of dispatches before executing event a
* single one.
*
* @constructor EventPropagators
*/
var EventPropagators = {
accumulateTwoPhaseDispatches: accumulateTwoPhaseDispatches,
accumulateTwoPhaseDispatchesSkipTarget: accumulateTwoPhaseDispatchesSkipTarget,
accumulateDirectDispatches: accumulateDirectDispatches,
accumulateEnterLeaveDispatches: accumulateEnterLeaveDispatches
};
module.exports = EventPropagators;
}).call(this,require('_process'))
},{"./EventPluginHub":50,"./EventPluginUtils":52,"./accumulateInto":131,"./forEachAccumulated":139,"_process":29,"fbjs/lib/warning":26}],54:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var _assign = require('object-assign');
var PooledClass = require('./PooledClass');
var getTextContentAccessor = require('./getTextContentAccessor');
/**
* This helper class stores information about text content of a target node,
* allowing comparison of content before and after a given event.
*
* Identify the node where selection currently begins, then observe
* both its text content and its current position in the DOM. Since the
* browser may natively replace the target node during composition, we can
* use its position to find its replacement.
*
* @param {DOMEventTarget} root
*/
function FallbackCompositionState(root) {
this._root = root;
this._startText = this.getText();
this._fallbackText = null;
}
_assign(FallbackCompositionState.prototype, {
destructor: function () {
this._root = null;
this._startText = null;
this._fallbackText = null;
},
/**
* Get current text of input.
*
* @return {string}
*/
getText: function () {
if ('value' in this._root) {
return this._root.value;
}
return this._root[getTextContentAccessor()];
},
/**
* Determine the differing substring between the initially stored
* text content and the current content.
*
* @return {string}
*/
getData: function () {
if (this._fallbackText) {
return this._fallbackText;
}
var start;
var startValue = this._startText;
var startLength = startValue.length;
var end;
var endValue = this.getText();
var endLength = endValue.length;
for (start = 0; start < startLength; start++) {
if (startValue[start] !== endValue[start]) {
break;
}
}
var minEnd = startLength - start;
for (end = 1; end <= minEnd; end++) {
if (startValue[startLength - end] !== endValue[endLength - end]) {
break;
}
}
var sliceTail = end > 1 ? 1 - end : undefined;
this._fallbackText = endValue.slice(start, sliceTail);
return this._fallbackText;
}
});
PooledClass.addPoolingTo(FallbackCompositionState);
module.exports = FallbackCompositionState;
},{"./PooledClass":58,"./getTextContentAccessor":147,"object-assign":28}],55:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var DOMProperty = require('./DOMProperty');
var MUST_USE_PROPERTY = DOMProperty.injection.MUST_USE_PROPERTY;
var HAS_BOOLEAN_VALUE = DOMProperty.injection.HAS_BOOLEAN_VALUE;
var HAS_NUMERIC_VALUE = DOMProperty.injection.HAS_NUMERIC_VALUE;
var HAS_POSITIVE_NUMERIC_VALUE = DOMProperty.injection.HAS_POSITIVE_NUMERIC_VALUE;
var HAS_OVERLOADED_BOOLEAN_VALUE = DOMProperty.injection.HAS_OVERLOADED_BOOLEAN_VALUE;
var HTMLDOMPropertyConfig = {
isCustomAttribute: RegExp.prototype.test.bind(new RegExp('^(data|aria)-[' + DOMProperty.ATTRIBUTE_NAME_CHAR + ']*$')),
Properties: {
/**
* Standard Properties
*/
accept: 0,
acceptCharset: 0,
accessKey: 0,
action: 0,
allowFullScreen: HAS_BOOLEAN_VALUE,
allowTransparency: 0,
alt: 0,
// specifies target context for links with `preload` type
as: 0,
async: HAS_BOOLEAN_VALUE,
autoComplete: 0,
// autoFocus is polyfilled/normalized by AutoFocusUtils
// autoFocus: HAS_BOOLEAN_VALUE,
autoPlay: HAS_BOOLEAN_VALUE,
capture: HAS_BOOLEAN_VALUE,
cellPadding: 0,
cellSpacing: 0,
charSet: 0,
challenge: 0,
checked: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
cite: 0,
classID: 0,
className: 0,
cols: HAS_POSITIVE_NUMERIC_VALUE,
colSpan: 0,
content: 0,
contentEditable: 0,
contextMenu: 0,
controls: HAS_BOOLEAN_VALUE,
coords: 0,
crossOrigin: 0,
data: 0, // For `<object />` acts as `src`.
dateTime: 0,
'default': HAS_BOOLEAN_VALUE,
defer: HAS_BOOLEAN_VALUE,
dir: 0,
disabled: HAS_BOOLEAN_VALUE,
download: HAS_OVERLOADED_BOOLEAN_VALUE,
draggable: 0,
encType: 0,
form: 0,
formAction: 0,
formEncType: 0,
formMethod: 0,
formNoValidate: HAS_BOOLEAN_VALUE,
formTarget: 0,
frameBorder: 0,
headers: 0,
height: 0,
hidden: HAS_BOOLEAN_VALUE,
high: 0,
href: 0,
hrefLang: 0,
htmlFor: 0,
httpEquiv: 0,
icon: 0,
id: 0,
inputMode: 0,
integrity: 0,
is: 0,
keyParams: 0,
keyType: 0,
kind: 0,
label: 0,
lang: 0,
list: 0,
loop: HAS_BOOLEAN_VALUE,
low: 0,
manifest: 0,
marginHeight: 0,
marginWidth: 0,
max: 0,
maxLength: 0,
media: 0,
mediaGroup: 0,
method: 0,
min: 0,
minLength: 0,
// Caution; `option.selected` is not updated if `select.multiple` is
// disabled with `removeAttribute`.
multiple: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
muted: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
name: 0,
nonce: 0,
noValidate: HAS_BOOLEAN_VALUE,
open: HAS_BOOLEAN_VALUE,
optimum: 0,
pattern: 0,
placeholder: 0,
playsInline: HAS_BOOLEAN_VALUE,
poster: 0,
preload: 0,
profile: 0,
radioGroup: 0,
readOnly: HAS_BOOLEAN_VALUE,
referrerPolicy: 0,
rel: 0,
required: HAS_BOOLEAN_VALUE,
reversed: HAS_BOOLEAN_VALUE,
role: 0,
rows: HAS_POSITIVE_NUMERIC_VALUE,
rowSpan: HAS_NUMERIC_VALUE,
sandbox: 0,
scope: 0,
scoped: HAS_BOOLEAN_VALUE,
scrolling: 0,
seamless: HAS_BOOLEAN_VALUE,
selected: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
shape: 0,
size: HAS_POSITIVE_NUMERIC_VALUE,
sizes: 0,
span: HAS_POSITIVE_NUMERIC_VALUE,
spellCheck: 0,
src: 0,
srcDoc: 0,
srcLang: 0,
srcSet: 0,
start: HAS_NUMERIC_VALUE,
step: 0,
style: 0,
summary: 0,
tabIndex: 0,
target: 0,
title: 0,
// Setting .type throws on non-<input> tags
type: 0,
useMap: 0,
value: 0,
width: 0,
wmode: 0,
wrap: 0,
/**
* RDFa Properties
*/
about: 0,
datatype: 0,
inlist: 0,
prefix: 0,
// property is also supported for OpenGraph in meta tags.
property: 0,
resource: 0,
'typeof': 0,
vocab: 0,
/**
* Non-standard Properties
*/
// autoCapitalize and autoCorrect are supported in Mobile Safari for
// keyboard hints.
autoCapitalize: 0,
autoCorrect: 0,
// autoSave allows WebKit/Blink to persist values of input fields on page reloads
autoSave: 0,
// color is for Safari mask-icon link
color: 0,
// itemProp, itemScope, itemType are for
// Microdata support. See http://schema.org/docs/gs.html
itemProp: 0,
itemScope: HAS_BOOLEAN_VALUE,
itemType: 0,
// itemID and itemRef are for Microdata support as well but
// only specified in the WHATWG spec document. See
// https://html.spec.whatwg.org/multipage/microdata.html#microdata-dom-api
itemID: 0,
itemRef: 0,
// results show looking glass icon and recent searches on input
// search fields in WebKit/Blink
results: 0,
// IE-only attribute that specifies security restrictions on an iframe
// as an alternative to the sandbox attribute on IE<10
security: 0,
// IE-only attribute that controls focus behavior
unselectable: 0
},
DOMAttributeNames: {
acceptCharset: 'accept-charset',
className: 'class',
htmlFor: 'for',
httpEquiv: 'http-equiv'
},
DOMPropertyNames: {},
DOMMutationMethods: {
value: function (node, value) {
if (value == null) {
return node.removeAttribute('value');
}
// Number inputs get special treatment due to some edge cases in
// Chrome. Let everything else assign the value attribute as normal.
// https://github.com/facebook/react/issues/7253#issuecomment-236074326
if (node.type !== 'number' || node.hasAttribute('value') === false) {
node.setAttribute('value', '' + value);
} else if (node.validity && !node.validity.badInput && node.ownerDocument.activeElement !== node) {
// Don't assign an attribute if validation reports bad
// input. Chrome will clear the value. Additionally, don't
// operate on inputs that have focus, otherwise Chrome might
// strip off trailing decimal places and cause the user's
// cursor position to jump to the beginning of the input.
//
// In ReactDOMInput, we have an onBlur event that will trigger
// this function again when focus is lost.
node.setAttribute('value', '' + value);
}
}
}
};
module.exports = HTMLDOMPropertyConfig;
},{"./DOMProperty":45}],56:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
'use strict';
/**
* Escape and wrap key so it is safe to use as a reactid
*
* @param {string} key to be escaped.
* @return {string} the escaped key.
*/
function escape(key) {
var escapeRegex = /[=:]/g;
var escaperLookup = {
'=': '=0',
':': '=2'
};
var escapedString = ('' + key).replace(escapeRegex, function (match) {
return escaperLookup[match];
});
return '$' + escapedString;
}
/**
* Unescape and unwrap key for human-readable display
*
* @param {string} key to unescape.
* @return {string} the unescaped key.
*/
function unescape(key) {
var unescapeRegex = /(=0|=2)/g;
var unescaperLookup = {
'=0': '=',
'=2': ':'
};
var keySubstring = key[0] === '.' && key[1] === '$' ? key.substring(2) : key.substring(1);
return ('' + keySubstring).replace(unescapeRegex, function (match) {
return unescaperLookup[match];
});
}
var KeyEscapeUtils = {
escape: escape,
unescape: unescape
};
module.exports = KeyEscapeUtils;
},{}],57:[function(require,module,exports){
(function (process){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var _prodInvariant = require('./reactProdInvariant');
var ReactPropTypesSecret = require('./ReactPropTypesSecret');
var propTypesFactory = require('prop-types/factory');
var React = require('react/lib/React');
var PropTypes = propTypesFactory(React.isValidElement);
var invariant = require('fbjs/lib/invariant');
var warning = require('fbjs/lib/warning');
var hasReadOnlyValue = {
'button': true,
'checkbox': true,
'image': true,
'hidden': true,
'radio': true,
'reset': true,
'submit': true
};
function _assertSingleLink(inputProps) {
!(inputProps.checkedLink == null || inputProps.valueLink == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Cannot provide a checkedLink and a valueLink. If you want to use checkedLink, you probably don\'t want to use valueLink and vice versa.') : _prodInvariant('87') : void 0;
}
function _assertValueLink(inputProps) {
_assertSingleLink(inputProps);
!(inputProps.value == null && inputProps.onChange == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Cannot provide a valueLink and a value or onChange event. If you want to use value or onChange, you probably don\'t want to use valueLink.') : _prodInvariant('88') : void 0;
}
function _assertCheckedLink(inputProps) {
_assertSingleLink(inputProps);
!(inputProps.checked == null && inputProps.onChange == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Cannot provide a checkedLink and a checked property or onChange event. If you want to use checked or onChange, you probably don\'t want to use checkedLink') : _prodInvariant('89') : void 0;
}
var propTypes = {
value: function (props, propName, componentName) {
if (!props[propName] || hasReadOnlyValue[props.type] || props.onChange || props.readOnly || props.disabled) {
return null;
}
return new Error('You provided a `value` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultValue`. Otherwise, ' + 'set either `onChange` or `readOnly`.');
},
checked: function (props, propName, componentName) {
if (!props[propName] || props.onChange || props.readOnly || props.disabled) {
return null;
}
return new Error('You provided a `checked` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultChecked`. Otherwise, ' + 'set either `onChange` or `readOnly`.');
},
onChange: PropTypes.func
};
var loggedTypeFailures = {};
function getDeclarationErrorAddendum(owner) {
if (owner) {
var name = owner.getName();
if (name) {
return ' Check the render method of `' + name + '`.';
}
}
return '';
}
/**
* Provide a linked `value` attribute for controlled forms. You should not use
* this outside of the ReactDOM controlled form components.
*/
var LinkedValueUtils = {
checkPropTypes: function (tagName, props, owner) {
for (var propName in propTypes) {
if (propTypes.hasOwnProperty(propName)) {
var error = propTypes[propName](props, propName, tagName, 'prop', null, ReactPropTypesSecret);
}
if (error instanceof Error && !(error.message in loggedTypeFailures)) {
// Only monitor this failure once because there tends to be a lot of the
// same error.
loggedTypeFailures[error.message] = true;
var addendum = getDeclarationErrorAddendum(owner);
process.env.NODE_ENV !== 'production' ? warning(false, 'Failed form propType: %s%s', error.message, addendum) : void 0;
}
}
},
/**
* @param {object} inputProps Props for form component
* @return {*} current value of the input either from value prop or link.
*/
getValue: function (inputProps) {
if (inputProps.valueLink) {
_assertValueLink(inputProps);
return inputProps.valueLink.value;
}
return inputProps.value;
},
/**
* @param {object} inputProps Props for form component
* @return {*} current checked status of the input either from checked prop
* or link.
*/
getChecked: function (inputProps) {
if (inputProps.checkedLink) {
_assertCheckedLink(inputProps);
return inputProps.checkedLink.value;
}
return inputProps.checked;
},
/**
* @param {object} inputProps Props for form component
* @param {SyntheticEvent} event change event to handle
*/
executeOnChange: function (inputProps, event) {
if (inputProps.valueLink) {
_assertValueLink(inputProps);
return inputProps.valueLink.requestChange(event.target.value);
} else if (inputProps.checkedLink) {
_assertCheckedLink(inputProps);
return inputProps.checkedLink.requestChange(event.target.checked);
} else if (inputProps.onChange) {
return inputProps.onChange.call(undefined, event);
}
}
};
module.exports = LinkedValueUtils;
}).call(this,require('_process'))
},{"./ReactPropTypesSecret":104,"./reactProdInvariant":153,"_process":29,"fbjs/lib/invariant":19,"fbjs/lib/warning":26,"prop-types/factory":161,"react/lib/React":165}],58:[function(require,module,exports){
(function (process){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
'use strict';
var _prodInvariant = require('./reactProdInvariant');
var invariant = require('fbjs/lib/invariant');
/**
* Static poolers. Several custom versions for each potential number of
* arguments. A completely generic pooler is easy to implement, but would
* require accessing the `arguments` object. In each of these, `this` refers to
* the Class itself, not an instance. If any others are needed, simply add them
* here, or in their own files.
*/
var oneArgumentPooler = function (copyFieldsFrom) {
var Klass = this;
if (Klass.instancePool.length) {
var instance = Klass.instancePool.pop();
Klass.call(instance, copyFieldsFrom);
return instance;
} else {
return new Klass(copyFieldsFrom);
}
};
var twoArgumentPooler = function (a1, a2) {
var Klass = this;
if (Klass.instancePool.length) {
var instance = Klass.instancePool.pop();
Klass.call(instance, a1, a2);
return instance;
} else {
return new Klass(a1, a2);
}
};
var threeArgumentPooler = function (a1, a2, a3) {
var Klass = this;
if (Klass.instancePool.length) {
var instance = Klass.instancePool.pop();
Klass.call(instance, a1, a2, a3);
return instance;
} else {
return new Klass(a1, a2, a3);
}
};
var fourArgumentPooler = function (a1, a2, a3, a4) {
var Klass = this;
if (Klass.instancePool.length) {
var instance = Klass.instancePool.pop();
Klass.call(instance, a1, a2, a3, a4);
return instance;
} else {
return new Klass(a1, a2, a3, a4);
}
};
var standardReleaser = function (instance) {
var Klass = this;
!(instance instanceof Klass) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Trying to release an instance into a pool of a different type.') : _prodInvariant('25') : void 0;
instance.destructor();
if (Klass.instancePool.length < Klass.poolSize) {
Klass.instancePool.push(instance);
}
};
var DEFAULT_POOL_SIZE = 10;
var DEFAULT_POOLER = oneArgumentPooler;
/**
* Augments `CopyConstructor` to be a poolable class, augmenting only the class
* itself (statically) not adding any prototypical fields. Any CopyConstructor
* you give this may have a `poolSize` property, and will look for a
* prototypical `destructor` on instances.
*
* @param {Function} CopyConstructor Constructor that can be used to reset.
* @param {Function} pooler Customizable pooler.
*/
var addPoolingTo = function (CopyConstructor, pooler) {
// Casting as any so that flow ignores the actual implementation and trusts
// it to match the type we declared
var NewKlass = CopyConstructor;
NewKlass.instancePool = [];
NewKlass.getPooled = pooler || DEFAULT_POOLER;
if (!NewKlass.poolSize) {
NewKlass.poolSize = DEFAULT_POOL_SIZE;
}
NewKlass.release = standardReleaser;
return NewKlass;
};
var PooledClass = {
addPoolingTo: addPoolingTo,
oneArgumentPooler: oneArgumentPooler,
twoArgumentPooler: twoArgumentPooler,
threeArgumentPooler: threeArgumentPooler,
fourArgumentPooler: fourArgumentPooler
};
module.exports = PooledClass;
}).call(this,require('_process'))
},{"./reactProdInvariant":153,"_process":29,"fbjs/lib/invariant":19}],59:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var _assign = require('object-assign');
var EventPluginRegistry = require('./EventPluginRegistry');
var ReactEventEmitterMixin = require('./ReactEventEmitterMixin');
var ViewportMetrics = require('./ViewportMetrics');
var getVendorPrefixedEventName = require('./getVendorPrefixedEventName');
var isEventSupported = require('./isEventSupported');
/**
* Summary of `ReactBrowserEventEmitter` event handling:
*
* - Top-level delegation is used to trap most native browser events. This
* may only occur in the main thread and is the responsibility of
* ReactEventListener, which is injected and can therefore support pluggable
* event sources. This is the only work that occurs in the main thread.
*
* - We normalize and de-duplicate events to account for browser quirks. This
* may be done in the worker thread.
*
* - Forward these native events (with the associated top-level type used to
* trap it) to `EventPluginHub`, which in turn will ask plugins if they want
* to extract any synthetic events.
*
* - The `EventPluginHub` will then process each event by annotating them with
* "dispatches", a sequence of listeners and IDs that care about that event.
*
* - The `EventPluginHub` then dispatches the events.
*
* Overview of React and the event system:
*
* +------------+ .
* | DOM | .
* +------------+ .
* | .
* v .
* +------------+ .
* | ReactEvent | .
* | Listener | .
* +------------+ . +-----------+
* | . +--------+|SimpleEvent|
* | . | |Plugin |
* +-----|------+ . v +-----------+
* | | | . +--------------+ +------------+
* | +-----------.--->|EventPluginHub| | Event |
* | | . | | +-----------+ | Propagators|
* | ReactEvent | . | | |TapEvent | |------------|
* | Emitter | . | |<---+|Plugin | |other plugin|
* | | . | | +-----------+ | utilities |
* | +-----------.--->| | +------------+
* | | | . +--------------+
* +-----|------+ . ^ +-----------+
* | . | |Enter/Leave|
* + . +-------+|Plugin |
* +-------------+ . +-----------+
* | application | .
* |-------------| .
* | | .
* | | .
* +-------------+ .
* .
* React Core . General Purpose Event Plugin System
*/
var hasEventPageXY;
var alreadyListeningTo = {};
var isMonitoringScrollValue = false;
var reactTopListenersCounter = 0;
// For events like 'submit' which don't consistently bubble (which we trap at a
// lower node than `document`), binding at `document` would cause duplicate
// events so we don't include them here
var topEventMapping = {
topAbort: 'abort',
topAnimationEnd: getVendorPrefixedEventName('animationend') || 'animationend',
topAnimationIteration: getVendorPrefixedEventName('animationiteration') || 'animationiteration',
topAnimationStart: getVendorPrefixedEventName('animationstart') || 'animationstart',
topBlur: 'blur',
topCanPlay: 'canplay',
topCanPlayThrough: 'canplaythrough',
topChange: 'change',
topClick: 'click',
topCompositionEnd: 'compositionend',
topCompositionStart: 'compositionstart',
topCompositionUpdate: 'compositionupdate',
topContextMenu: 'contextmenu',
topCopy: 'copy',
topCut: 'cut',
topDoubleClick: 'dblclick',
topDrag: 'drag',
topDragEnd: 'dragend',
topDragEnter: 'dragenter',
topDragExit: 'dragexit',
topDragLeave: 'dragleave',
topDragOver: 'dragover',
topDragStart: 'dragstart',
topDrop: 'drop',
topDurationChange: 'durationchange',
topEmptied: 'emptied',
topEncrypted: 'encrypted',
topEnded: 'ended',
topError: 'error',
topFocus: 'focus',
topInput: 'input',
topKeyDown: 'keydown',
topKeyPress: 'keypress',
topKeyUp: 'keyup',
topLoadedData: 'loadeddata',
topLoadedMetadata: 'loadedmetadata',
topLoadStart: 'loadstart',
topMouseDown: 'mousedown',
topMouseMove: 'mousemove',
topMouseOut: 'mouseout',
topMouseOver: 'mouseover',
topMouseUp: 'mouseup',
topPaste: 'paste',
topPause: 'pause',
topPlay: 'play',
topPlaying: 'playing',
topProgress: 'progress',
topRateChange: 'ratechange',
topScroll: 'scroll',
topSeeked: 'seeked',
topSeeking: 'seeking',
topSelectionChange: 'selectionchange',
topStalled: 'stalled',
topSuspend: 'suspend',
topTextInput: 'textInput',
topTimeUpdate: 'timeupdate',
topTouchCancel: 'touchcancel',
topTouchEnd: 'touchend',
topTouchMove: 'touchmove',
topTouchStart: 'touchstart',
topTransitionEnd: getVendorPrefixedEventName('transitionend') || 'transitionend',
topVolumeChange: 'volumechange',
topWaiting: 'waiting',
topWheel: 'wheel'
};
/**
* To ensure no conflicts with other potential React instances on the page
*/
var topListenersIDKey = '_reactListenersID' + String(Math.random()).slice(2);
function getListeningForDocument(mountAt) {
// In IE8, `mountAt` is a host object and doesn't have `hasOwnProperty`
// directly.
if (!Object.prototype.hasOwnProperty.call(mountAt, topListenersIDKey)) {
mountAt[topListenersIDKey] = reactTopListenersCounter++;
alreadyListeningTo[mountAt[topListenersIDKey]] = {};
}
return alreadyListeningTo[mountAt[topListenersIDKey]];
}
/**
* `ReactBrowserEventEmitter` is used to attach top-level event listeners. For
* example:
*
* EventPluginHub.putListener('myID', 'onClick', myFunction);
*
* This would allocate a "registration" of `('onClick', myFunction)` on 'myID'.
*
* @internal
*/
var ReactBrowserEventEmitter = _assign({}, ReactEventEmitterMixin, {
/**
* Injectable event backend
*/
ReactEventListener: null,
injection: {
/**
* @param {object} ReactEventListener
*/
injectReactEventListener: function (ReactEventListener) {
ReactEventListener.setHandleTopLevel(ReactBrowserEventEmitter.handleTopLevel);
ReactBrowserEventEmitter.ReactEventListener = ReactEventListener;
}
},
/**
* Sets whether or not any created callbacks should be enabled.
*
* @param {boolean} enabled True if callbacks should be enabled.
*/
setEnabled: function (enabled) {
if (ReactBrowserEventEmitter.ReactEventListener) {
ReactBrowserEventEmitter.ReactEventListener.setEnabled(enabled);
}
},
/**
* @return {boolean} True if callbacks are enabled.
*/
isEnabled: function () {
return !!(ReactBrowserEventEmitter.ReactEventListener && ReactBrowserEventEmitter.ReactEventListener.isEnabled());
},
/**
* We listen for bubbled touch events on the document object.
*
* Firefox v8.01 (and possibly others) exhibited strange behavior when
* mounting `onmousemove` events at some node that was not the document
* element. The symptoms were that if your mouse is not moving over something
* contained within that mount point (for example on the background) the
* top-level listeners for `onmousemove` won't be called. However, if you
* register the `mousemove` on the document object, then it will of course
* catch all `mousemove`s. This along with iOS quirks, justifies restricting
* top-level listeners to the document object only, at least for these
* movement types of events and possibly all events.
*
* @see http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html
*
* Also, `keyup`/`keypress`/`keydown` do not bubble to the window on IE, but
* they bubble to document.
*
* @param {string} registrationName Name of listener (e.g. `onClick`).
* @param {object} contentDocumentHandle Document which owns the container
*/
listenTo: function (registrationName, contentDocumentHandle) {
var mountAt = contentDocumentHandle;
var isListening = getListeningForDocument(mountAt);
var dependencies = EventPluginRegistry.registrationNameDependencies[registrationName];
for (var i = 0; i < dependencies.length; i++) {
var dependency = dependencies[i];
if (!(isListening.hasOwnProperty(dependency) && isListening[dependency])) {
if (dependency === 'topWheel') {
if (isEventSupported('wheel')) {
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent('topWheel', 'wheel', mountAt);
} else if (isEventSupported('mousewheel')) {
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent('topWheel', 'mousewheel', mountAt);
} else {
// Firefox needs to capture a different mouse scroll event.
// @see http://www.quirksmode.org/dom/events/tests/scroll.html
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent('topWheel', 'DOMMouseScroll', mountAt);
}
} else if (dependency === 'topScroll') {
if (isEventSupported('scroll', true)) {
ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent('topScroll', 'scroll', mountAt);
} else {
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent('topScroll', 'scroll', ReactBrowserEventEmitter.ReactEventListener.WINDOW_HANDLE);
}
} else if (dependency === 'topFocus' || dependency === 'topBlur') {
if (isEventSupported('focus', true)) {
ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent('topFocus', 'focus', mountAt);
ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent('topBlur', 'blur', mountAt);
} else if (isEventSupported('focusin')) {
// IE has `focusin` and `focusout` events which bubble.
// @see http://www.quirksmode.org/blog/archives/2008/04/delegating_the.html
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent('topFocus', 'focusin', mountAt);
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent('topBlur', 'focusout', mountAt);
}
// to make sure blur and focus event listeners are only attached once
isListening.topBlur = true;
isListening.topFocus = true;
} else if (topEventMapping.hasOwnProperty(dependency)) {
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(dependency, topEventMapping[dependency], mountAt);
}
isListening[dependency] = true;
}
}
},
trapBubbledEvent: function (topLevelType, handlerBaseName, handle) {
return ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelType, handlerBaseName, handle);
},
trapCapturedEvent: function (topLevelType, handlerBaseName, handle) {
return ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelType, handlerBaseName, handle);
},
/**
* Protect against document.createEvent() returning null
* Some popup blocker extensions appear to do this:
* https://github.com/facebook/react/issues/6887
*/
supportsEventPageXY: function () {
if (!document.createEvent) {
return false;
}
var ev = document.createEvent('MouseEvent');
return ev != null && 'pageX' in ev;
},
/**
* Listens to window scroll and resize events. We cache scroll values so that
* application code can access them without triggering reflows.
*
* ViewportMetrics is only used by SyntheticMouse/TouchEvent and only when
* pageX/pageY isn't supported (legacy browsers).
*
* NOTE: Scroll events do not bubble.
*
* @see http://www.quirksmode.org/dom/events/scroll.html
*/
ensureScrollValueMonitoring: function () {
if (hasEventPageXY === undefined) {
hasEventPageXY = ReactBrowserEventEmitter.supportsEventPageXY();
}
if (!hasEventPageXY && !isMonitoringScrollValue) {
var refresh = ViewportMetrics.refreshScrollValues;
ReactBrowserEventEmitter.ReactEventListener.monitorScrollValue(refresh);
isMonitoringScrollValue = true;
}
}
});
module.exports = ReactBrowserEventEmitter;
},{"./EventPluginRegistry":51,"./ReactEventEmitterMixin":88,"./ViewportMetrics":130,"./getVendorPrefixedEventName":148,"./isEventSupported":150,"object-assign":28}],60:[function(require,module,exports){
(function (process){
/**
* Copyright 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var ReactReconciler = require('./ReactReconciler');
var instantiateReactComponent = require('./instantiateReactComponent');
var KeyEscapeUtils = require('./KeyEscapeUtils');
var shouldUpdateReactComponent = require('./shouldUpdateReactComponent');
var traverseAllChildren = require('./traverseAllChildren');
var warning = require('fbjs/lib/warning');
var ReactComponentTreeHook;
if (typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'test') {
// Temporary hack.
// Inline requires don't work well with Jest:
// https://github.com/facebook/react/issues/7240
// Remove the inline requires when we don't need them anymore:
// https://github.com/facebook/react/pull/7178
ReactComponentTreeHook = require('react/lib/ReactComponentTreeHook');
}
function instantiateChild(childInstances, child, name, selfDebugID) {
// We found a component instance.
var keyUnique = childInstances[name] === undefined;
if (process.env.NODE_ENV !== 'production') {
if (!ReactComponentTreeHook) {
ReactComponentTreeHook = require('react/lib/ReactComponentTreeHook');
}
if (!keyUnique) {
process.env.NODE_ENV !== 'production' ? warning(false, 'flattenChildren(...): Encountered two children with the same key, ' + '`%s`. Child keys must be unique; when two children share a key, only ' + 'the first child will be used.%s', KeyEscapeUtils.unescape(name), ReactComponentTreeHook.getStackAddendumByID(selfDebugID)) : void 0;
}
}
if (child != null && keyUnique) {
childInstances[name] = instantiateReactComponent(child, true);
}
}
/**
* ReactChildReconciler provides helpers for initializing or updating a set of
* children. Its output is suitable for passing it onto ReactMultiChild which
* does diffed reordering and insertion.
*/
var ReactChildReconciler = {
/**
* Generates a "mount image" for each of the supplied children. In the case
* of `ReactDOMComponent`, a mount image is a string of markup.
*
* @param {?object} nestedChildNodes Nested child maps.
* @return {?object} A set of child instances.
* @internal
*/
instantiateChildren: function (nestedChildNodes, transaction, context, selfDebugID // 0 in production and for roots
) {
if (nestedChildNodes == null) {
return null;
}
var childInstances = {};
if (process.env.NODE_ENV !== 'production') {
traverseAllChildren(nestedChildNodes, function (childInsts, child, name) {
return instantiateChild(childInsts, child, name, selfDebugID);
}, childInstances);
} else {
traverseAllChildren(nestedChildNodes, instantiateChild, childInstances);
}
return childInstances;
},
/**
* Updates the rendered children and returns a new set of children.
*
* @param {?object} prevChildren Previously initialized set of children.
* @param {?object} nextChildren Flat child element maps.
* @param {ReactReconcileTransaction} transaction
* @param {object} context
* @return {?object} A new set of child instances.
* @internal
*/
updateChildren: function (prevChildren, nextChildren, mountImages, removedNodes, transaction, hostParent, hostContainerInfo, context, selfDebugID // 0 in production and for roots
) {
// We currently don't have a way to track moves here but if we use iterators
// instead of for..in we can zip the iterators and check if an item has
// moved.
// TODO: If nothing has changed, return the prevChildren object so that we
// can quickly bailout if nothing has changed.
if (!nextChildren && !prevChildren) {
return;
}
var name;
var prevChild;
for (name in nextChildren) {
if (!nextChildren.hasOwnProperty(name)) {
continue;
}
prevChild = prevChildren && prevChildren[name];
var prevElement = prevChild && prevChild._currentElement;
var nextElement = nextChildren[name];
if (prevChild != null && shouldUpdateReactComponent(prevElement, nextElement)) {
ReactReconciler.receiveComponent(prevChild, nextElement, transaction, context);
nextChildren[name] = prevChild;
} else {
if (prevChild) {
removedNodes[name] = ReactReconciler.getHostNode(prevChild);
ReactReconciler.unmountComponent(prevChild, false);
}
// The child must be instantiated before it's mounted.
var nextChildInstance = instantiateReactComponent(nextElement, true);
nextChildren[name] = nextChildInstance;
// Creating mount image now ensures refs are resolved in right order
// (see https://github.com/facebook/react/pull/7101 for explanation).
var nextChildMountImage = ReactReconciler.mountComponent(nextChildInstance, transaction, hostParent, hostContainerInfo, context, selfDebugID);
mountImages.push(nextChildMountImage);
}
}
// Unmount children that are no longer present.
for (name in prevChildren) {
if (prevChildren.hasOwnProperty(name) && !(nextChildren && nextChildren.hasOwnProperty(name))) {
prevChild = prevChildren[name];
removedNodes[name] = ReactReconciler.getHostNode(prevChild);
ReactReconciler.unmountComponent(prevChild, false);
}
}
},
/**
* Unmounts all rendered children. This should be used to clean up children
* when this component is unmounted.
*
* @param {?object} renderedChildren Previously initialized set of children.
* @internal
*/
unmountChildren: function (renderedChildren, safely) {
for (var name in renderedChildren) {
if (renderedChildren.hasOwnProperty(name)) {
var renderedChild = renderedChildren[name];
ReactReconciler.unmountComponent(renderedChild, safely);
}
}
}
};
module.exports = ReactChildReconciler;
}).call(this,require('_process'))
},{"./KeyEscapeUtils":56,"./ReactReconciler":106,"./instantiateReactComponent":149,"./shouldUpdateReactComponent":157,"./traverseAllChildren":158,"_process":29,"fbjs/lib/warning":26,"react/lib/ReactComponentTreeHook":168}],61:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var DOMChildrenOperations = require('./DOMChildrenOperations');
var ReactDOMIDOperations = require('./ReactDOMIDOperations');
/**
* Abstracts away all functionality of the reconciler that requires knowledge of
* the browser context. TODO: These callers should be refactored to avoid the
* need for this injection.
*/
var ReactComponentBrowserEnvironment = {
processChildrenUpdates: ReactDOMIDOperations.dangerouslyProcessChildrenUpdates,
replaceNodeWithMarkup: DOMChildrenOperations.dangerouslyReplaceNodeWithMarkup
};
module.exports = ReactComponentBrowserEnvironment;
},{"./DOMChildrenOperations":42,"./ReactDOMIDOperations":71}],62:[function(require,module,exports){
(function (process){
/**
* Copyright 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
'use strict';
var _prodInvariant = require('./reactProdInvariant');
var invariant = require('fbjs/lib/invariant');
var injected = false;
var ReactComponentEnvironment = {
/**
* Optionally injectable hook for swapping out mount images in the middle of
* the tree.
*/
replaceNodeWithMarkup: null,
/**
* Optionally injectable hook for processing a queue of child updates. Will
* later move into MultiChildComponents.
*/
processChildrenUpdates: null,
injection: {
injectEnvironment: function (environment) {
!!injected ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactCompositeComponent: injectEnvironment() can only be called once.') : _prodInvariant('104') : void 0;
ReactComponentEnvironment.replaceNodeWithMarkup = environment.replaceNodeWithMarkup;
ReactComponentEnvironment.processChildrenUpdates = environment.processChildrenUpdates;
injected = true;
}
}
};
module.exports = ReactComponentEnvironment;
}).call(this,require('_process'))
},{"./reactProdInvariant":153,"_process":29,"fbjs/lib/invariant":19}],63:[function(require,module,exports){
(function (process){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var _prodInvariant = require('./reactProdInvariant'),
_assign = require('object-assign');
var React = require('react/lib/React');
var ReactComponentEnvironment = require('./ReactComponentEnvironment');
var ReactCurrentOwner = require('react/lib/ReactCurrentOwner');
var ReactErrorUtils = require('./ReactErrorUtils');
var ReactInstanceMap = require('./ReactInstanceMap');
var ReactInstrumentation = require('./ReactInstrumentation');
var ReactNodeTypes = require('./ReactNodeTypes');
var ReactReconciler = require('./ReactReconciler');
if (process.env.NODE_ENV !== 'production') {
var checkReactTypeSpec = require('./checkReactTypeSpec');
}
var emptyObject = require('fbjs/lib/emptyObject');
var invariant = require('fbjs/lib/invariant');
var shallowEqual = require('fbjs/lib/shallowEqual');
var shouldUpdateReactComponent = require('./shouldUpdateReactComponent');
var warning = require('fbjs/lib/warning');
var CompositeTypes = {
ImpureClass: 0,
PureClass: 1,
StatelessFunctional: 2
};
function StatelessComponent(Component) {}
StatelessComponent.prototype.render = function () {
var Component = ReactInstanceMap.get(this)._currentElement.type;
var element = Component(this.props, this.context, this.updater);
warnIfInvalidElement(Component, element);
return element;
};
function warnIfInvalidElement(Component, element) {
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(element === null || element === false || React.isValidElement(element), '%s(...): A valid React element (or null) must be returned. You may have ' + 'returned undefined, an array or some other invalid object.', Component.displayName || Component.name || 'Component') : void 0;
process.env.NODE_ENV !== 'production' ? warning(!Component.childContextTypes, '%s(...): childContextTypes cannot be defined on a functional component.', Component.displayName || Component.name || 'Component') : void 0;
}
}
function shouldConstruct(Component) {
return !!(Component.prototype && Component.prototype.isReactComponent);
}
function isPureComponent(Component) {
return !!(Component.prototype && Component.prototype.isPureReactComponent);
}
// Separated into a function to contain deoptimizations caused by try/finally.
function measureLifeCyclePerf(fn, debugID, timerType) {
if (debugID === 0) {
// Top-level wrappers (see ReactMount) and empty components (see
// ReactDOMEmptyComponent) are invisible to hooks and devtools.
// Both are implementation details that should go away in the future.
return fn();
}
ReactInstrumentation.debugTool.onBeginLifeCycleTimer(debugID, timerType);
try {
return fn();
} finally {
ReactInstrumentation.debugTool.onEndLifeCycleTimer(debugID, timerType);
}
}
/**
* ------------------ The Life-Cycle of a Composite Component ------------------
*
* - constructor: Initialization of state. The instance is now retained.
* - componentWillMount
* - render
* - [children's constructors]
* - [children's componentWillMount and render]
* - [children's componentDidMount]
* - componentDidMount
*
* Update Phases:
* - componentWillReceiveProps (only called if parent updated)
* - shouldComponentUpdate
* - componentWillUpdate
* - render
* - [children's constructors or receive props phases]
* - componentDidUpdate
*
* - componentWillUnmount
* - [children's componentWillUnmount]
* - [children destroyed]
* - (destroyed): The instance is now blank, released by React and ready for GC.
*
* -----------------------------------------------------------------------------
*/
/**
* An incrementing ID assigned to each component when it is mounted. This is
* used to enforce the order in which `ReactUpdates` updates dirty components.
*
* @private
*/
var nextMountID = 1;
/**
* @lends {ReactCompositeComponent.prototype}
*/
var ReactCompositeComponent = {
/**
* Base constructor for all composite component.
*
* @param {ReactElement} element
* @final
* @internal
*/
construct: function (element) {
this._currentElement = element;
this._rootNodeID = 0;
this._compositeType = null;
this._instance = null;
this._hostParent = null;
this._hostContainerInfo = null;
// See ReactUpdateQueue
this._updateBatchNumber = null;
this._pendingElement = null;
this._pendingStateQueue = null;
this._pendingReplaceState = false;
this._pendingForceUpdate = false;
this._renderedNodeType = null;
this._renderedComponent = null;
this._context = null;
this._mountOrder = 0;
this._topLevelWrapper = null;
// See ReactUpdates and ReactUpdateQueue.
this._pendingCallbacks = null;
// ComponentWillUnmount shall only be called once
this._calledComponentWillUnmount = false;
if (process.env.NODE_ENV !== 'production') {
this._warnedAboutRefsInRender = false;
}
},
/**
* Initializes the component, renders markup, and registers event listeners.
*
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @param {?object} hostParent
* @param {?object} hostContainerInfo
* @param {?object} context
* @return {?string} Rendered markup to be inserted into the DOM.
* @final
* @internal
*/
mountComponent: function (transaction, hostParent, hostContainerInfo, context) {
var _this = this;
this._context = context;
this._mountOrder = nextMountID++;
this._hostParent = hostParent;
this._hostContainerInfo = hostContainerInfo;
var publicProps = this._currentElement.props;
var publicContext = this._processContext(context);
var Component = this._currentElement.type;
var updateQueue = transaction.getUpdateQueue();
// Initialize the public class
var doConstruct = shouldConstruct(Component);
var inst = this._constructComponent(doConstruct, publicProps, publicContext, updateQueue);
var renderedElement;
// Support functional components
if (!doConstruct && (inst == null || inst.render == null)) {
renderedElement = inst;
warnIfInvalidElement(Component, renderedElement);
!(inst === null || inst === false || React.isValidElement(inst)) ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s(...): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.', Component.displayName || Component.name || 'Component') : _prodInvariant('105', Component.displayName || Component.name || 'Component') : void 0;
inst = new StatelessComponent(Component);
this._compositeType = CompositeTypes.StatelessFunctional;
} else {
if (isPureComponent(Component)) {
this._compositeType = CompositeTypes.PureClass;
} else {
this._compositeType = CompositeTypes.ImpureClass;
}
}
if (process.env.NODE_ENV !== 'production') {
// This will throw later in _renderValidatedComponent, but add an early
// warning now to help debugging
if (inst.render == null) {
process.env.NODE_ENV !== 'production' ? warning(false, '%s(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render`.', Component.displayName || Component.name || 'Component') : void 0;
}
var propsMutated = inst.props !== publicProps;
var componentName = Component.displayName || Component.name || 'Component';
process.env.NODE_ENV !== 'production' ? warning(inst.props === undefined || !propsMutated, '%s(...): When calling super() in `%s`, make sure to pass ' + 'up the same props that your component\'s constructor was passed.', componentName, componentName) : void 0;
}
// These should be set up in the constructor, but as a convenience for
// simpler class abstractions, we set them up after the fact.
inst.props = publicProps;
inst.context = publicContext;
inst.refs = emptyObject;
inst.updater = updateQueue;
this._instance = inst;
// Store a reference from the instance back to the internal representation
ReactInstanceMap.set(inst, this);
if (process.env.NODE_ENV !== 'production') {
// Since plain JS classes are defined without any special initialization
// logic, we can not catch common errors early. Therefore, we have to
// catch them here, at initialization time, instead.
process.env.NODE_ENV !== 'production' ? warning(!inst.getInitialState || inst.getInitialState.isReactClassApproved || inst.state, 'getInitialState was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Did you mean to define a state property instead?', this.getName() || 'a component') : void 0;
process.env.NODE_ENV !== 'production' ? warning(!inst.getDefaultProps || inst.getDefaultProps.isReactClassApproved, 'getDefaultProps was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Use a static property to define defaultProps instead.', this.getName() || 'a component') : void 0;
process.env.NODE_ENV !== 'production' ? warning(!inst.propTypes, 'propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', this.getName() || 'a component') : void 0;
process.env.NODE_ENV !== 'production' ? warning(!inst.contextTypes, 'contextTypes was defined as an instance property on %s. Use a ' + 'static property to define contextTypes instead.', this.getName() || 'a component') : void 0;
process.env.NODE_ENV !== 'production' ? warning(typeof inst.componentShouldUpdate !== 'function', '%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', this.getName() || 'A component') : void 0;
process.env.NODE_ENV !== 'production' ? warning(typeof inst.componentDidUnmount !== 'function', '%s has a method called ' + 'componentDidUnmount(). But there is no such lifecycle method. ' + 'Did you mean componentWillUnmount()?', this.getName() || 'A component') : void 0;
process.env.NODE_ENV !== 'production' ? warning(typeof inst.componentWillRecieveProps !== 'function', '%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', this.getName() || 'A component') : void 0;
}
var initialState = inst.state;
if (initialState === undefined) {
inst.state = initialState = null;
}
!(typeof initialState === 'object' && !Array.isArray(initialState)) ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s.state: must be set to an object or null', this.getName() || 'ReactCompositeComponent') : _prodInvariant('106', this.getName() || 'ReactCompositeComponent') : void 0;
this._pendingStateQueue = null;
this._pendingReplaceState = false;
this._pendingForceUpdate = false;
var markup;
if (inst.unstable_handleError) {
markup = this.performInitialMountWithErrorHandling(renderedElement, hostParent, hostContainerInfo, transaction, context);
} else {
markup = this.performInitialMount(renderedElement, hostParent, hostContainerInfo, transaction, context);
}
if (inst.componentDidMount) {
if (process.env.NODE_ENV !== 'production') {
transaction.getReactMountReady().enqueue(function () {
measureLifeCyclePerf(function () {
return inst.componentDidMount();
}, _this._debugID, 'componentDidMount');
});
} else {
transaction.getReactMountReady().enqueue(inst.componentDidMount, inst);
}
}
return markup;
},
_constructComponent: function (doConstruct, publicProps, publicContext, updateQueue) {
if (process.env.NODE_ENV !== 'production') {
ReactCurrentOwner.current = this;
try {
return this._constructComponentWithoutOwner(doConstruct, publicProps, publicContext, updateQueue);
} finally {
ReactCurrentOwner.current = null;
}
} else {
return this._constructComponentWithoutOwner(doConstruct, publicProps, publicContext, updateQueue);
}
},
_constructComponentWithoutOwner: function (doConstruct, publicProps, publicContext, updateQueue) {
var Component = this._currentElement.type;
if (doConstruct) {
if (process.env.NODE_ENV !== 'production') {
return measureLifeCyclePerf(function () {
return new Component(publicProps, publicContext, updateQueue);
}, this._debugID, 'ctor');
} else {
return new Component(publicProps, publicContext, updateQueue);
}
}
// This can still be an instance in case of factory components
// but we'll count this as time spent rendering as the more common case.
if (process.env.NODE_ENV !== 'production') {
return measureLifeCyclePerf(function () {
return Component(publicProps, publicContext, updateQueue);
}, this._debugID, 'render');
} else {
return Component(publicProps, publicContext, updateQueue);
}
},
performInitialMountWithErrorHandling: function (renderedElement, hostParent, hostContainerInfo, transaction, context) {
var markup;
var checkpoint = transaction.checkpoint();
try {
markup = this.performInitialMount(renderedElement, hostParent, hostContainerInfo, transaction, context);
} catch (e) {
// Roll back to checkpoint, handle error (which may add items to the transaction), and take a new checkpoint
transaction.rollback(checkpoint);
this._instance.unstable_handleError(e);
if (this._pendingStateQueue) {
this._instance.state = this._processPendingState(this._instance.props, this._instance.context);
}
checkpoint = transaction.checkpoint();
this._renderedComponent.unmountComponent(true);
transaction.rollback(checkpoint);
// Try again - we've informed the component about the error, so they can render an error message this time.
// If this throws again, the error will bubble up (and can be caught by a higher error boundary).
markup = this.performInitialMount(renderedElement, hostParent, hostContainerInfo, transaction, context);
}
return markup;
},
performInitialMount: function (renderedElement, hostParent, hostContainerInfo, transaction, context) {
var inst = this._instance;
var debugID = 0;
if (process.env.NODE_ENV !== 'production') {
debugID = this._debugID;
}
if (inst.componentWillMount) {
if (process.env.NODE_ENV !== 'production') {
measureLifeCyclePerf(function () {
return inst.componentWillMount();
}, debugID, 'componentWillMount');
} else {
inst.componentWillMount();
}
// When mounting, calls to `setState` by `componentWillMount` will set
// `this._pendingStateQueue` without triggering a re-render.
if (this._pendingStateQueue) {
inst.state = this._processPendingState(inst.props, inst.context);
}
}
// If not a stateless component, we now render
if (renderedElement === undefined) {
renderedElement = this._renderValidatedComponent();
}
var nodeType = ReactNodeTypes.getType(renderedElement);
this._renderedNodeType = nodeType;
var child = this._instantiateReactComponent(renderedElement, nodeType !== ReactNodeTypes.EMPTY /* shouldHaveDebugID */
);
this._renderedComponent = child;
var markup = ReactReconciler.mountComponent(child, transaction, hostParent, hostContainerInfo, this._processChildContext(context), debugID);
if (process.env.NODE_ENV !== 'production') {
if (debugID !== 0) {
var childDebugIDs = child._debugID !== 0 ? [child._debugID] : [];
ReactInstrumentation.debugTool.onSetChildren(debugID, childDebugIDs);
}
}
return markup;
},
getHostNode: function () {
return ReactReconciler.getHostNode(this._renderedComponent);
},
/**
* Releases any resources allocated by `mountComponent`.
*
* @final
* @internal
*/
unmountComponent: function (safely) {
if (!this._renderedComponent) {
return;
}
var inst = this._instance;
if (inst.componentWillUnmount && !inst._calledComponentWillUnmount) {
inst._calledComponentWillUnmount = true;
if (safely) {
var name = this.getName() + '.componentWillUnmount()';
ReactErrorUtils.invokeGuardedCallback(name, inst.componentWillUnmount.bind(inst));
} else {
if (process.env.NODE_ENV !== 'production') {
measureLifeCyclePerf(function () {
return inst.componentWillUnmount();
}, this._debugID, 'componentWillUnmount');
} else {
inst.componentWillUnmount();
}
}
}
if (this._renderedComponent) {
ReactReconciler.unmountComponent(this._renderedComponent, safely);
this._renderedNodeType = null;
this._renderedComponent = null;
this._instance = null;
}
// Reset pending fields
// Even if this component is scheduled for another update in ReactUpdates,
// it would still be ignored because these fields are reset.
this._pendingStateQueue = null;
this._pendingReplaceState = false;
this._pendingForceUpdate = false;
this._pendingCallbacks = null;
this._pendingElement = null;
// These fields do not really need to be reset since this object is no
// longer accessible.
this._context = null;
this._rootNodeID = 0;
this._topLevelWrapper = null;
// Delete the reference from the instance to this internal representation
// which allow the internals to be properly cleaned up even if the user
// leaks a reference to the public instance.
ReactInstanceMap.remove(inst);
// Some existing components rely on inst.props even after they've been
// destroyed (in event handlers).
// TODO: inst.props = null;
// TODO: inst.state = null;
// TODO: inst.context = null;
},
/**
* Filters the context object to only contain keys specified in
* `contextTypes`
*
* @param {object} context
* @return {?object}
* @private
*/
_maskContext: function (context) {
var Component = this._currentElement.type;
var contextTypes = Component.contextTypes;
if (!contextTypes) {
return emptyObject;
}
var maskedContext = {};
for (var contextName in contextTypes) {
maskedContext[contextName] = context[contextName];
}
return maskedContext;
},
/**
* Filters the context object to only contain keys specified in
* `contextTypes`, and asserts that they are valid.
*
* @param {object} context
* @return {?object}
* @private
*/
_processContext: function (context) {
var maskedContext = this._maskContext(context);
if (process.env.NODE_ENV !== 'production') {
var Component = this._currentElement.type;
if (Component.contextTypes) {
this._checkContextTypes(Component.contextTypes, maskedContext, 'context');
}
}
return maskedContext;
},
/**
* @param {object} currentContext
* @return {object}
* @private
*/
_processChildContext: function (currentContext) {
var Component = this._currentElement.type;
var inst = this._instance;
var childContext;
if (inst.getChildContext) {
if (process.env.NODE_ENV !== 'production') {
ReactInstrumentation.debugTool.onBeginProcessingChildContext();
try {
childContext = inst.getChildContext();
} finally {
ReactInstrumentation.debugTool.onEndProcessingChildContext();
}
} else {
childContext = inst.getChildContext();
}
}
if (childContext) {
!(typeof Component.childContextTypes === 'object') ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s.getChildContext(): childContextTypes must be defined in order to use getChildContext().', this.getName() || 'ReactCompositeComponent') : _prodInvariant('107', this.getName() || 'ReactCompositeComponent') : void 0;
if (process.env.NODE_ENV !== 'production') {
this._checkContextTypes(Component.childContextTypes, childContext, 'child context');
}
for (var name in childContext) {
!(name in Component.childContextTypes) ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s.getChildContext(): key "%s" is not defined in childContextTypes.', this.getName() || 'ReactCompositeComponent', name) : _prodInvariant('108', this.getName() || 'ReactCompositeComponent', name) : void 0;
}
return _assign({}, currentContext, childContext);
}
return currentContext;
},
/**
* Assert that the context types are valid
*
* @param {object} typeSpecs Map of context field to a ReactPropType
* @param {object} values Runtime values that need to be type-checked
* @param {string} location e.g. "prop", "context", "child context"
* @private
*/
_checkContextTypes: function (typeSpecs, values, location) {
if (process.env.NODE_ENV !== 'production') {
checkReactTypeSpec(typeSpecs, values, location, this.getName(), null, this._debugID);
}
},
receiveComponent: function (nextElement, transaction, nextContext) {
var prevElement = this._currentElement;
var prevContext = this._context;
this._pendingElement = null;
this.updateComponent(transaction, prevElement, nextElement, prevContext, nextContext);
},
/**
* If any of `_pendingElement`, `_pendingStateQueue`, or `_pendingForceUpdate`
* is set, update the component.
*
* @param {ReactReconcileTransaction} transaction
* @internal
*/
performUpdateIfNecessary: function (transaction) {
if (this._pendingElement != null) {
ReactReconciler.receiveComponent(this, this._pendingElement, transaction, this._context);
} else if (this._pendingStateQueue !== null || this._pendingForceUpdate) {
this.updateComponent(transaction, this._currentElement, this._currentElement, this._context, this._context);
} else {
this._updateBatchNumber = null;
}
},
/**
* Perform an update to a mounted component. The componentWillReceiveProps and
* shouldComponentUpdate methods are called, then (assuming the update isn't
* skipped) the remaining update lifecycle methods are called and the DOM
* representation is updated.
*
* By default, this implements React's rendering and reconciliation algorithm.
* Sophisticated clients may wish to override this.
*
* @param {ReactReconcileTransaction} transaction
* @param {ReactElement} prevParentElement
* @param {ReactElement} nextParentElement
* @internal
* @overridable
*/
updateComponent: function (transaction, prevParentElement, nextParentElement, prevUnmaskedContext, nextUnmaskedContext) {
var inst = this._instance;
!(inst != null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Attempted to update component `%s` that has already been unmounted (or failed to mount).', this.getName() || 'ReactCompositeComponent') : _prodInvariant('136', this.getName() || 'ReactCompositeComponent') : void 0;
var willReceive = false;
var nextContext;
// Determine if the context has changed or not
if (this._context === nextUnmaskedContext) {
nextContext = inst.context;
} else {
nextContext = this._processContext(nextUnmaskedContext);
willReceive = true;
}
var prevProps = prevParentElement.props;
var nextProps = nextParentElement.props;
// Not a simple state update but a props update
if (prevParentElement !== nextParentElement) {
willReceive = true;
}
// An update here will schedule an update but immediately set
// _pendingStateQueue which will ensure that any state updates gets
// immediately reconciled instead of waiting for the next batch.
if (willReceive && inst.componentWillReceiveProps) {
if (process.env.NODE_ENV !== 'production') {
measureLifeCyclePerf(function () {
return inst.componentWillReceiveProps(nextProps, nextContext);
}, this._debugID, 'componentWillReceiveProps');
} else {
inst.componentWillReceiveProps(nextProps, nextContext);
}
}
var nextState = this._processPendingState(nextProps, nextContext);
var shouldUpdate = true;
if (!this._pendingForceUpdate) {
if (inst.shouldComponentUpdate) {
if (process.env.NODE_ENV !== 'production') {
shouldUpdate = measureLifeCyclePerf(function () {
return inst.shouldComponentUpdate(nextProps, nextState, nextContext);
}, this._debugID, 'shouldComponentUpdate');
} else {
shouldUpdate = inst.shouldComponentUpdate(nextProps, nextState, nextContext);
}
} else {
if (this._compositeType === CompositeTypes.PureClass) {
shouldUpdate = !shallowEqual(prevProps, nextProps) || !shallowEqual(inst.state, nextState);
}
}
}
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(shouldUpdate !== undefined, '%s.shouldComponentUpdate(): Returned undefined instead of a ' + 'boolean value. Make sure to return true or false.', this.getName() || 'ReactCompositeComponent') : void 0;
}
this._updateBatchNumber = null;
if (shouldUpdate) {
this._pendingForceUpdate = false;
// Will set `this.props`, `this.state` and `this.context`.
this._performComponentUpdate(nextParentElement, nextProps, nextState, nextContext, transaction, nextUnmaskedContext);
} else {
// If it's determined that a component should not update, we still want
// to set props and state but we shortcut the rest of the update.
this._currentElement = nextParentElement;
this._context = nextUnmaskedContext;
inst.props = nextProps;
inst.state = nextState;
inst.context = nextContext;
}
},
_processPendingState: function (props, context) {
var inst = this._instance;
var queue = this._pendingStateQueue;
var replace = this._pendingReplaceState;
this._pendingReplaceState = false;
this._pendingStateQueue = null;
if (!queue) {
return inst.state;
}
if (replace && queue.length === 1) {
return queue[0];
}
var nextState = _assign({}, replace ? queue[0] : inst.state);
for (var i = replace ? 1 : 0; i < queue.length; i++) {
var partial = queue[i];
_assign(nextState, typeof partial === 'function' ? partial.call(inst, nextState, props, context) : partial);
}
return nextState;
},
/**
* Merges new props and state, notifies delegate methods of update and
* performs update.
*
* @param {ReactElement} nextElement Next element
* @param {object} nextProps Next public object to set as properties.
* @param {?object} nextState Next object to set as state.
* @param {?object} nextContext Next public object to set as context.
* @param {ReactReconcileTransaction} transaction
* @param {?object} unmaskedContext
* @private
*/
_performComponentUpdate: function (nextElement, nextProps, nextState, nextContext, transaction, unmaskedContext) {
var _this2 = this;
var inst = this._instance;
var hasComponentDidUpdate = Boolean(inst.componentDidUpdate);
var prevProps;
var prevState;
var prevContext;
if (hasComponentDidUpdate) {
prevProps = inst.props;
prevState = inst.state;
prevContext = inst.context;
}
if (inst.componentWillUpdate) {
if (process.env.NODE_ENV !== 'production') {
measureLifeCyclePerf(function () {
return inst.componentWillUpdate(nextProps, nextState, nextContext);
}, this._debugID, 'componentWillUpdate');
} else {
inst.componentWillUpdate(nextProps, nextState, nextContext);
}
}
this._currentElement = nextElement;
this._context = unmaskedContext;
inst.props = nextProps;
inst.state = nextState;
inst.context = nextContext;
this._updateRenderedComponent(transaction, unmaskedContext);
if (hasComponentDidUpdate) {
if (process.env.NODE_ENV !== 'production') {
transaction.getReactMountReady().enqueue(function () {
measureLifeCyclePerf(inst.componentDidUpdate.bind(inst, prevProps, prevState, prevContext), _this2._debugID, 'componentDidUpdate');
});
} else {
transaction.getReactMountReady().enqueue(inst.componentDidUpdate.bind(inst, prevProps, prevState, prevContext), inst);
}
}
},
/**
* Call the component's `render` method and update the DOM accordingly.
*
* @param {ReactReconcileTransaction} transaction
* @internal
*/
_updateRenderedComponent: function (transaction, context) {
var prevComponentInstance = this._renderedComponent;
var prevRenderedElement = prevComponentInstance._currentElement;
var nextRenderedElement = this._renderValidatedComponent();
var debugID = 0;
if (process.env.NODE_ENV !== 'production') {
debugID = this._debugID;
}
if (shouldUpdateReactComponent(prevRenderedElement, nextRenderedElement)) {
ReactReconciler.receiveComponent(prevComponentInstance, nextRenderedElement, transaction, this._processChildContext(context));
} else {
var oldHostNode = ReactReconciler.getHostNode(prevComponentInstance);
ReactReconciler.unmountComponent(prevComponentInstance, false);
var nodeType = ReactNodeTypes.getType(nextRenderedElement);
this._renderedNodeType = nodeType;
var child = this._instantiateReactComponent(nextRenderedElement, nodeType !== ReactNodeTypes.EMPTY /* shouldHaveDebugID */
);
this._renderedComponent = child;
var nextMarkup = ReactReconciler.mountComponent(child, transaction, this._hostParent, this._hostContainerInfo, this._processChildContext(context), debugID);
if (process.env.NODE_ENV !== 'production') {
if (debugID !== 0) {
var childDebugIDs = child._debugID !== 0 ? [child._debugID] : [];
ReactInstrumentation.debugTool.onSetChildren(debugID, childDebugIDs);
}
}
this._replaceNodeWithMarkup(oldHostNode, nextMarkup, prevComponentInstance);
}
},
/**
* Overridden in shallow rendering.
*
* @protected
*/
_replaceNodeWithMarkup: function (oldHostNode, nextMarkup, prevInstance) {
ReactComponentEnvironment.replaceNodeWithMarkup(oldHostNode, nextMarkup, prevInstance);
},
/**
* @protected
*/
_renderValidatedComponentWithoutOwnerOrContext: function () {
var inst = this._instance;
var renderedElement;
if (process.env.NODE_ENV !== 'production') {
renderedElement = measureLifeCyclePerf(function () {
return inst.render();
}, this._debugID, 'render');
} else {
renderedElement = inst.render();
}
if (process.env.NODE_ENV !== 'production') {
// We allow auto-mocks to proceed as if they're returning null.
if (renderedElement === undefined && inst.render._isMockFunction) {
// This is probably bad practice. Consider warning here and
// deprecating this convenience.
renderedElement = null;
}
}
return renderedElement;
},
/**
* @private
*/
_renderValidatedComponent: function () {
var renderedElement;
if (process.env.NODE_ENV !== 'production' || this._compositeType !== CompositeTypes.StatelessFunctional) {
ReactCurrentOwner.current = this;
try {
renderedElement = this._renderValidatedComponentWithoutOwnerOrContext();
} finally {
ReactCurrentOwner.current = null;
}
} else {
renderedElement = this._renderValidatedComponentWithoutOwnerOrContext();
}
!(
// TODO: An `isValidNode` function would probably be more appropriate
renderedElement === null || renderedElement === false || React.isValidElement(renderedElement)) ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s.render(): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.', this.getName() || 'ReactCompositeComponent') : _prodInvariant('109', this.getName() || 'ReactCompositeComponent') : void 0;
return renderedElement;
},
/**
* Lazily allocates the refs object and stores `component` as `ref`.
*
* @param {string} ref Reference name.
* @param {component} component Component to store as `ref`.
* @final
* @private
*/
attachRef: function (ref, component) {
var inst = this.getPublicInstance();
!(inst != null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Stateless function components cannot have refs.') : _prodInvariant('110') : void 0;
var publicComponentInstance = component.getPublicInstance();
if (process.env.NODE_ENV !== 'production') {
var componentName = component && component.getName ? component.getName() : 'a component';
process.env.NODE_ENV !== 'production' ? warning(publicComponentInstance != null || component._compositeType !== CompositeTypes.StatelessFunctional, 'Stateless function components cannot be given refs ' + '(See ref "%s" in %s created by %s). ' + 'Attempts to access this ref will fail.', ref, componentName, this.getName()) : void 0;
}
var refs = inst.refs === emptyObject ? inst.refs = {} : inst.refs;
refs[ref] = publicComponentInstance;
},
/**
* Detaches a reference name.
*
* @param {string} ref Name to dereference.
* @final
* @private
*/
detachRef: function (ref) {
var refs = this.getPublicInstance().refs;
delete refs[ref];
},
/**
* Get a text description of the component that can be used to identify it
* in error messages.
* @return {string} The name or null.
* @internal
*/
getName: function () {
var type = this._currentElement.type;
var constructor = this._instance && this._instance.constructor;
return type.displayName || constructor && constructor.displayName || type.name || constructor && constructor.name || null;
},
/**
* Get the publicly accessible representation of this component - i.e. what
* is exposed by refs and returned by render. Can be null for stateless
* components.
*
* @return {ReactComponent} the public component instance.
* @internal
*/
getPublicInstance: function () {
var inst = this._instance;
if (this._compositeType === CompositeTypes.StatelessFunctional) {
return null;
}
return inst;
},
// Stub
_instantiateReactComponent: null
};
module.exports = ReactCompositeComponent;
}).call(this,require('_process'))
},{"./ReactComponentEnvironment":62,"./ReactErrorUtils":87,"./ReactInstanceMap":95,"./ReactInstrumentation":96,"./ReactNodeTypes":101,"./ReactReconciler":106,"./checkReactTypeSpec":133,"./reactProdInvariant":153,"./shouldUpdateReactComponent":157,"_process":29,"fbjs/lib/emptyObject":12,"fbjs/lib/invariant":19,"fbjs/lib/shallowEqual":25,"fbjs/lib/warning":26,"object-assign":28,"react/lib/React":165,"react/lib/ReactCurrentOwner":169}],64:[function(require,module,exports){
(function (process){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
/* globals __REACT_DEVTOOLS_GLOBAL_HOOK__*/
'use strict';
var ReactDOMComponentTree = require('./ReactDOMComponentTree');
var ReactDefaultInjection = require('./ReactDefaultInjection');
var ReactMount = require('./ReactMount');
var ReactReconciler = require('./ReactReconciler');
var ReactUpdates = require('./ReactUpdates');
var ReactVersion = require('./ReactVersion');
var findDOMNode = require('./findDOMNode');
var getHostComponentFromComposite = require('./getHostComponentFromComposite');
var renderSubtreeIntoContainer = require('./renderSubtreeIntoContainer');
var warning = require('fbjs/lib/warning');
ReactDefaultInjection.inject();
var ReactDOM = {
findDOMNode: findDOMNode,
render: ReactMount.render,
unmountComponentAtNode: ReactMount.unmountComponentAtNode,
version: ReactVersion,
/* eslint-disable camelcase */
unstable_batchedUpdates: ReactUpdates.batchedUpdates,
unstable_renderSubtreeIntoContainer: renderSubtreeIntoContainer
};
// Inject the runtime into a devtools global hook regardless of browser.
// Allows for debugging when the hook is injected on the page.
if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.inject === 'function') {
__REACT_DEVTOOLS_GLOBAL_HOOK__.inject({
ComponentTree: {
getClosestInstanceFromNode: ReactDOMComponentTree.getClosestInstanceFromNode,
getNodeFromInstance: function (inst) {
// inst is an internal instance (but could be a composite)
if (inst._renderedComponent) {
inst = getHostComponentFromComposite(inst);
}
if (inst) {
return ReactDOMComponentTree.getNodeFromInstance(inst);
} else {
return null;
}
}
},
Mount: ReactMount,
Reconciler: ReactReconciler
});
}
if (process.env.NODE_ENV !== 'production') {
var ExecutionEnvironment = require('fbjs/lib/ExecutionEnvironment');
if (ExecutionEnvironment.canUseDOM && window.top === window.self) {
// First check if devtools is not installed
if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') {
// If we're in Chrome or Firefox, provide a download link if not installed.
if (navigator.userAgent.indexOf('Chrome') > -1 && navigator.userAgent.indexOf('Edge') === -1 || navigator.userAgent.indexOf('Firefox') > -1) {
// Firefox does not have the issue with devtools loaded over file://
var showFileUrlMessage = window.location.protocol.indexOf('http') === -1 && navigator.userAgent.indexOf('Firefox') === -1;
console.debug('Download the React DevTools ' + (showFileUrlMessage ? 'and use an HTTP server (instead of a file: URL) ' : '') + 'for a better development experience: ' + 'https://fb.me/react-devtools');
}
}
var testFunc = function testFn() {};
process.env.NODE_ENV !== 'production' ? warning((testFunc.name || testFunc.toString()).indexOf('testFn') !== -1, 'It looks like you\'re using a minified copy of the development build ' + 'of React. When deploying React apps to production, make sure to use ' + 'the production build which skips development warnings and is faster. ' + 'See https://fb.me/react-minification for more details.') : void 0;
// If we're in IE8, check to see if we are in compatibility mode and provide
// information on preventing compatibility mode
var ieCompatibilityMode = document.documentMode && document.documentMode < 8;
process.env.NODE_ENV !== 'production' ? warning(!ieCompatibilityMode, 'Internet Explorer is running in compatibility mode; please add the ' + 'following tag to your HTML to prevent this from happening: ' + '<meta http-equiv="X-UA-Compatible" content="IE=edge" />') : void 0;
var expectedFeatures = [
// shims
Array.isArray, Array.prototype.every, Array.prototype.forEach, Array.prototype.indexOf, Array.prototype.map, Date.now, Function.prototype.bind, Object.keys, String.prototype.trim];
for (var i = 0; i < expectedFeatures.length; i++) {
if (!expectedFeatures[i]) {
process.env.NODE_ENV !== 'production' ? warning(false, 'One or more ES5 shims expected by React are not available: ' + 'https://fb.me/react-warning-polyfills') : void 0;
break;
}
}
}
}
if (process.env.NODE_ENV !== 'production') {
var ReactInstrumentation = require('./ReactInstrumentation');
var ReactDOMUnknownPropertyHook = require('./ReactDOMUnknownPropertyHook');
var ReactDOMNullInputValuePropHook = require('./ReactDOMNullInputValuePropHook');
var ReactDOMInvalidARIAHook = require('./ReactDOMInvalidARIAHook');
ReactInstrumentation.debugTool.addHook(ReactDOMUnknownPropertyHook);
ReactInstrumentation.debugTool.addHook(ReactDOMNullInputValuePropHook);
ReactInstrumentation.debugTool.addHook(ReactDOMInvalidARIAHook);
}
module.exports = ReactDOM;
}).call(this,require('_process'))
},{"./ReactDOMComponentTree":67,"./ReactDOMInvalidARIAHook":73,"./ReactDOMNullInputValuePropHook":74,"./ReactDOMUnknownPropertyHook":81,"./ReactDefaultInjection":84,"./ReactInstrumentation":96,"./ReactMount":99,"./ReactReconciler":106,"./ReactUpdates":111,"./ReactVersion":112,"./findDOMNode":137,"./getHostComponentFromComposite":144,"./renderSubtreeIntoContainer":154,"_process":29,"fbjs/lib/ExecutionEnvironment":5,"fbjs/lib/warning":26}],65:[function(require,module,exports){
(function (process){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
/* global hasOwnProperty:true */
'use strict';
var _prodInvariant = require('./reactProdInvariant'),
_assign = require('object-assign');
var AutoFocusUtils = require('./AutoFocusUtils');
var CSSPropertyOperations = require('./CSSPropertyOperations');
var DOMLazyTree = require('./DOMLazyTree');
var DOMNamespaces = require('./DOMNamespaces');
var DOMProperty = require('./DOMProperty');
var DOMPropertyOperations = require('./DOMPropertyOperations');
var EventPluginHub = require('./EventPluginHub');
var EventPluginRegistry = require('./EventPluginRegistry');
var ReactBrowserEventEmitter = require('./ReactBrowserEventEmitter');
var ReactDOMComponentFlags = require('./ReactDOMComponentFlags');
var ReactDOMComponentTree = require('./ReactDOMComponentTree');
var ReactDOMInput = require('./ReactDOMInput');
var ReactDOMOption = require('./ReactDOMOption');
var ReactDOMSelect = require('./ReactDOMSelect');
var ReactDOMTextarea = require('./ReactDOMTextarea');
var ReactInstrumentation = require('./ReactInstrumentation');
var ReactMultiChild = require('./ReactMultiChild');
var ReactServerRenderingTransaction = require('./ReactServerRenderingTransaction');
var emptyFunction = require('fbjs/lib/emptyFunction');
var escapeTextContentForBrowser = require('./escapeTextContentForBrowser');
var invariant = require('fbjs/lib/invariant');
var isEventSupported = require('./isEventSupported');
var shallowEqual = require('fbjs/lib/shallowEqual');
var validateDOMNesting = require('./validateDOMNesting');
var warning = require('fbjs/lib/warning');
var Flags = ReactDOMComponentFlags;
var deleteListener = EventPluginHub.deleteListener;
var getNode = ReactDOMComponentTree.getNodeFromInstance;
var listenTo = ReactBrowserEventEmitter.listenTo;
var registrationNameModules = EventPluginRegistry.registrationNameModules;
// For quickly matching children type, to test if can be treated as content.
var CONTENT_TYPES = { 'string': true, 'number': true };
var STYLE = 'style';
var HTML = '__html';
var RESERVED_PROPS = {
children: null,
dangerouslySetInnerHTML: null,
suppressContentEditableWarning: null
};
// Node type for document fragments (Node.DOCUMENT_FRAGMENT_NODE).
var DOC_FRAGMENT_TYPE = 11;
function getDeclarationErrorAddendum(internalInstance) {
if (internalInstance) {
var owner = internalInstance._currentElement._owner || null;
if (owner) {
var name = owner.getName();
if (name) {
return ' This DOM node was rendered by `' + name + '`.';
}
}
}
return '';
}
function friendlyStringify(obj) {
if (typeof obj === 'object') {
if (Array.isArray(obj)) {
return '[' + obj.map(friendlyStringify).join(', ') + ']';
} else {
var pairs = [];
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
var keyEscaped = /^[a-z$_][\w$_]*$/i.test(key) ? key : JSON.stringify(key);
pairs.push(keyEscaped + ': ' + friendlyStringify(obj[key]));
}
}
return '{' + pairs.join(', ') + '}';
}
} else if (typeof obj === 'string') {
return JSON.stringify(obj);
} else if (typeof obj === 'function') {
return '[function object]';
}
// Differs from JSON.stringify in that undefined because undefined and that
// inf and nan don't become null
return String(obj);
}
var styleMutationWarning = {};
function checkAndWarnForMutatedStyle(style1, style2, component) {
if (style1 == null || style2 == null) {
return;
}
if (shallowEqual(style1, style2)) {
return;
}
var componentName = component._tag;
var owner = component._currentElement._owner;
var ownerName;
if (owner) {
ownerName = owner.getName();
}
var hash = ownerName + '|' + componentName;
if (styleMutationWarning.hasOwnProperty(hash)) {
return;
}
styleMutationWarning[hash] = true;
process.env.NODE_ENV !== 'production' ? warning(false, '`%s` was passed a style object that has previously been mutated. ' + 'Mutating `style` is deprecated. Consider cloning it beforehand. Check ' + 'the `render` %s. Previous style: %s. Mutated style: %s.', componentName, owner ? 'of `' + ownerName + '`' : 'using <' + componentName + '>', friendlyStringify(style1), friendlyStringify(style2)) : void 0;
}
/**
* @param {object} component
* @param {?object} props
*/
function assertValidProps(component, props) {
if (!props) {
return;
}
// Note the use of `==` which checks for null or undefined.
if (voidElementTags[component._tag]) {
!(props.children == null && props.dangerouslySetInnerHTML == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML`.%s', component._tag, component._currentElement._owner ? ' Check the render method of ' + component._currentElement._owner.getName() + '.' : '') : _prodInvariant('137', component._tag, component._currentElement._owner ? ' Check the render method of ' + component._currentElement._owner.getName() + '.' : '') : void 0;
}
if (props.dangerouslySetInnerHTML != null) {
!(props.children == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Can only set one of `children` or `props.dangerouslySetInnerHTML`.') : _prodInvariant('60') : void 0;
!(typeof props.dangerouslySetInnerHTML === 'object' && HTML in props.dangerouslySetInnerHTML) ? process.env.NODE_ENV !== 'production' ? invariant(false, '`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. Please visit https://fb.me/react-invariant-dangerously-set-inner-html for more information.') : _prodInvariant('61') : void 0;
}
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(props.innerHTML == null, 'Directly setting property `innerHTML` is not permitted. ' + 'For more information, lookup documentation on `dangerouslySetInnerHTML`.') : void 0;
process.env.NODE_ENV !== 'production' ? warning(props.suppressContentEditableWarning || !props.contentEditable || props.children == null, 'A component is `contentEditable` and contains `children` managed by ' + 'React. It is now your responsibility to guarantee that none of ' + 'those nodes are unexpectedly modified or duplicated. This is ' + 'probably not intentional.') : void 0;
process.env.NODE_ENV !== 'production' ? warning(props.onFocusIn == null && props.onFocusOut == null, 'React uses onFocus and onBlur instead of onFocusIn and onFocusOut. ' + 'All React events are normalized to bubble, so onFocusIn and onFocusOut ' + 'are not needed/supported by React.') : void 0;
}
!(props.style == null || typeof props.style === 'object') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'The `style` prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + \'em\'}} when using JSX.%s', getDeclarationErrorAddendum(component)) : _prodInvariant('62', getDeclarationErrorAddendum(component)) : void 0;
}
function enqueuePutListener(inst, registrationName, listener, transaction) {
if (transaction instanceof ReactServerRenderingTransaction) {
return;
}
if (process.env.NODE_ENV !== 'production') {
// IE8 has no API for event capturing and the `onScroll` event doesn't
// bubble.
process.env.NODE_ENV !== 'production' ? warning(registrationName !== 'onScroll' || isEventSupported('scroll', true), 'This browser doesn\'t support the `onScroll` event') : void 0;
}
var containerInfo = inst._hostContainerInfo;
var isDocumentFragment = containerInfo._node && containerInfo._node.nodeType === DOC_FRAGMENT_TYPE;
var doc = isDocumentFragment ? containerInfo._node : containerInfo._ownerDocument;
listenTo(registrationName, doc);
transaction.getReactMountReady().enqueue(putListener, {
inst: inst,
registrationName: registrationName,
listener: listener
});
}
function putListener() {
var listenerToPut = this;
EventPluginHub.putListener(listenerToPut.inst, listenerToPut.registrationName, listenerToPut.listener);
}
function inputPostMount() {
var inst = this;
ReactDOMInput.postMountWrapper(inst);
}
function textareaPostMount() {
var inst = this;
ReactDOMTextarea.postMountWrapper(inst);
}
function optionPostMount() {
var inst = this;
ReactDOMOption.postMountWrapper(inst);
}
var setAndValidateContentChildDev = emptyFunction;
if (process.env.NODE_ENV !== 'production') {
setAndValidateContentChildDev = function (content) {
var hasExistingContent = this._contentDebugID != null;
var debugID = this._debugID;
// This ID represents the inlined child that has no backing instance:
var contentDebugID = -debugID;
if (content == null) {
if (hasExistingContent) {
ReactInstrumentation.debugTool.onUnmountComponent(this._contentDebugID);
}
this._contentDebugID = null;
return;
}
validateDOMNesting(null, String(content), this, this._ancestorInfo);
this._contentDebugID = contentDebugID;
if (hasExistingContent) {
ReactInstrumentation.debugTool.onBeforeUpdateComponent(contentDebugID, content);
ReactInstrumentation.debugTool.onUpdateComponent(contentDebugID);
} else {
ReactInstrumentation.debugTool.onBeforeMountComponent(contentDebugID, content, debugID);
ReactInstrumentation.debugTool.onMountComponent(contentDebugID);
ReactInstrumentation.debugTool.onSetChildren(debugID, [contentDebugID]);
}
};
}
// There are so many media events, it makes sense to just
// maintain a list rather than create a `trapBubbledEvent` for each
var mediaEvents = {
topAbort: 'abort',
topCanPlay: 'canplay',
topCanPlayThrough: 'canplaythrough',
topDurationChange: 'durationchange',
topEmptied: 'emptied',
topEncrypted: 'encrypted',
topEnded: 'ended',
topError: 'error',
topLoadedData: 'loadeddata',
topLoadedMetadata: 'loadedmetadata',
topLoadStart: 'loadstart',
topPause: 'pause',
topPlay: 'play',
topPlaying: 'playing',
topProgress: 'progress',
topRateChange: 'ratechange',
topSeeked: 'seeked',
topSeeking: 'seeking',
topStalled: 'stalled',
topSuspend: 'suspend',
topTimeUpdate: 'timeupdate',
topVolumeChange: 'volumechange',
topWaiting: 'waiting'
};
function trapBubbledEventsLocal() {
var inst = this;
// If a component renders to null or if another component fatals and causes
// the state of the tree to be corrupted, `node` here can be null.
!inst._rootNodeID ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Must be mounted to trap events') : _prodInvariant('63') : void 0;
var node = getNode(inst);
!node ? process.env.NODE_ENV !== 'production' ? invariant(false, 'trapBubbledEvent(...): Requires node to be rendered.') : _prodInvariant('64') : void 0;
switch (inst._tag) {
case 'iframe':
case 'object':
inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent('topLoad', 'load', node)];
break;
case 'video':
case 'audio':
inst._wrapperState.listeners = [];
// Create listener for each media event
for (var event in mediaEvents) {
if (mediaEvents.hasOwnProperty(event)) {
inst._wrapperState.listeners.push(ReactBrowserEventEmitter.trapBubbledEvent(event, mediaEvents[event], node));
}
}
break;
case 'source':
inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent('topError', 'error', node)];
break;
case 'img':
inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent('topError', 'error', node), ReactBrowserEventEmitter.trapBubbledEvent('topLoad', 'load', node)];
break;
case 'form':
inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent('topReset', 'reset', node), ReactBrowserEventEmitter.trapBubbledEvent('topSubmit', 'submit', node)];
break;
case 'input':
case 'select':
case 'textarea':
inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent('topInvalid', 'invalid', node)];
break;
}
}
function postUpdateSelectWrapper() {
ReactDOMSelect.postUpdateWrapper(this);
}
// For HTML, certain tags should omit their close tag. We keep a whitelist for
// those special-case tags.
var omittedCloseTags = {
'area': true,
'base': true,
'br': true,
'col': true,
'embed': true,
'hr': true,
'img': true,
'input': true,
'keygen': true,
'link': true,
'meta': true,
'param': true,
'source': true,
'track': true,
'wbr': true
};
var newlineEatingTags = {
'listing': true,
'pre': true,
'textarea': true
};
// For HTML, certain tags cannot have children. This has the same purpose as
// `omittedCloseTags` except that `menuitem` should still have its closing tag.
var voidElementTags = _assign({
'menuitem': true
}, omittedCloseTags);
// We accept any tag to be rendered but since this gets injected into arbitrary
// HTML, we want to make sure that it's a safe tag.
// http://www.w3.org/TR/REC-xml/#NT-Name
var VALID_TAG_REGEX = /^[a-zA-Z][a-zA-Z:_\.\-\d]*$/; // Simplified subset
var validatedTagCache = {};
var hasOwnProperty = {}.hasOwnProperty;
function validateDangerousTag(tag) {
if (!hasOwnProperty.call(validatedTagCache, tag)) {
!VALID_TAG_REGEX.test(tag) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Invalid tag: %s', tag) : _prodInvariant('65', tag) : void 0;
validatedTagCache[tag] = true;
}
}
function isCustomComponent(tagName, props) {
return tagName.indexOf('-') >= 0 || props.is != null;
}
var globalIdCounter = 1;
/**
* Creates a new React class that is idempotent and capable of containing other
* React components. It accepts event listeners and DOM properties that are
* valid according to `DOMProperty`.
*
* - Event listeners: `onClick`, `onMouseDown`, etc.
* - DOM properties: `className`, `name`, `title`, etc.
*
* The `style` property functions differently from the DOM API. It accepts an
* object mapping of style properties to values.
*
* @constructor ReactDOMComponent
* @extends ReactMultiChild
*/
function ReactDOMComponent(element) {
var tag = element.type;
validateDangerousTag(tag);
this._currentElement = element;
this._tag = tag.toLowerCase();
this._namespaceURI = null;
this._renderedChildren = null;
this._previousStyle = null;
this._previousStyleCopy = null;
this._hostNode = null;
this._hostParent = null;
this._rootNodeID = 0;
this._domID = 0;
this._hostContainerInfo = null;
this._wrapperState = null;
this._topLevelWrapper = null;
this._flags = 0;
if (process.env.NODE_ENV !== 'production') {
this._ancestorInfo = null;
setAndValidateContentChildDev.call(this, null);
}
}
ReactDOMComponent.displayName = 'ReactDOMComponent';
ReactDOMComponent.Mixin = {
/**
* Generates root tag markup then recurses. This method has side effects and
* is not idempotent.
*
* @internal
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @param {?ReactDOMComponent} the parent component instance
* @param {?object} info about the host container
* @param {object} context
* @return {string} The computed markup.
*/
mountComponent: function (transaction, hostParent, hostContainerInfo, context) {
this._rootNodeID = globalIdCounter++;
this._domID = hostContainerInfo._idCounter++;
this._hostParent = hostParent;
this._hostContainerInfo = hostContainerInfo;
var props = this._currentElement.props;
switch (this._tag) {
case 'audio':
case 'form':
case 'iframe':
case 'img':
case 'link':
case 'object':
case 'source':
case 'video':
this._wrapperState = {
listeners: null
};
transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this);
break;
case 'input':
ReactDOMInput.mountWrapper(this, props, hostParent);
props = ReactDOMInput.getHostProps(this, props);
transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this);
break;
case 'option':
ReactDOMOption.mountWrapper(this, props, hostParent);
props = ReactDOMOption.getHostProps(this, props);
break;
case 'select':
ReactDOMSelect.mountWrapper(this, props, hostParent);
props = ReactDOMSelect.getHostProps(this, props);
transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this);
break;
case 'textarea':
ReactDOMTextarea.mountWrapper(this, props, hostParent);
props = ReactDOMTextarea.getHostProps(this, props);
transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this);
break;
}
assertValidProps(this, props);
// We create tags in the namespace of their parent container, except HTML
// tags get no namespace.
var namespaceURI;
var parentTag;
if (hostParent != null) {
namespaceURI = hostParent._namespaceURI;
parentTag = hostParent._tag;
} else if (hostContainerInfo._tag) {
namespaceURI = hostContainerInfo._namespaceURI;
parentTag = hostContainerInfo._tag;
}
if (namespaceURI == null || namespaceURI === DOMNamespaces.svg && parentTag === 'foreignobject') {
namespaceURI = DOMNamespaces.html;
}
if (namespaceURI === DOMNamespaces.html) {
if (this._tag === 'svg') {
namespaceURI = DOMNamespaces.svg;
} else if (this._tag === 'math') {
namespaceURI = DOMNamespaces.mathml;
}
}
this._namespaceURI = namespaceURI;
if (process.env.NODE_ENV !== 'production') {
var parentInfo;
if (hostParent != null) {
parentInfo = hostParent._ancestorInfo;
} else if (hostContainerInfo._tag) {
parentInfo = hostContainerInfo._ancestorInfo;
}
if (parentInfo) {
// parentInfo should always be present except for the top-level
// component when server rendering
validateDOMNesting(this._tag, null, this, parentInfo);
}
this._ancestorInfo = validateDOMNesting.updatedAncestorInfo(parentInfo, this._tag, this);
}
var mountImage;
if (transaction.useCreateElement) {
var ownerDocument = hostContainerInfo._ownerDocument;
var el;
if (namespaceURI === DOMNamespaces.html) {
if (this._tag === 'script') {
// Create the script via .innerHTML so its "parser-inserted" flag is
// set to true and it does not execute
var div = ownerDocument.createElement('div');
var type = this._currentElement.type;
div.innerHTML = '<' + type + '></' + type + '>';
el = div.removeChild(div.firstChild);
} else if (props.is) {
el = ownerDocument.createElement(this._currentElement.type, props.is);
} else {
// Separate else branch instead of using `props.is || undefined` above becuase of a Firefox bug.
// See discussion in https://github.com/facebook/react/pull/6896
// and discussion in https://bugzilla.mozilla.org/show_bug.cgi?id=1276240
el = ownerDocument.createElement(this._currentElement.type);
}
} else {
el = ownerDocument.createElementNS(namespaceURI, this._currentElement.type);
}
ReactDOMComponentTree.precacheNode(this, el);
this._flags |= Flags.hasCachedChildNodes;
if (!this._hostParent) {
DOMPropertyOperations.setAttributeForRoot(el);
}
this._updateDOMProperties(null, props, transaction);
var lazyTree = DOMLazyTree(el);
this._createInitialChildren(transaction, props, context, lazyTree);
mountImage = lazyTree;
} else {
var tagOpen = this._createOpenTagMarkupAndPutListeners(transaction, props);
var tagContent = this._createContentMarkup(transaction, props, context);
if (!tagContent && omittedCloseTags[this._tag]) {
mountImage = tagOpen + '/>';
} else {
mountImage = tagOpen + '>' + tagContent + '</' + this._currentElement.type + '>';
}
}
switch (this._tag) {
case 'input':
transaction.getReactMountReady().enqueue(inputPostMount, this);
if (props.autoFocus) {
transaction.getReactMountReady().enqueue(AutoFocusUtils.focusDOMComponent, this);
}
break;
case 'textarea':
transaction.getReactMountReady().enqueue(textareaPostMount, this);
if (props.autoFocus) {
transaction.getReactMountReady().enqueue(AutoFocusUtils.focusDOMComponent, this);
}
break;
case 'select':
if (props.autoFocus) {
transaction.getReactMountReady().enqueue(AutoFocusUtils.focusDOMComponent, this);
}
break;
case 'button':
if (props.autoFocus) {
transaction.getReactMountReady().enqueue(AutoFocusUtils.focusDOMComponent, this);
}
break;
case 'option':
transaction.getReactMountReady().enqueue(optionPostMount, this);
break;
}
return mountImage;
},
/**
* Creates markup for the open tag and all attributes.
*
* This method has side effects because events get registered.
*
* Iterating over object properties is faster than iterating over arrays.
* @see http://jsperf.com/obj-vs-arr-iteration
*
* @private
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @param {object} props
* @return {string} Markup of opening tag.
*/
_createOpenTagMarkupAndPutListeners: function (transaction, props) {
var ret = '<' + this._currentElement.type;
for (var propKey in props) {
if (!props.hasOwnProperty(propKey)) {
continue;
}
var propValue = props[propKey];
if (propValue == null) {
continue;
}
if (registrationNameModules.hasOwnProperty(propKey)) {
if (propValue) {
enqueuePutListener(this, propKey, propValue, transaction);
}
} else {
if (propKey === STYLE) {
if (propValue) {
if (process.env.NODE_ENV !== 'production') {
// See `_updateDOMProperties`. style block
this._previousStyle = propValue;
}
propValue = this._previousStyleCopy = _assign({}, props.style);
}
propValue = CSSPropertyOperations.createMarkupForStyles(propValue, this);
}
var markup = null;
if (this._tag != null && isCustomComponent(this._tag, props)) {
if (!RESERVED_PROPS.hasOwnProperty(propKey)) {
markup = DOMPropertyOperations.createMarkupForCustomAttribute(propKey, propValue);
}
} else {
markup = DOMPropertyOperations.createMarkupForProperty(propKey, propValue);
}
if (markup) {
ret += ' ' + markup;
}
}
}
// For static pages, no need to put React ID and checksum. Saves lots of
// bytes.
if (transaction.renderToStaticMarkup) {
return ret;
}
if (!this._hostParent) {
ret += ' ' + DOMPropertyOperations.createMarkupForRoot();
}
ret += ' ' + DOMPropertyOperations.createMarkupForID(this._domID);
return ret;
},
/**
* Creates markup for the content between the tags.
*
* @private
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @param {object} props
* @param {object} context
* @return {string} Content markup.
*/
_createContentMarkup: function (transaction, props, context) {
var ret = '';
// Intentional use of != to avoid catching zero/false.
var innerHTML = props.dangerouslySetInnerHTML;
if (innerHTML != null) {
if (innerHTML.__html != null) {
ret = innerHTML.__html;
}
} else {
var contentToUse = CONTENT_TYPES[typeof props.children] ? props.children : null;
var childrenToUse = contentToUse != null ? null : props.children;
if (contentToUse != null) {
// TODO: Validate that text is allowed as a child of this node
ret = escapeTextContentForBrowser(contentToUse);
if (process.env.NODE_ENV !== 'production') {
setAndValidateContentChildDev.call(this, contentToUse);
}
} else if (childrenToUse != null) {
var mountImages = this.mountChildren(childrenToUse, transaction, context);
ret = mountImages.join('');
}
}
if (newlineEatingTags[this._tag] && ret.charAt(0) === '\n') {
// text/html ignores the first character in these tags if it's a newline
// Prefer to break application/xml over text/html (for now) by adding
// a newline specifically to get eaten by the parser. (Alternately for
// textareas, replacing "^\n" with "\r\n" doesn't get eaten, and the first
// \r is normalized out by HTMLTextAreaElement#value.)
// See: <http://www.w3.org/TR/html-polyglot/#newlines-in-textarea-and-pre>
// See: <http://www.w3.org/TR/html5/syntax.html#element-restrictions>
// See: <http://www.w3.org/TR/html5/syntax.html#newlines>
// See: Parsing of "textarea" "listing" and "pre" elements
// from <http://www.w3.org/TR/html5/syntax.html#parsing-main-inbody>
return '\n' + ret;
} else {
return ret;
}
},
_createInitialChildren: function (transaction, props, context, lazyTree) {
// Intentional use of != to avoid catching zero/false.
var innerHTML = props.dangerouslySetInnerHTML;
if (innerHTML != null) {
if (innerHTML.__html != null) {
DOMLazyTree.queueHTML(lazyTree, innerHTML.__html);
}
} else {
var contentToUse = CONTENT_TYPES[typeof props.children] ? props.children : null;
var childrenToUse = contentToUse != null ? null : props.children;
// TODO: Validate that text is allowed as a child of this node
if (contentToUse != null) {
// Avoid setting textContent when the text is empty. In IE11 setting
// textContent on a text area will cause the placeholder to not
// show within the textarea until it has been focused and blurred again.
// https://github.com/facebook/react/issues/6731#issuecomment-254874553
if (contentToUse !== '') {
if (process.env.NODE_ENV !== 'production') {
setAndValidateContentChildDev.call(this, contentToUse);
}
DOMLazyTree.queueText(lazyTree, contentToUse);
}
} else if (childrenToUse != null) {
var mountImages = this.mountChildren(childrenToUse, transaction, context);
for (var i = 0; i < mountImages.length; i++) {
DOMLazyTree.queueChild(lazyTree, mountImages[i]);
}
}
}
},
/**
* Receives a next element and updates the component.
*
* @internal
* @param {ReactElement} nextElement
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @param {object} context
*/
receiveComponent: function (nextElement, transaction, context) {
var prevElement = this._currentElement;
this._currentElement = nextElement;
this.updateComponent(transaction, prevElement, nextElement, context);
},
/**
* Updates a DOM component after it has already been allocated and
* attached to the DOM. Reconciles the root DOM node, then recurses.
*
* @param {ReactReconcileTransaction} transaction
* @param {ReactElement} prevElement
* @param {ReactElement} nextElement
* @internal
* @overridable
*/
updateComponent: function (transaction, prevElement, nextElement, context) {
var lastProps = prevElement.props;
var nextProps = this._currentElement.props;
switch (this._tag) {
case 'input':
lastProps = ReactDOMInput.getHostProps(this, lastProps);
nextProps = ReactDOMInput.getHostProps(this, nextProps);
break;
case 'option':
lastProps = ReactDOMOption.getHostProps(this, lastProps);
nextProps = ReactDOMOption.getHostProps(this, nextProps);
break;
case 'select':
lastProps = ReactDOMSelect.getHostProps(this, lastProps);
nextProps = ReactDOMSelect.getHostProps(this, nextProps);
break;
case 'textarea':
lastProps = ReactDOMTextarea.getHostProps(this, lastProps);
nextProps = ReactDOMTextarea.getHostProps(this, nextProps);
break;
}
assertValidProps(this, nextProps);
this._updateDOMProperties(lastProps, nextProps, transaction);
this._updateDOMChildren(lastProps, nextProps, transaction, context);
switch (this._tag) {
case 'input':
// Update the wrapper around inputs *after* updating props. This has to
// happen after `_updateDOMProperties`. Otherwise HTML5 input validations
// raise warnings and prevent the new value from being assigned.
ReactDOMInput.updateWrapper(this);
break;
case 'textarea':
ReactDOMTextarea.updateWrapper(this);
break;
case 'select':
// <select> value update needs to occur after <option> children
// reconciliation
transaction.getReactMountReady().enqueue(postUpdateSelectWrapper, this);
break;
}
},
/**
* Reconciles the properties by detecting differences in property values and
* updating the DOM as necessary. This function is probably the single most
* critical path for performance optimization.
*
* TODO: Benchmark whether checking for changed values in memory actually
* improves performance (especially statically positioned elements).
* TODO: Benchmark the effects of putting this at the top since 99% of props
* do not change for a given reconciliation.
* TODO: Benchmark areas that can be improved with caching.
*
* @private
* @param {object} lastProps
* @param {object} nextProps
* @param {?DOMElement} node
*/
_updateDOMProperties: function (lastProps, nextProps, transaction) {
var propKey;
var styleName;
var styleUpdates;
for (propKey in lastProps) {
if (nextProps.hasOwnProperty(propKey) || !lastProps.hasOwnProperty(propKey) || lastProps[propKey] == null) {
continue;
}
if (propKey === STYLE) {
var lastStyle = this._previousStyleCopy;
for (styleName in lastStyle) {
if (lastStyle.hasOwnProperty(styleName)) {
styleUpdates = styleUpdates || {};
styleUpdates[styleName] = '';
}
}
this._previousStyleCopy = null;
} else if (registrationNameModules.hasOwnProperty(propKey)) {
if (lastProps[propKey]) {
// Only call deleteListener if there was a listener previously or
// else willDeleteListener gets called when there wasn't actually a
// listener (e.g., onClick={null})
deleteListener(this, propKey);
}
} else if (isCustomComponent(this._tag, lastProps)) {
if (!RESERVED_PROPS.hasOwnProperty(propKey)) {
DOMPropertyOperations.deleteValueForAttribute(getNode(this), propKey);
}
} else if (DOMProperty.properties[propKey] || DOMProperty.isCustomAttribute(propKey)) {
DOMPropertyOperations.deleteValueForProperty(getNode(this), propKey);
}
}
for (propKey in nextProps) {
var nextProp = nextProps[propKey];
var lastProp = propKey === STYLE ? this._previousStyleCopy : lastProps != null ? lastProps[propKey] : undefined;
if (!nextProps.hasOwnProperty(propKey) || nextProp === lastProp || nextProp == null && lastProp == null) {
continue;
}
if (propKey === STYLE) {
if (nextProp) {
if (process.env.NODE_ENV !== 'production') {
checkAndWarnForMutatedStyle(this._previousStyleCopy, this._previousStyle, this);
this._previousStyle = nextProp;
}
nextProp = this._previousStyleCopy = _assign({}, nextProp);
} else {
this._previousStyleCopy = null;
}
if (lastProp) {
// Unset styles on `lastProp` but not on `nextProp`.
for (styleName in lastProp) {
if (lastProp.hasOwnProperty(styleName) && (!nextProp || !nextProp.hasOwnProperty(styleName))) {
styleUpdates = styleUpdates || {};
styleUpdates[styleName] = '';
}
}
// Update styles that changed since `lastProp`.
for (styleName in nextProp) {
if (nextProp.hasOwnProperty(styleName) && lastProp[styleName] !== nextProp[styleName]) {
styleUpdates = styleUpdates || {};
styleUpdates[styleName] = nextProp[styleName];
}
}
} else {
// Relies on `updateStylesByID` not mutating `styleUpdates`.
styleUpdates = nextProp;
}
} else if (registrationNameModules.hasOwnProperty(propKey)) {
if (nextProp) {
enqueuePutListener(this, propKey, nextProp, transaction);
} else if (lastProp) {
deleteListener(this, propKey);
}
} else if (isCustomComponent(this._tag, nextProps)) {
if (!RESERVED_PROPS.hasOwnProperty(propKey)) {
DOMPropertyOperations.setValueForAttribute(getNode(this), propKey, nextProp);
}
} else if (DOMProperty.properties[propKey] || DOMProperty.isCustomAttribute(propKey)) {
var node = getNode(this);
// If we're updating to null or undefined, we should remove the property
// from the DOM node instead of inadvertently setting to a string. This
// brings us in line with the same behavior we have on initial render.
if (nextProp != null) {
DOMPropertyOperations.setValueForProperty(node, propKey, nextProp);
} else {
DOMPropertyOperations.deleteValueForProperty(node, propKey);
}
}
}
if (styleUpdates) {
CSSPropertyOperations.setValueForStyles(getNode(this), styleUpdates, this);
}
},
/**
* Reconciles the children with the various properties that affect the
* children content.
*
* @param {object} lastProps
* @param {object} nextProps
* @param {ReactReconcileTransaction} transaction
* @param {object} context
*/
_updateDOMChildren: function (lastProps, nextProps, transaction, context) {
var lastContent = CONTENT_TYPES[typeof lastProps.children] ? lastProps.children : null;
var nextContent = CONTENT_TYPES[typeof nextProps.children] ? nextProps.children : null;
var lastHtml = lastProps.dangerouslySetInnerHTML && lastProps.dangerouslySetInnerHTML.__html;
var nextHtml = nextProps.dangerouslySetInnerHTML && nextProps.dangerouslySetInnerHTML.__html;
// Note the use of `!=` which checks for null or undefined.
var lastChildren = lastContent != null ? null : lastProps.children;
var nextChildren = nextContent != null ? null : nextProps.children;
// If we're switching from children to content/html or vice versa, remove
// the old content
var lastHasContentOrHtml = lastContent != null || lastHtml != null;
var nextHasContentOrHtml = nextContent != null || nextHtml != null;
if (lastChildren != null && nextChildren == null) {
this.updateChildren(null, transaction, context);
} else if (lastHasContentOrHtml && !nextHasContentOrHtml) {
this.updateTextContent('');
if (process.env.NODE_ENV !== 'production') {
ReactInstrumentation.debugTool.onSetChildren(this._debugID, []);
}
}
if (nextContent != null) {
if (lastContent !== nextContent) {
this.updateTextContent('' + nextContent);
if (process.env.NODE_ENV !== 'production') {
setAndValidateContentChildDev.call(this, nextContent);
}
}
} else if (nextHtml != null) {
if (lastHtml !== nextHtml) {
this.updateMarkup('' + nextHtml);
}
if (process.env.NODE_ENV !== 'production') {
ReactInstrumentation.debugTool.onSetChildren(this._debugID, []);
}
} else if (nextChildren != null) {
if (process.env.NODE_ENV !== 'production') {
setAndValidateContentChildDev.call(this, null);
}
this.updateChildren(nextChildren, transaction, context);
}
},
getHostNode: function () {
return getNode(this);
},
/**
* Destroys all event registrations for this instance. Does not remove from
* the DOM. That must be done by the parent.
*
* @internal
*/
unmountComponent: function (safely) {
switch (this._tag) {
case 'audio':
case 'form':
case 'iframe':
case 'img':
case 'link':
case 'object':
case 'source':
case 'video':
var listeners = this._wrapperState.listeners;
if (listeners) {
for (var i = 0; i < listeners.length; i++) {
listeners[i].remove();
}
}
break;
case 'html':
case 'head':
case 'body':
/**
* Components like <html> <head> and <body> can't be removed or added
* easily in a cross-browser way, however it's valuable to be able to
* take advantage of React's reconciliation for styling and <title>
* management. So we just document it and throw in dangerous cases.
*/
!false ? process.env.NODE_ENV !== 'production' ? invariant(false, '<%s> tried to unmount. Because of cross-browser quirks it is impossible to unmount some top-level components (eg <html>, <head>, and <body>) reliably and efficiently. To fix this, have a single top-level component that never unmounts render these elements.', this._tag) : _prodInvariant('66', this._tag) : void 0;
break;
}
this.unmountChildren(safely);
ReactDOMComponentTree.uncacheNode(this);
EventPluginHub.deleteAllListeners(this);
this._rootNodeID = 0;
this._domID = 0;
this._wrapperState = null;
if (process.env.NODE_ENV !== 'production') {
setAndValidateContentChildDev.call(this, null);
}
},
getPublicInstance: function () {
return getNode(this);
}
};
_assign(ReactDOMComponent.prototype, ReactDOMComponent.Mixin, ReactMultiChild.Mixin);
module.exports = ReactDOMComponent;
}).call(this,require('_process'))
},{"./AutoFocusUtils":36,"./CSSPropertyOperations":39,"./DOMLazyTree":43,"./DOMNamespaces":44,"./DOMProperty":45,"./DOMPropertyOperations":46,"./EventPluginHub":50,"./EventPluginRegistry":51,"./ReactBrowserEventEmitter":59,"./ReactDOMComponentFlags":66,"./ReactDOMComponentTree":67,"./ReactDOMInput":72,"./ReactDOMOption":75,"./ReactDOMSelect":76,"./ReactDOMTextarea":79,"./ReactInstrumentation":96,"./ReactMultiChild":100,"./ReactServerRenderingTransaction":108,"./escapeTextContentForBrowser":136,"./isEventSupported":150,"./reactProdInvariant":153,"./validateDOMNesting":159,"_process":29,"fbjs/lib/emptyFunction":11,"fbjs/lib/invariant":19,"fbjs/lib/shallowEqual":25,"fbjs/lib/warning":26,"object-assign":28}],66:[function(require,module,exports){
/**
* Copyright 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var ReactDOMComponentFlags = {
hasCachedChildNodes: 1 << 0
};
module.exports = ReactDOMComponentFlags;
},{}],67:[function(require,module,exports){
(function (process){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var _prodInvariant = require('./reactProdInvariant');
var DOMProperty = require('./DOMProperty');
var ReactDOMComponentFlags = require('./ReactDOMComponentFlags');
var invariant = require('fbjs/lib/invariant');
var ATTR_NAME = DOMProperty.ID_ATTRIBUTE_NAME;
var Flags = ReactDOMComponentFlags;
var internalInstanceKey = '__reactInternalInstance$' + Math.random().toString(36).slice(2);
/**
* Check if a given node should be cached.
*/
function shouldPrecacheNode(node, nodeID) {
return node.nodeType === 1 && node.getAttribute(ATTR_NAME) === String(nodeID) || node.nodeType === 8 && node.nodeValue === ' react-text: ' + nodeID + ' ' || node.nodeType === 8 && node.nodeValue === ' react-empty: ' + nodeID + ' ';
}
/**
* Drill down (through composites and empty components) until we get a host or
* host text component.
*
* This is pretty polymorphic but unavoidable with the current structure we have
* for `_renderedChildren`.
*/
function getRenderedHostOrTextFromComponent(component) {
var rendered;
while (rendered = component._renderedComponent) {
component = rendered;
}
return component;
}
/**
* Populate `_hostNode` on the rendered host/text component with the given
* DOM node. The passed `inst` can be a composite.
*/
function precacheNode(inst, node) {
var hostInst = getRenderedHostOrTextFromComponent(inst);
hostInst._hostNode = node;
node[internalInstanceKey] = hostInst;
}
function uncacheNode(inst) {
var node = inst._hostNode;
if (node) {
delete node[internalInstanceKey];
inst._hostNode = null;
}
}
/**
* Populate `_hostNode` on each child of `inst`, assuming that the children
* match up with the DOM (element) children of `node`.
*
* We cache entire levels at once to avoid an n^2 problem where we access the
* children of a node sequentially and have to walk from the start to our target
* node every time.
*
* Since we update `_renderedChildren` and the actual DOM at (slightly)
* different times, we could race here and see a newer `_renderedChildren` than
* the DOM nodes we see. To avoid this, ReactMultiChild calls
* `prepareToManageChildren` before we change `_renderedChildren`, at which
* time the container's child nodes are always cached (until it unmounts).
*/
function precacheChildNodes(inst, node) {
if (inst._flags & Flags.hasCachedChildNodes) {
return;
}
var children = inst._renderedChildren;
var childNode = node.firstChild;
outer: for (var name in children) {
if (!children.hasOwnProperty(name)) {
continue;
}
var childInst = children[name];
var childID = getRenderedHostOrTextFromComponent(childInst)._domID;
if (childID === 0) {
// We're currently unmounting this child in ReactMultiChild; skip it.
continue;
}
// We assume the child nodes are in the same order as the child instances.
for (; childNode !== null; childNode = childNode.nextSibling) {
if (shouldPrecacheNode(childNode, childID)) {
precacheNode(childInst, childNode);
continue outer;
}
}
// We reached the end of the DOM children without finding an ID match.
!false ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Unable to find element with ID %s.', childID) : _prodInvariant('32', childID) : void 0;
}
inst._flags |= Flags.hasCachedChildNodes;
}
/**
* Given a DOM node, return the closest ReactDOMComponent or
* ReactDOMTextComponent instance ancestor.
*/
function getClosestInstanceFromNode(node) {
if (node[internalInstanceKey]) {
return node[internalInstanceKey];
}
// Walk up the tree until we find an ancestor whose instance we have cached.
var parents = [];
while (!node[internalInstanceKey]) {
parents.push(node);
if (node.parentNode) {
node = node.parentNode;
} else {
// Top of the tree. This node must not be part of a React tree (or is
// unmounted, potentially).
return null;
}
}
var closest;
var inst;
for (; node && (inst = node[internalInstanceKey]); node = parents.pop()) {
closest = inst;
if (parents.length) {
precacheChildNodes(inst, node);
}
}
return closest;
}
/**
* Given a DOM node, return the ReactDOMComponent or ReactDOMTextComponent
* instance, or null if the node was not rendered by this React.
*/
function getInstanceFromNode(node) {
var inst = getClosestInstanceFromNode(node);
if (inst != null && inst._hostNode === node) {
return inst;
} else {
return null;
}
}
/**
* Given a ReactDOMComponent or ReactDOMTextComponent, return the corresponding
* DOM node.
*/
function getNodeFromInstance(inst) {
// Without this first invariant, passing a non-DOM-component triggers the next
// invariant for a missing parent, which is super confusing.
!(inst._hostNode !== undefined) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'getNodeFromInstance: Invalid argument.') : _prodInvariant('33') : void 0;
if (inst._hostNode) {
return inst._hostNode;
}
// Walk up the tree until we find an ancestor whose DOM node we have cached.
var parents = [];
while (!inst._hostNode) {
parents.push(inst);
!inst._hostParent ? process.env.NODE_ENV !== 'production' ? invariant(false, 'React DOM tree root should always have a node reference.') : _prodInvariant('34') : void 0;
inst = inst._hostParent;
}
// Now parents contains each ancestor that does *not* have a cached native
// node, and `inst` is the deepest ancestor that does.
for (; parents.length; inst = parents.pop()) {
precacheChildNodes(inst, inst._hostNode);
}
return inst._hostNode;
}
var ReactDOMComponentTree = {
getClosestInstanceFromNode: getClosestInstanceFromNode,
getInstanceFromNode: getInstanceFromNode,
getNodeFromInstance: getNodeFromInstance,
precacheChildNodes: precacheChildNodes,
precacheNode: precacheNode,
uncacheNode: uncacheNode
};
module.exports = ReactDOMComponentTree;
}).call(this,require('_process'))
},{"./DOMProperty":45,"./ReactDOMComponentFlags":66,"./reactProdInvariant":153,"_process":29,"fbjs/lib/invariant":19}],68:[function(require,module,exports){
(function (process){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var validateDOMNesting = require('./validateDOMNesting');
var DOC_NODE_TYPE = 9;
function ReactDOMContainerInfo(topLevelWrapper, node) {
var info = {
_topLevelWrapper: topLevelWrapper,
_idCounter: 1,
_ownerDocument: node ? node.nodeType === DOC_NODE_TYPE ? node : node.ownerDocument : null,
_node: node,
_tag: node ? node.nodeName.toLowerCase() : null,
_namespaceURI: node ? node.namespaceURI : null
};
if (process.env.NODE_ENV !== 'production') {
info._ancestorInfo = node ? validateDOMNesting.updatedAncestorInfo(null, info._tag, null) : null;
}
return info;
}
module.exports = ReactDOMContainerInfo;
}).call(this,require('_process'))
},{"./validateDOMNesting":159,"_process":29}],69:[function(require,module,exports){
/**
* Copyright 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var _assign = require('object-assign');
var DOMLazyTree = require('./DOMLazyTree');
var ReactDOMComponentTree = require('./ReactDOMComponentTree');
var ReactDOMEmptyComponent = function (instantiate) {
// ReactCompositeComponent uses this:
this._currentElement = null;
// ReactDOMComponentTree uses these:
this._hostNode = null;
this._hostParent = null;
this._hostContainerInfo = null;
this._domID = 0;
};
_assign(ReactDOMEmptyComponent.prototype, {
mountComponent: function (transaction, hostParent, hostContainerInfo, context) {
var domID = hostContainerInfo._idCounter++;
this._domID = domID;
this._hostParent = hostParent;
this._hostContainerInfo = hostContainerInfo;
var nodeValue = ' react-empty: ' + this._domID + ' ';
if (transaction.useCreateElement) {
var ownerDocument = hostContainerInfo._ownerDocument;
var node = ownerDocument.createComment(nodeValue);
ReactDOMComponentTree.precacheNode(this, node);
return DOMLazyTree(node);
} else {
if (transaction.renderToStaticMarkup) {
// Normally we'd insert a comment node, but since this is a situation
// where React won't take over (static pages), we can simply return
// nothing.
return '';
}
return '<!--' + nodeValue + '-->';
}
},
receiveComponent: function () {},
getHostNode: function () {
return ReactDOMComponentTree.getNodeFromInstance(this);
},
unmountComponent: function () {
ReactDOMComponentTree.uncacheNode(this);
}
});
module.exports = ReactDOMEmptyComponent;
},{"./DOMLazyTree":43,"./ReactDOMComponentTree":67,"object-assign":28}],70:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var ReactDOMFeatureFlags = {
useCreateElement: true,
useFiber: false
};
module.exports = ReactDOMFeatureFlags;
},{}],71:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var DOMChildrenOperations = require('./DOMChildrenOperations');
var ReactDOMComponentTree = require('./ReactDOMComponentTree');
/**
* Operations used to process updates to DOM nodes.
*/
var ReactDOMIDOperations = {
/**
* Updates a component's children by processing a series of updates.
*
* @param {array<object>} updates List of update configurations.
* @internal
*/
dangerouslyProcessChildrenUpdates: function (parentInst, updates) {
var node = ReactDOMComponentTree.getNodeFromInstance(parentInst);
DOMChildrenOperations.processUpdates(node, updates);
}
};
module.exports = ReactDOMIDOperations;
},{"./DOMChildrenOperations":42,"./ReactDOMComponentTree":67}],72:[function(require,module,exports){
(function (process){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var _prodInvariant = require('./reactProdInvariant'),
_assign = require('object-assign');
var DOMPropertyOperations = require('./DOMPropertyOperations');
var LinkedValueUtils = require('./LinkedValueUtils');
var ReactDOMComponentTree = require('./ReactDOMComponentTree');
var ReactUpdates = require('./ReactUpdates');
var invariant = require('fbjs/lib/invariant');
var warning = require('fbjs/lib/warning');
var didWarnValueLink = false;
var didWarnCheckedLink = false;
var didWarnValueDefaultValue = false;
var didWarnCheckedDefaultChecked = false;
var didWarnControlledToUncontrolled = false;
var didWarnUncontrolledToControlled = false;
function forceUpdateIfMounted() {
if (this._rootNodeID) {
// DOM component is still mounted; update
ReactDOMInput.updateWrapper(this);
}
}
function isControlled(props) {
var usesChecked = props.type === 'checkbox' || props.type === 'radio';
return usesChecked ? props.checked != null : props.value != null;
}
/**
* Implements an <input> host component that allows setting these optional
* props: `checked`, `value`, `defaultChecked`, and `defaultValue`.
*
* If `checked` or `value` are not supplied (or null/undefined), user actions
* that affect the checked state or value will trigger updates to the element.
*
* If they are supplied (and not null/undefined), the rendered element will not
* trigger updates to the element. Instead, the props must change in order for
* the rendered element to be updated.
*
* The rendered element will be initialized as unchecked (or `defaultChecked`)
* with an empty value (or `defaultValue`).
*
* @see http://www.w3.org/TR/2012/WD-html5-20121025/the-input-element.html
*/
var ReactDOMInput = {
getHostProps: function (inst, props) {
var value = LinkedValueUtils.getValue(props);
var checked = LinkedValueUtils.getChecked(props);
var hostProps = _assign({
// Make sure we set .type before any other properties (setting .value
// before .type means .value is lost in IE11 and below)
type: undefined,
// Make sure we set .step before .value (setting .value before .step
// means .value is rounded on mount, based upon step precision)
step: undefined,
// Make sure we set .min & .max before .value (to ensure proper order
// in corner cases such as min or max deriving from value, e.g. Issue #7170)
min: undefined,
max: undefined
}, props, {
defaultChecked: undefined,
defaultValue: undefined,
value: value != null ? value : inst._wrapperState.initialValue,
checked: checked != null ? checked : inst._wrapperState.initialChecked,
onChange: inst._wrapperState.onChange
});
return hostProps;
},
mountWrapper: function (inst, props) {
if (process.env.NODE_ENV !== 'production') {
LinkedValueUtils.checkPropTypes('input', props, inst._currentElement._owner);
var owner = inst._currentElement._owner;
if (props.valueLink !== undefined && !didWarnValueLink) {
process.env.NODE_ENV !== 'production' ? warning(false, '`valueLink` prop on `input` is deprecated; set `value` and `onChange` instead.') : void 0;
didWarnValueLink = true;
}
if (props.checkedLink !== undefined && !didWarnCheckedLink) {
process.env.NODE_ENV !== 'production' ? warning(false, '`checkedLink` prop on `input` is deprecated; set `value` and `onChange` instead.') : void 0;
didWarnCheckedLink = true;
}
if (props.checked !== undefined && props.defaultChecked !== undefined && !didWarnCheckedDefaultChecked) {
process.env.NODE_ENV !== 'production' ? warning(false, '%s contains an input of type %s with both checked and defaultChecked props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the checked prop, or the defaultChecked prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components', owner && owner.getName() || 'A component', props.type) : void 0;
didWarnCheckedDefaultChecked = true;
}
if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue) {
process.env.NODE_ENV !== 'production' ? warning(false, '%s contains an input of type %s with both value and defaultValue props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components', owner && owner.getName() || 'A component', props.type) : void 0;
didWarnValueDefaultValue = true;
}
}
var defaultValue = props.defaultValue;
inst._wrapperState = {
initialChecked: props.checked != null ? props.checked : props.defaultChecked,
initialValue: props.value != null ? props.value : defaultValue,
listeners: null,
onChange: _handleChange.bind(inst),
controlled: isControlled(props)
};
},
updateWrapper: function (inst) {
var props = inst._currentElement.props;
if (process.env.NODE_ENV !== 'production') {
var controlled = isControlled(props);
var owner = inst._currentElement._owner;
if (!inst._wrapperState.controlled && controlled && !didWarnUncontrolledToControlled) {
process.env.NODE_ENV !== 'production' ? warning(false, '%s is changing an uncontrolled input of type %s to be controlled. ' + 'Input elements should not switch from uncontrolled to controlled (or vice versa). ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components', owner && owner.getName() || 'A component', props.type) : void 0;
didWarnUncontrolledToControlled = true;
}
if (inst._wrapperState.controlled && !controlled && !didWarnControlledToUncontrolled) {
process.env.NODE_ENV !== 'production' ? warning(false, '%s is changing a controlled input of type %s to be uncontrolled. ' + 'Input elements should not switch from controlled to uncontrolled (or vice versa). ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components', owner && owner.getName() || 'A component', props.type) : void 0;
didWarnControlledToUncontrolled = true;
}
}
// TODO: Shouldn't this be getChecked(props)?
var checked = props.checked;
if (checked != null) {
DOMPropertyOperations.setValueForProperty(ReactDOMComponentTree.getNodeFromInstance(inst), 'checked', checked || false);
}
var node = ReactDOMComponentTree.getNodeFromInstance(inst);
var value = LinkedValueUtils.getValue(props);
if (value != null) {
if (value === 0 && node.value === '') {
node.value = '0';
// Note: IE9 reports a number inputs as 'text', so check props instead.
} else if (props.type === 'number') {
// Simulate `input.valueAsNumber`. IE9 does not support it
var valueAsNumber = parseFloat(node.value, 10) || 0;
// eslint-disable-next-line
if (value != valueAsNumber) {
// Cast `value` to a string to ensure the value is set correctly. While
// browsers typically do this as necessary, jsdom doesn't.
node.value = '' + value;
}
// eslint-disable-next-line
} else if (value != node.value) {
// Cast `value` to a string to ensure the value is set correctly. While
// browsers typically do this as necessary, jsdom doesn't.
node.value = '' + value;
}
} else {
if (props.value == null && props.defaultValue != null) {
// In Chrome, assigning defaultValue to certain input types triggers input validation.
// For number inputs, the display value loses trailing decimal points. For email inputs,
// Chrome raises "The specified value <x> is not a valid email address".
//
// Here we check to see if the defaultValue has actually changed, avoiding these problems
// when the user is inputting text
//
// https://github.com/facebook/react/issues/7253
if (node.defaultValue !== '' + props.defaultValue) {
node.defaultValue = '' + props.defaultValue;
}
}
if (props.checked == null && props.defaultChecked != null) {
node.defaultChecked = !!props.defaultChecked;
}
}
},
postMountWrapper: function (inst) {
var props = inst._currentElement.props;
// This is in postMount because we need access to the DOM node, which is not
// available until after the component has mounted.
var node = ReactDOMComponentTree.getNodeFromInstance(inst);
// Detach value from defaultValue. We won't do anything if we're working on
// submit or reset inputs as those values & defaultValues are linked. They
// are not resetable nodes so this operation doesn't matter and actually
// removes browser-default values (eg "Submit Query") when no value is
// provided.
switch (props.type) {
case 'submit':
case 'reset':
break;
case 'color':
case 'date':
case 'datetime':
case 'datetime-local':
case 'month':
case 'time':
case 'week':
// This fixes the no-show issue on iOS Safari and Android Chrome:
// https://github.com/facebook/react/issues/7233
node.value = '';
node.value = node.defaultValue;
break;
default:
node.value = node.value;
break;
}
// Normally, we'd just do `node.checked = node.checked` upon initial mount, less this bug
// this is needed to work around a chrome bug where setting defaultChecked
// will sometimes influence the value of checked (even after detachment).
// Reference: https://bugs.chromium.org/p/chromium/issues/detail?id=608416
// We need to temporarily unset name to avoid disrupting radio button groups.
var name = node.name;
if (name !== '') {
node.name = '';
}
node.defaultChecked = !node.defaultChecked;
node.defaultChecked = !node.defaultChecked;
if (name !== '') {
node.name = name;
}
}
};
function _handleChange(event) {
var props = this._currentElement.props;
var returnValue = LinkedValueUtils.executeOnChange(props, event);
// Here we use asap to wait until all updates have propagated, which
// is important when using controlled components within layers:
// https://github.com/facebook/react/issues/1698
ReactUpdates.asap(forceUpdateIfMounted, this);
var name = props.name;
if (props.type === 'radio' && name != null) {
var rootNode = ReactDOMComponentTree.getNodeFromInstance(this);
var queryRoot = rootNode;
while (queryRoot.parentNode) {
queryRoot = queryRoot.parentNode;
}
// If `rootNode.form` was non-null, then we could try `form.elements`,
// but that sometimes behaves strangely in IE8. We could also try using
// `form.getElementsByName`, but that will only return direct children
// and won't include inputs that use the HTML5 `form=` attribute. Since
// the input might not even be in a form, let's just use the global
// `querySelectorAll` to ensure we don't miss anything.
var group = queryRoot.querySelectorAll('input[name=' + JSON.stringify('' + name) + '][type="radio"]');
for (var i = 0; i < group.length; i++) {
var otherNode = group[i];
if (otherNode === rootNode || otherNode.form !== rootNode.form) {
continue;
}
// This will throw if radio buttons rendered by different copies of React
// and the same name are rendered into the same form (same as #1939).
// That's probably okay; we don't support it just as we don't support
// mixing React radio buttons with non-React ones.
var otherInstance = ReactDOMComponentTree.getInstanceFromNode(otherNode);
!otherInstance ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactDOMInput: Mixing React and non-React radio inputs with the same `name` is not supported.') : _prodInvariant('90') : void 0;
// If this is a controlled radio button group, forcing the input that
// was previously checked to update will cause it to be come re-checked
// as appropriate.
ReactUpdates.asap(forceUpdateIfMounted, otherInstance);
}
}
return returnValue;
}
module.exports = ReactDOMInput;
}).call(this,require('_process'))
},{"./DOMPropertyOperations":46,"./LinkedValueUtils":57,"./ReactDOMComponentTree":67,"./ReactUpdates":111,"./reactProdInvariant":153,"_process":29,"fbjs/lib/invariant":19,"fbjs/lib/warning":26,"object-assign":28}],73:[function(require,module,exports){
(function (process){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var DOMProperty = require('./DOMProperty');
var ReactComponentTreeHook = require('react/lib/ReactComponentTreeHook');
var warning = require('fbjs/lib/warning');
var warnedProperties = {};
var rARIA = new RegExp('^(aria)-[' + DOMProperty.ATTRIBUTE_NAME_CHAR + ']*$');
function validateProperty(tagName, name, debugID) {
if (warnedProperties.hasOwnProperty(name) && warnedProperties[name]) {
return true;
}
if (rARIA.test(name)) {
var lowerCasedName = name.toLowerCase();
var standardName = DOMProperty.getPossibleStandardName.hasOwnProperty(lowerCasedName) ? DOMProperty.getPossibleStandardName[lowerCasedName] : null;
// If this is an aria-* attribute, but is not listed in the known DOM
// DOM properties, then it is an invalid aria-* attribute.
if (standardName == null) {
warnedProperties[name] = true;
return false;
}
// aria-* attributes should be lowercase; suggest the lowercase version.
if (name !== standardName) {
process.env.NODE_ENV !== 'production' ? warning(false, 'Unknown ARIA attribute %s. Did you mean %s?%s', name, standardName, ReactComponentTreeHook.getStackAddendumByID(debugID)) : void 0;
warnedProperties[name] = true;
return true;
}
}
return true;
}
function warnInvalidARIAProps(debugID, element) {
var invalidProps = [];
for (var key in element.props) {
var isValid = validateProperty(element.type, key, debugID);
if (!isValid) {
invalidProps.push(key);
}
}
var unknownPropString = invalidProps.map(function (prop) {
return '`' + prop + '`';
}).join(', ');
if (invalidProps.length === 1) {
process.env.NODE_ENV !== 'production' ? warning(false, 'Invalid aria prop %s on <%s> tag. ' + 'For details, see https://fb.me/invalid-aria-prop%s', unknownPropString, element.type, ReactComponentTreeHook.getStackAddendumByID(debugID)) : void 0;
} else if (invalidProps.length > 1) {
process.env.NODE_ENV !== 'production' ? warning(false, 'Invalid aria props %s on <%s> tag. ' + 'For details, see https://fb.me/invalid-aria-prop%s', unknownPropString, element.type, ReactComponentTreeHook.getStackAddendumByID(debugID)) : void 0;
}
}
function handleElement(debugID, element) {
if (element == null || typeof element.type !== 'string') {
return;
}
if (element.type.indexOf('-') >= 0 || element.props.is) {
return;
}
warnInvalidARIAProps(debugID, element);
}
var ReactDOMInvalidARIAHook = {
onBeforeMountComponent: function (debugID, element) {
if (process.env.NODE_ENV !== 'production') {
handleElement(debugID, element);
}
},
onBeforeUpdateComponent: function (debugID, element) {
if (process.env.NODE_ENV !== 'production') {
handleElement(debugID, element);
}
}
};
module.exports = ReactDOMInvalidARIAHook;
}).call(this,require('_process'))
},{"./DOMProperty":45,"_process":29,"fbjs/lib/warning":26,"react/lib/ReactComponentTreeHook":168}],74:[function(require,module,exports){
(function (process){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var ReactComponentTreeHook = require('react/lib/ReactComponentTreeHook');
var warning = require('fbjs/lib/warning');
var didWarnValueNull = false;
function handleElement(debugID, element) {
if (element == null) {
return;
}
if (element.type !== 'input' && element.type !== 'textarea' && element.type !== 'select') {
return;
}
if (element.props != null && element.props.value === null && !didWarnValueNull) {
process.env.NODE_ENV !== 'production' ? warning(false, '`value` prop on `%s` should not be null. ' + 'Consider using the empty string to clear the component or `undefined` ' + 'for uncontrolled components.%s', element.type, ReactComponentTreeHook.getStackAddendumByID(debugID)) : void 0;
didWarnValueNull = true;
}
}
var ReactDOMNullInputValuePropHook = {
onBeforeMountComponent: function (debugID, element) {
handleElement(debugID, element);
},
onBeforeUpdateComponent: function (debugID, element) {
handleElement(debugID, element);
}
};
module.exports = ReactDOMNullInputValuePropHook;
}).call(this,require('_process'))
},{"_process":29,"fbjs/lib/warning":26,"react/lib/ReactComponentTreeHook":168}],75:[function(require,module,exports){
(function (process){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var _assign = require('object-assign');
var React = require('react/lib/React');
var ReactDOMComponentTree = require('./ReactDOMComponentTree');
var ReactDOMSelect = require('./ReactDOMSelect');
var warning = require('fbjs/lib/warning');
var didWarnInvalidOptionChildren = false;
function flattenChildren(children) {
var content = '';
// Flatten children and warn if they aren't strings or numbers;
// invalid types are ignored.
React.Children.forEach(children, function (child) {
if (child == null) {
return;
}
if (typeof child === 'string' || typeof child === 'number') {
content += child;
} else if (!didWarnInvalidOptionChildren) {
didWarnInvalidOptionChildren = true;
process.env.NODE_ENV !== 'production' ? warning(false, 'Only strings and numbers are supported as <option> children.') : void 0;
}
});
return content;
}
/**
* Implements an <option> host component that warns when `selected` is set.
*/
var ReactDOMOption = {
mountWrapper: function (inst, props, hostParent) {
// TODO (yungsters): Remove support for `selected` in <option>.
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(props.selected == null, 'Use the `defaultValue` or `value` props on <select> instead of ' + 'setting `selected` on <option>.') : void 0;
}
// Look up whether this option is 'selected'
var selectValue = null;
if (hostParent != null) {
var selectParent = hostParent;
if (selectParent._tag === 'optgroup') {
selectParent = selectParent._hostParent;
}
if (selectParent != null && selectParent._tag === 'select') {
selectValue = ReactDOMSelect.getSelectValueContext(selectParent);
}
}
// If the value is null (e.g., no specified value or after initial mount)
// or missing (e.g., for <datalist>), we don't change props.selected
var selected = null;
if (selectValue != null) {
var value;
if (props.value != null) {
value = props.value + '';
} else {
value = flattenChildren(props.children);
}
selected = false;
if (Array.isArray(selectValue)) {
// multiple
for (var i = 0; i < selectValue.length; i++) {
if ('' + selectValue[i] === value) {
selected = true;
break;
}
}
} else {
selected = '' + selectValue === value;
}
}
inst._wrapperState = { selected: selected };
},
postMountWrapper: function (inst) {
// value="" should make a value attribute (#6219)
var props = inst._currentElement.props;
if (props.value != null) {
var node = ReactDOMComponentTree.getNodeFromInstance(inst);
node.setAttribute('value', props.value);
}
},
getHostProps: function (inst, props) {
var hostProps = _assign({ selected: undefined, children: undefined }, props);
// Read state only from initial mount because <select> updates value
// manually; we need the initial state only for server rendering
if (inst._wrapperState.selected != null) {
hostProps.selected = inst._wrapperState.selected;
}
var content = flattenChildren(props.children);
if (content) {
hostProps.children = content;
}
return hostProps;
}
};
module.exports = ReactDOMOption;
}).call(this,require('_process'))
},{"./ReactDOMComponentTree":67,"./ReactDOMSelect":76,"_process":29,"fbjs/lib/warning":26,"object-assign":28,"react/lib/React":165}],76:[function(require,module,exports){
(function (process){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var _assign = require('object-assign');
var LinkedValueUtils = require('./LinkedValueUtils');
var ReactDOMComponentTree = require('./ReactDOMComponentTree');
var ReactUpdates = require('./ReactUpdates');
var warning = require('fbjs/lib/warning');
var didWarnValueLink = false;
var didWarnValueDefaultValue = false;
function updateOptionsIfPendingUpdateAndMounted() {
if (this._rootNodeID && this._wrapperState.pendingUpdate) {
this._wrapperState.pendingUpdate = false;
var props = this._currentElement.props;
var value = LinkedValueUtils.getValue(props);
if (value != null) {
updateOptions(this, Boolean(props.multiple), value);
}
}
}
function getDeclarationErrorAddendum(owner) {
if (owner) {
var name = owner.getName();
if (name) {
return ' Check the render method of `' + name + '`.';
}
}
return '';
}
var valuePropNames = ['value', 'defaultValue'];
/**
* Validation function for `value` and `defaultValue`.
* @private
*/
function checkSelectPropTypes(inst, props) {
var owner = inst._currentElement._owner;
LinkedValueUtils.checkPropTypes('select', props, owner);
if (props.valueLink !== undefined && !didWarnValueLink) {
process.env.NODE_ENV !== 'production' ? warning(false, '`valueLink` prop on `select` is deprecated; set `value` and `onChange` instead.') : void 0;
didWarnValueLink = true;
}
for (var i = 0; i < valuePropNames.length; i++) {
var propName = valuePropNames[i];
if (props[propName] == null) {
continue;
}
var isArray = Array.isArray(props[propName]);
if (props.multiple && !isArray) {
process.env.NODE_ENV !== 'production' ? warning(false, 'The `%s` prop supplied to <select> must be an array if ' + '`multiple` is true.%s', propName, getDeclarationErrorAddendum(owner)) : void 0;
} else if (!props.multiple && isArray) {
process.env.NODE_ENV !== 'production' ? warning(false, 'The `%s` prop supplied to <select> must be a scalar ' + 'value if `multiple` is false.%s', propName, getDeclarationErrorAddendum(owner)) : void 0;
}
}
}
/**
* @param {ReactDOMComponent} inst
* @param {boolean} multiple
* @param {*} propValue A stringable (with `multiple`, a list of stringables).
* @private
*/
function updateOptions(inst, multiple, propValue) {
var selectedValue, i;
var options = ReactDOMComponentTree.getNodeFromInstance(inst).options;
if (multiple) {
selectedValue = {};
for (i = 0; i < propValue.length; i++) {
selectedValue['' + propValue[i]] = true;
}
for (i = 0; i < options.length; i++) {
var selected = selectedValue.hasOwnProperty(options[i].value);
if (options[i].selected !== selected) {
options[i].selected = selected;
}
}
} else {
// Do not set `select.value` as exact behavior isn't consistent across all
// browsers for all cases.
selectedValue = '' + propValue;
for (i = 0; i < options.length; i++) {
if (options[i].value === selectedValue) {
options[i].selected = true;
return;
}
}
if (options.length) {
options[0].selected = true;
}
}
}
/**
* Implements a <select> host component that allows optionally setting the
* props `value` and `defaultValue`. If `multiple` is false, the prop must be a
* stringable. If `multiple` is true, the prop must be an array of stringables.
*
* If `value` is not supplied (or null/undefined), user actions that change the
* selected option will trigger updates to the rendered options.
*
* If it is supplied (and not null/undefined), the rendered options will not
* update in response to user actions. Instead, the `value` prop must change in
* order for the rendered options to update.
*
* If `defaultValue` is provided, any options with the supplied values will be
* selected.
*/
var ReactDOMSelect = {
getHostProps: function (inst, props) {
return _assign({}, props, {
onChange: inst._wrapperState.onChange,
value: undefined
});
},
mountWrapper: function (inst, props) {
if (process.env.NODE_ENV !== 'production') {
checkSelectPropTypes(inst, props);
}
var value = LinkedValueUtils.getValue(props);
inst._wrapperState = {
pendingUpdate: false,
initialValue: value != null ? value : props.defaultValue,
listeners: null,
onChange: _handleChange.bind(inst),
wasMultiple: Boolean(props.multiple)
};
if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue) {
process.env.NODE_ENV !== 'production' ? warning(false, 'Select elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled select ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components') : void 0;
didWarnValueDefaultValue = true;
}
},
getSelectValueContext: function (inst) {
// ReactDOMOption looks at this initial value so the initial generated
// markup has correct `selected` attributes
return inst._wrapperState.initialValue;
},
postUpdateWrapper: function (inst) {
var props = inst._currentElement.props;
// After the initial mount, we control selected-ness manually so don't pass
// this value down
inst._wrapperState.initialValue = undefined;
var wasMultiple = inst._wrapperState.wasMultiple;
inst._wrapperState.wasMultiple = Boolean(props.multiple);
var value = LinkedValueUtils.getValue(props);
if (value != null) {
inst._wrapperState.pendingUpdate = false;
updateOptions(inst, Boolean(props.multiple), value);
} else if (wasMultiple !== Boolean(props.multiple)) {
// For simplicity, reapply `defaultValue` if `multiple` is toggled.
if (props.defaultValue != null) {
updateOptions(inst, Boolean(props.multiple), props.defaultValue);
} else {
// Revert the select back to its default unselected state.
updateOptions(inst, Boolean(props.multiple), props.multiple ? [] : '');
}
}
}
};
function _handleChange(event) {
var props = this._currentElement.props;
var returnValue = LinkedValueUtils.executeOnChange(props, event);
if (this._rootNodeID) {
this._wrapperState.pendingUpdate = true;
}
ReactUpdates.asap(updateOptionsIfPendingUpdateAndMounted, this);
return returnValue;
}
module.exports = ReactDOMSelect;
}).call(this,require('_process'))
},{"./LinkedValueUtils":57,"./ReactDOMComponentTree":67,"./ReactUpdates":111,"_process":29,"fbjs/lib/warning":26,"object-assign":28}],77:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var ExecutionEnvironment = require('fbjs/lib/ExecutionEnvironment');
var getNodeForCharacterOffset = require('./getNodeForCharacterOffset');
var getTextContentAccessor = require('./getTextContentAccessor');
/**
* While `isCollapsed` is available on the Selection object and `collapsed`
* is available on the Range object, IE11 sometimes gets them wrong.
* If the anchor/focus nodes and offsets are the same, the range is collapsed.
*/
function isCollapsed(anchorNode, anchorOffset, focusNode, focusOffset) {
return anchorNode === focusNode && anchorOffset === focusOffset;
}
/**
* Get the appropriate anchor and focus node/offset pairs for IE.
*
* The catch here is that IE's selection API doesn't provide information
* about whether the selection is forward or backward, so we have to
* behave as though it's always forward.
*
* IE text differs from modern selection in that it behaves as though
* block elements end with a new line. This means character offsets will
* differ between the two APIs.
*
* @param {DOMElement} node
* @return {object}
*/
function getIEOffsets(node) {
var selection = document.selection;
var selectedRange = selection.createRange();
var selectedLength = selectedRange.text.length;
// Duplicate selection so we can move range without breaking user selection.
var fromStart = selectedRange.duplicate();
fromStart.moveToElementText(node);
fromStart.setEndPoint('EndToStart', selectedRange);
var startOffset = fromStart.text.length;
var endOffset = startOffset + selectedLength;
return {
start: startOffset,
end: endOffset
};
}
/**
* @param {DOMElement} node
* @return {?object}
*/
function getModernOffsets(node) {
var selection = window.getSelection && window.getSelection();
if (!selection || selection.rangeCount === 0) {
return null;
}
var anchorNode = selection.anchorNode;
var anchorOffset = selection.anchorOffset;
var focusNode = selection.focusNode;
var focusOffset = selection.focusOffset;
var currentRange = selection.getRangeAt(0);
// In Firefox, range.startContainer and range.endContainer can be "anonymous
// divs", e.g. the up/down buttons on an <input type="number">. Anonymous
// divs do not seem to expose properties, triggering a "Permission denied
// error" if any of its properties are accessed. The only seemingly possible
// way to avoid erroring is to access a property that typically works for
// non-anonymous divs and catch any error that may otherwise arise. See
// https://bugzilla.mozilla.org/show_bug.cgi?id=208427
try {
/* eslint-disable no-unused-expressions */
currentRange.startContainer.nodeType;
currentRange.endContainer.nodeType;
/* eslint-enable no-unused-expressions */
} catch (e) {
return null;
}
// If the node and offset values are the same, the selection is collapsed.
// `Selection.isCollapsed` is available natively, but IE sometimes gets
// this value wrong.
var isSelectionCollapsed = isCollapsed(selection.anchorNode, selection.anchorOffset, selection.focusNode, selection.focusOffset);
var rangeLength = isSelectionCollapsed ? 0 : currentRange.toString().length;
var tempRange = currentRange.cloneRange();
tempRange.selectNodeContents(node);
tempRange.setEnd(currentRange.startContainer, currentRange.startOffset);
var isTempRangeCollapsed = isCollapsed(tempRange.startContainer, tempRange.startOffset, tempRange.endContainer, tempRange.endOffset);
var start = isTempRangeCollapsed ? 0 : tempRange.toString().length;
var end = start + rangeLength;
// Detect whether the selection is backward.
var detectionRange = document.createRange();
detectionRange.setStart(anchorNode, anchorOffset);
detectionRange.setEnd(focusNode, focusOffset);
var isBackward = detectionRange.collapsed;
return {
start: isBackward ? end : start,
end: isBackward ? start : end
};
}
/**
* @param {DOMElement|DOMTextNode} node
* @param {object} offsets
*/
function setIEOffsets(node, offsets) {
var range = document.selection.createRange().duplicate();
var start, end;
if (offsets.end === undefined) {
start = offsets.start;
end = start;
} else if (offsets.start > offsets.end) {
start = offsets.end;
end = offsets.start;
} else {
start = offsets.start;
end = offsets.end;
}
range.moveToElementText(node);
range.moveStart('character', start);
range.setEndPoint('EndToStart', range);
range.moveEnd('character', end - start);
range.select();
}
/**
* In modern non-IE browsers, we can support both forward and backward
* selections.
*
* Note: IE10+ supports the Selection object, but it does not support
* the `extend` method, which means that even in modern IE, it's not possible
* to programmatically create a backward selection. Thus, for all IE
* versions, we use the old IE API to create our selections.
*
* @param {DOMElement|DOMTextNode} node
* @param {object} offsets
*/
function setModernOffsets(node, offsets) {
if (!window.getSelection) {
return;
}
var selection = window.getSelection();
var length = node[getTextContentAccessor()].length;
var start = Math.min(offsets.start, length);
var end = offsets.end === undefined ? start : Math.min(offsets.end, length);
// IE 11 uses modern selection, but doesn't support the extend method.
// Flip backward selections, so we can set with a single range.
if (!selection.extend && start > end) {
var temp = end;
end = start;
start = temp;
}
var startMarker = getNodeForCharacterOffset(node, start);
var endMarker = getNodeForCharacterOffset(node, end);
if (startMarker && endMarker) {
var range = document.createRange();
range.setStart(startMarker.node, startMarker.offset);
selection.removeAllRanges();
if (start > end) {
selection.addRange(range);
selection.extend(endMarker.node, endMarker.offset);
} else {
range.setEnd(endMarker.node, endMarker.offset);
selection.addRange(range);
}
}
}
var useIEOffsets = ExecutionEnvironment.canUseDOM && 'selection' in document && !('getSelection' in window);
var ReactDOMSelection = {
/**
* @param {DOMElement} node
*/
getOffsets: useIEOffsets ? getIEOffsets : getModernOffsets,
/**
* @param {DOMElement|DOMTextNode} node
* @param {object} offsets
*/
setOffsets: useIEOffsets ? setIEOffsets : setModernOffsets
};
module.exports = ReactDOMSelection;
},{"./getNodeForCharacterOffset":146,"./getTextContentAccessor":147,"fbjs/lib/ExecutionEnvironment":5}],78:[function(require,module,exports){
(function (process){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var _prodInvariant = require('./reactProdInvariant'),
_assign = require('object-assign');
var DOMChildrenOperations = require('./DOMChildrenOperations');
var DOMLazyTree = require('./DOMLazyTree');
var ReactDOMComponentTree = require('./ReactDOMComponentTree');
var escapeTextContentForBrowser = require('./escapeTextContentForBrowser');
var invariant = require('fbjs/lib/invariant');
var validateDOMNesting = require('./validateDOMNesting');
/**
* Text nodes violate a couple assumptions that React makes about components:
*
* - When mounting text into the DOM, adjacent text nodes are merged.
* - Text nodes cannot be assigned a React root ID.
*
* This component is used to wrap strings between comment nodes so that they
* can undergo the same reconciliation that is applied to elements.
*
* TODO: Investigate representing React components in the DOM with text nodes.
*
* @class ReactDOMTextComponent
* @extends ReactComponent
* @internal
*/
var ReactDOMTextComponent = function (text) {
// TODO: This is really a ReactText (ReactNode), not a ReactElement
this._currentElement = text;
this._stringText = '' + text;
// ReactDOMComponentTree uses these:
this._hostNode = null;
this._hostParent = null;
// Properties
this._domID = 0;
this._mountIndex = 0;
this._closingComment = null;
this._commentNodes = null;
};
_assign(ReactDOMTextComponent.prototype, {
/**
* Creates the markup for this text node. This node is not intended to have
* any features besides containing text content.
*
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @return {string} Markup for this text node.
* @internal
*/
mountComponent: function (transaction, hostParent, hostContainerInfo, context) {
if (process.env.NODE_ENV !== 'production') {
var parentInfo;
if (hostParent != null) {
parentInfo = hostParent._ancestorInfo;
} else if (hostContainerInfo != null) {
parentInfo = hostContainerInfo._ancestorInfo;
}
if (parentInfo) {
// parentInfo should always be present except for the top-level
// component when server rendering
validateDOMNesting(null, this._stringText, this, parentInfo);
}
}
var domID = hostContainerInfo._idCounter++;
var openingValue = ' react-text: ' + domID + ' ';
var closingValue = ' /react-text ';
this._domID = domID;
this._hostParent = hostParent;
if (transaction.useCreateElement) {
var ownerDocument = hostContainerInfo._ownerDocument;
var openingComment = ownerDocument.createComment(openingValue);
var closingComment = ownerDocument.createComment(closingValue);
var lazyTree = DOMLazyTree(ownerDocument.createDocumentFragment());
DOMLazyTree.queueChild(lazyTree, DOMLazyTree(openingComment));
if (this._stringText) {
DOMLazyTree.queueChild(lazyTree, DOMLazyTree(ownerDocument.createTextNode(this._stringText)));
}
DOMLazyTree.queueChild(lazyTree, DOMLazyTree(closingComment));
ReactDOMComponentTree.precacheNode(this, openingComment);
this._closingComment = closingComment;
return lazyTree;
} else {
var escapedText = escapeTextContentForBrowser(this._stringText);
if (transaction.renderToStaticMarkup) {
// Normally we'd wrap this between comment nodes for the reasons stated
// above, but since this is a situation where React won't take over
// (static pages), we can simply return the text as it is.
return escapedText;
}
return '<!--' + openingValue + '-->' + escapedText + '<!--' + closingValue + '-->';
}
},
/**
* Updates this component by updating the text content.
*
* @param {ReactText} nextText The next text content
* @param {ReactReconcileTransaction} transaction
* @internal
*/
receiveComponent: function (nextText, transaction) {
if (nextText !== this._currentElement) {
this._currentElement = nextText;
var nextStringText = '' + nextText;
if (nextStringText !== this._stringText) {
// TODO: Save this as pending props and use performUpdateIfNecessary
// and/or updateComponent to do the actual update for consistency with
// other component types?
this._stringText = nextStringText;
var commentNodes = this.getHostNode();
DOMChildrenOperations.replaceDelimitedText(commentNodes[0], commentNodes[1], nextStringText);
}
}
},
getHostNode: function () {
var hostNode = this._commentNodes;
if (hostNode) {
return hostNode;
}
if (!this._closingComment) {
var openingComment = ReactDOMComponentTree.getNodeFromInstance(this);
var node = openingComment.nextSibling;
while (true) {
!(node != null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Missing closing comment for text component %s', this._domID) : _prodInvariant('67', this._domID) : void 0;
if (node.nodeType === 8 && node.nodeValue === ' /react-text ') {
this._closingComment = node;
break;
}
node = node.nextSibling;
}
}
hostNode = [this._hostNode, this._closingComment];
this._commentNodes = hostNode;
return hostNode;
},
unmountComponent: function () {
this._closingComment = null;
this._commentNodes = null;
ReactDOMComponentTree.uncacheNode(this);
}
});
module.exports = ReactDOMTextComponent;
}).call(this,require('_process'))
},{"./DOMChildrenOperations":42,"./DOMLazyTree":43,"./ReactDOMComponentTree":67,"./escapeTextContentForBrowser":136,"./reactProdInvariant":153,"./validateDOMNesting":159,"_process":29,"fbjs/lib/invariant":19,"object-assign":28}],79:[function(require,module,exports){
(function (process){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var _prodInvariant = require('./reactProdInvariant'),
_assign = require('object-assign');
var LinkedValueUtils = require('./LinkedValueUtils');
var ReactDOMComponentTree = require('./ReactDOMComponentTree');
var ReactUpdates = require('./ReactUpdates');
var invariant = require('fbjs/lib/invariant');
var warning = require('fbjs/lib/warning');
var didWarnValueLink = false;
var didWarnValDefaultVal = false;
function forceUpdateIfMounted() {
if (this._rootNodeID) {
// DOM component is still mounted; update
ReactDOMTextarea.updateWrapper(this);
}
}
/**
* Implements a <textarea> host component that allows setting `value`, and
* `defaultValue`. This differs from the traditional DOM API because value is
* usually set as PCDATA children.
*
* If `value` is not supplied (or null/undefined), user actions that affect the
* value will trigger updates to the element.
*
* If `value` is supplied (and not null/undefined), the rendered element will
* not trigger updates to the element. Instead, the `value` prop must change in
* order for the rendered element to be updated.
*
* The rendered element will be initialized with an empty value, the prop
* `defaultValue` if specified, or the children content (deprecated).
*/
var ReactDOMTextarea = {
getHostProps: function (inst, props) {
!(props.dangerouslySetInnerHTML == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, '`dangerouslySetInnerHTML` does not make sense on <textarea>.') : _prodInvariant('91') : void 0;
// Always set children to the same thing. In IE9, the selection range will
// get reset if `textContent` is mutated. We could add a check in setTextContent
// to only set the value if/when the value differs from the node value (which would
// completely solve this IE9 bug), but Sebastian+Ben seemed to like this solution.
// The value can be a boolean or object so that's why it's forced to be a string.
var hostProps = _assign({}, props, {
value: undefined,
defaultValue: undefined,
children: '' + inst._wrapperState.initialValue,
onChange: inst._wrapperState.onChange
});
return hostProps;
},
mountWrapper: function (inst, props) {
if (process.env.NODE_ENV !== 'production') {
LinkedValueUtils.checkPropTypes('textarea', props, inst._currentElement._owner);
if (props.valueLink !== undefined && !didWarnValueLink) {
process.env.NODE_ENV !== 'production' ? warning(false, '`valueLink` prop on `textarea` is deprecated; set `value` and `onChange` instead.') : void 0;
didWarnValueLink = true;
}
if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValDefaultVal) {
process.env.NODE_ENV !== 'production' ? warning(false, 'Textarea elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled textarea ' + 'and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components') : void 0;
didWarnValDefaultVal = true;
}
}
var value = LinkedValueUtils.getValue(props);
var initialValue = value;
// Only bother fetching default value if we're going to use it
if (value == null) {
var defaultValue = props.defaultValue;
// TODO (yungsters): Remove support for children content in <textarea>.
var children = props.children;
if (children != null) {
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(false, 'Use the `defaultValue` or `value` props instead of setting ' + 'children on <textarea>.') : void 0;
}
!(defaultValue == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'If you supply `defaultValue` on a <textarea>, do not pass children.') : _prodInvariant('92') : void 0;
if (Array.isArray(children)) {
!(children.length <= 1) ? process.env.NODE_ENV !== 'production' ? invariant(false, '<textarea> can only have at most one child.') : _prodInvariant('93') : void 0;
children = children[0];
}
defaultValue = '' + children;
}
if (defaultValue == null) {
defaultValue = '';
}
initialValue = defaultValue;
}
inst._wrapperState = {
initialValue: '' + initialValue,
listeners: null,
onChange: _handleChange.bind(inst)
};
},
updateWrapper: function (inst) {
var props = inst._currentElement.props;
var node = ReactDOMComponentTree.getNodeFromInstance(inst);
var value = LinkedValueUtils.getValue(props);
if (value != null) {
// Cast `value` to a string to ensure the value is set correctly. While
// browsers typically do this as necessary, jsdom doesn't.
var newValue = '' + value;
// To avoid side effects (such as losing text selection), only set value if changed
if (newValue !== node.value) {
node.value = newValue;
}
if (props.defaultValue == null) {
node.defaultValue = newValue;
}
}
if (props.defaultValue != null) {
node.defaultValue = props.defaultValue;
}
},
postMountWrapper: function (inst) {
// This is in postMount because we need access to the DOM node, which is not
// available until after the component has mounted.
var node = ReactDOMComponentTree.getNodeFromInstance(inst);
var textContent = node.textContent;
// Only set node.value if textContent is equal to the expected
// initial value. In IE10/IE11 there is a bug where the placeholder attribute
// will populate textContent as well.
// https://developer.microsoft.com/microsoft-edge/platform/issues/101525/
if (textContent === inst._wrapperState.initialValue) {
node.value = textContent;
}
}
};
function _handleChange(event) {
var props = this._currentElement.props;
var returnValue = LinkedValueUtils.executeOnChange(props, event);
ReactUpdates.asap(forceUpdateIfMounted, this);
return returnValue;
}
module.exports = ReactDOMTextarea;
}).call(this,require('_process'))
},{"./LinkedValueUtils":57,"./ReactDOMComponentTree":67,"./ReactUpdates":111,"./reactProdInvariant":153,"_process":29,"fbjs/lib/invariant":19,"fbjs/lib/warning":26,"object-assign":28}],80:[function(require,module,exports){
(function (process){
/**
* Copyright 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var _prodInvariant = require('./reactProdInvariant');
var invariant = require('fbjs/lib/invariant');
/**
* Return the lowest common ancestor of A and B, or null if they are in
* different trees.
*/
function getLowestCommonAncestor(instA, instB) {
!('_hostNode' in instA) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'getNodeFromInstance: Invalid argument.') : _prodInvariant('33') : void 0;
!('_hostNode' in instB) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'getNodeFromInstance: Invalid argument.') : _prodInvariant('33') : void 0;
var depthA = 0;
for (var tempA = instA; tempA; tempA = tempA._hostParent) {
depthA++;
}
var depthB = 0;
for (var tempB = instB; tempB; tempB = tempB._hostParent) {
depthB++;
}
// If A is deeper, crawl up.
while (depthA - depthB > 0) {
instA = instA._hostParent;
depthA--;
}
// If B is deeper, crawl up.
while (depthB - depthA > 0) {
instB = instB._hostParent;
depthB--;
}
// Walk in lockstep until we find a match.
var depth = depthA;
while (depth--) {
if (instA === instB) {
return instA;
}
instA = instA._hostParent;
instB = instB._hostParent;
}
return null;
}
/**
* Return if A is an ancestor of B.
*/
function isAncestor(instA, instB) {
!('_hostNode' in instA) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'isAncestor: Invalid argument.') : _prodInvariant('35') : void 0;
!('_hostNode' in instB) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'isAncestor: Invalid argument.') : _prodInvariant('35') : void 0;
while (instB) {
if (instB === instA) {
return true;
}
instB = instB._hostParent;
}
return false;
}
/**
* Return the parent instance of the passed-in instance.
*/
function getParentInstance(inst) {
!('_hostNode' in inst) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'getParentInstance: Invalid argument.') : _prodInvariant('36') : void 0;
return inst._hostParent;
}
/**
* Simulates the traversal of a two-phase, capture/bubble event dispatch.
*/
function traverseTwoPhase(inst, fn, arg) {
var path = [];
while (inst) {
path.push(inst);
inst = inst._hostParent;
}
var i;
for (i = path.length; i-- > 0;) {
fn(path[i], 'captured', arg);
}
for (i = 0; i < path.length; i++) {
fn(path[i], 'bubbled', arg);
}
}
/**
* Traverses the ID hierarchy and invokes the supplied `cb` on any IDs that
* should would receive a `mouseEnter` or `mouseLeave` event.
*
* Does not invoke the callback on the nearest common ancestor because nothing
* "entered" or "left" that element.
*/
function traverseEnterLeave(from, to, fn, argFrom, argTo) {
var common = from && to ? getLowestCommonAncestor(from, to) : null;
var pathFrom = [];
while (from && from !== common) {
pathFrom.push(from);
from = from._hostParent;
}
var pathTo = [];
while (to && to !== common) {
pathTo.push(to);
to = to._hostParent;
}
var i;
for (i = 0; i < pathFrom.length; i++) {
fn(pathFrom[i], 'bubbled', argFrom);
}
for (i = pathTo.length; i-- > 0;) {
fn(pathTo[i], 'captured', argTo);
}
}
module.exports = {
isAncestor: isAncestor,
getLowestCommonAncestor: getLowestCommonAncestor,
getParentInstance: getParentInstance,
traverseTwoPhase: traverseTwoPhase,
traverseEnterLeave: traverseEnterLeave
};
}).call(this,require('_process'))
},{"./reactProdInvariant":153,"_process":29,"fbjs/lib/invariant":19}],81:[function(require,module,exports){
(function (process){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var DOMProperty = require('./DOMProperty');
var EventPluginRegistry = require('./EventPluginRegistry');
var ReactComponentTreeHook = require('react/lib/ReactComponentTreeHook');
var warning = require('fbjs/lib/warning');
if (process.env.NODE_ENV !== 'production') {
var reactProps = {
children: true,
dangerouslySetInnerHTML: true,
key: true,
ref: true,
autoFocus: true,
defaultValue: true,
valueLink: true,
defaultChecked: true,
checkedLink: true,
innerHTML: true,
suppressContentEditableWarning: true,
onFocusIn: true,
onFocusOut: true
};
var warnedProperties = {};
var validateProperty = function (tagName, name, debugID) {
if (DOMProperty.properties.hasOwnProperty(name) || DOMProperty.isCustomAttribute(name)) {
return true;
}
if (reactProps.hasOwnProperty(name) && reactProps[name] || warnedProperties.hasOwnProperty(name) && warnedProperties[name]) {
return true;
}
if (EventPluginRegistry.registrationNameModules.hasOwnProperty(name)) {
return true;
}
warnedProperties[name] = true;
var lowerCasedName = name.toLowerCase();
// data-* attributes should be lowercase; suggest the lowercase version
var standardName = DOMProperty.isCustomAttribute(lowerCasedName) ? lowerCasedName : DOMProperty.getPossibleStandardName.hasOwnProperty(lowerCasedName) ? DOMProperty.getPossibleStandardName[lowerCasedName] : null;
var registrationName = EventPluginRegistry.possibleRegistrationNames.hasOwnProperty(lowerCasedName) ? EventPluginRegistry.possibleRegistrationNames[lowerCasedName] : null;
if (standardName != null) {
process.env.NODE_ENV !== 'production' ? warning(false, 'Unknown DOM property %s. Did you mean %s?%s', name, standardName, ReactComponentTreeHook.getStackAddendumByID(debugID)) : void 0;
return true;
} else if (registrationName != null) {
process.env.NODE_ENV !== 'production' ? warning(false, 'Unknown event handler property %s. Did you mean `%s`?%s', name, registrationName, ReactComponentTreeHook.getStackAddendumByID(debugID)) : void 0;
return true;
} else {
// We were unable to guess which prop the user intended.
// It is likely that the user was just blindly spreading/forwarding props
// Components should be careful to only render valid props/attributes.
// Warning will be invoked in warnUnknownProperties to allow grouping.
return false;
}
};
}
var warnUnknownProperties = function (debugID, element) {
var unknownProps = [];
for (var key in element.props) {
var isValid = validateProperty(element.type, key, debugID);
if (!isValid) {
unknownProps.push(key);
}
}
var unknownPropString = unknownProps.map(function (prop) {
return '`' + prop + '`';
}).join(', ');
if (unknownProps.length === 1) {
process.env.NODE_ENV !== 'production' ? warning(false, 'Unknown prop %s on <%s> tag. Remove this prop from the element. ' + 'For details, see https://fb.me/react-unknown-prop%s', unknownPropString, element.type, ReactComponentTreeHook.getStackAddendumByID(debugID)) : void 0;
} else if (unknownProps.length > 1) {
process.env.NODE_ENV !== 'production' ? warning(false, 'Unknown props %s on <%s> tag. Remove these props from the element. ' + 'For details, see https://fb.me/react-unknown-prop%s', unknownPropString, element.type, ReactComponentTreeHook.getStackAddendumByID(debugID)) : void 0;
}
};
function handleElement(debugID, element) {
if (element == null || typeof element.type !== 'string') {
return;
}
if (element.type.indexOf('-') >= 0 || element.props.is) {
return;
}
warnUnknownProperties(debugID, element);
}
var ReactDOMUnknownPropertyHook = {
onBeforeMountComponent: function (debugID, element) {
handleElement(debugID, element);
},
onBeforeUpdateComponent: function (debugID, element) {
handleElement(debugID, element);
}
};
module.exports = ReactDOMUnknownPropertyHook;
}).call(this,require('_process'))
},{"./DOMProperty":45,"./EventPluginRegistry":51,"_process":29,"fbjs/lib/warning":26,"react/lib/ReactComponentTreeHook":168}],82:[function(require,module,exports){
(function (process){
/**
* Copyright 2016-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
'use strict';
var ReactInvalidSetStateWarningHook = require('./ReactInvalidSetStateWarningHook');
var ReactHostOperationHistoryHook = require('./ReactHostOperationHistoryHook');
var ReactComponentTreeHook = require('react/lib/ReactComponentTreeHook');
var ExecutionEnvironment = require('fbjs/lib/ExecutionEnvironment');
var performanceNow = require('fbjs/lib/performanceNow');
var warning = require('fbjs/lib/warning');
var hooks = [];
var didHookThrowForEvent = {};
function callHook(event, fn, context, arg1, arg2, arg3, arg4, arg5) {
try {
fn.call(context, arg1, arg2, arg3, arg4, arg5);
} catch (e) {
process.env.NODE_ENV !== 'production' ? warning(didHookThrowForEvent[event], 'Exception thrown by hook while handling %s: %s', event, e + '\n' + e.stack) : void 0;
didHookThrowForEvent[event] = true;
}
}
function emitEvent(event, arg1, arg2, arg3, arg4, arg5) {
for (var i = 0; i < hooks.length; i++) {
var hook = hooks[i];
var fn = hook[event];
if (fn) {
callHook(event, fn, hook, arg1, arg2, arg3, arg4, arg5);
}
}
}
var isProfiling = false;
var flushHistory = [];
var lifeCycleTimerStack = [];
var currentFlushNesting = 0;
var currentFlushMeasurements = [];
var currentFlushStartTime = 0;
var currentTimerDebugID = null;
var currentTimerStartTime = 0;
var currentTimerNestedFlushDuration = 0;
var currentTimerType = null;
var lifeCycleTimerHasWarned = false;
function clearHistory() {
ReactComponentTreeHook.purgeUnmountedComponents();
ReactHostOperationHistoryHook.clearHistory();
}
function getTreeSnapshot(registeredIDs) {
return registeredIDs.reduce(function (tree, id) {
var ownerID = ReactComponentTreeHook.getOwnerID(id);
var parentID = ReactComponentTreeHook.getParentID(id);
tree[id] = {
displayName: ReactComponentTreeHook.getDisplayName(id),
text: ReactComponentTreeHook.getText(id),
updateCount: ReactComponentTreeHook.getUpdateCount(id),
childIDs: ReactComponentTreeHook.getChildIDs(id),
// Text nodes don't have owners but this is close enough.
ownerID: ownerID || parentID && ReactComponentTreeHook.getOwnerID(parentID) || 0,
parentID: parentID
};
return tree;
}, {});
}
function resetMeasurements() {
var previousStartTime = currentFlushStartTime;
var previousMeasurements = currentFlushMeasurements;
var previousOperations = ReactHostOperationHistoryHook.getHistory();
if (currentFlushNesting === 0) {
currentFlushStartTime = 0;
currentFlushMeasurements = [];
clearHistory();
return;
}
if (previousMeasurements.length || previousOperations.length) {
var registeredIDs = ReactComponentTreeHook.getRegisteredIDs();
flushHistory.push({
duration: performanceNow() - previousStartTime,
measurements: previousMeasurements || [],
operations: previousOperations || [],
treeSnapshot: getTreeSnapshot(registeredIDs)
});
}
clearHistory();
currentFlushStartTime = performanceNow();
currentFlushMeasurements = [];
}
function checkDebugID(debugID) {
var allowRoot = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
if (allowRoot && debugID === 0) {
return;
}
if (!debugID) {
process.env.NODE_ENV !== 'production' ? warning(false, 'ReactDebugTool: debugID may not be empty.') : void 0;
}
}
function beginLifeCycleTimer(debugID, timerType) {
if (currentFlushNesting === 0) {
return;
}
if (currentTimerType && !lifeCycleTimerHasWarned) {
process.env.NODE_ENV !== 'production' ? warning(false, 'There is an internal error in the React performance measurement code. ' + 'Did not expect %s timer to start while %s timer is still in ' + 'progress for %s instance.', timerType, currentTimerType || 'no', debugID === currentTimerDebugID ? 'the same' : 'another') : void 0;
lifeCycleTimerHasWarned = true;
}
currentTimerStartTime = performanceNow();
currentTimerNestedFlushDuration = 0;
currentTimerDebugID = debugID;
currentTimerType = timerType;
}
function endLifeCycleTimer(debugID, timerType) {
if (currentFlushNesting === 0) {
return;
}
if (currentTimerType !== timerType && !lifeCycleTimerHasWarned) {
process.env.NODE_ENV !== 'production' ? warning(false, 'There is an internal error in the React performance measurement code. ' + 'We did not expect %s timer to stop while %s timer is still in ' + 'progress for %s instance. Please report this as a bug in React.', timerType, currentTimerType || 'no', debugID === currentTimerDebugID ? 'the same' : 'another') : void 0;
lifeCycleTimerHasWarned = true;
}
if (isProfiling) {
currentFlushMeasurements.push({
timerType: timerType,
instanceID: debugID,
duration: performanceNow() - currentTimerStartTime - currentTimerNestedFlushDuration
});
}
currentTimerStartTime = 0;
currentTimerNestedFlushDuration = 0;
currentTimerDebugID = null;
currentTimerType = null;
}
function pauseCurrentLifeCycleTimer() {
var currentTimer = {
startTime: currentTimerStartTime,
nestedFlushStartTime: performanceNow(),
debugID: currentTimerDebugID,
timerType: currentTimerType
};
lifeCycleTimerStack.push(currentTimer);
currentTimerStartTime = 0;
currentTimerNestedFlushDuration = 0;
currentTimerDebugID = null;
currentTimerType = null;
}
function resumeCurrentLifeCycleTimer() {
var _lifeCycleTimerStack$ = lifeCycleTimerStack.pop(),
startTime = _lifeCycleTimerStack$.startTime,
nestedFlushStartTime = _lifeCycleTimerStack$.nestedFlushStartTime,
debugID = _lifeCycleTimerStack$.debugID,
timerType = _lifeCycleTimerStack$.timerType;
var nestedFlushDuration = performanceNow() - nestedFlushStartTime;
currentTimerStartTime = startTime;
currentTimerNestedFlushDuration += nestedFlushDuration;
currentTimerDebugID = debugID;
currentTimerType = timerType;
}
var lastMarkTimeStamp = 0;
var canUsePerformanceMeasure = typeof performance !== 'undefined' && typeof performance.mark === 'function' && typeof performance.clearMarks === 'function' && typeof performance.measure === 'function' && typeof performance.clearMeasures === 'function';
function shouldMark(debugID) {
if (!isProfiling || !canUsePerformanceMeasure) {
return false;
}
var element = ReactComponentTreeHook.getElement(debugID);
if (element == null || typeof element !== 'object') {
return false;
}
var isHostElement = typeof element.type === 'string';
if (isHostElement) {
return false;
}
return true;
}
function markBegin(debugID, markType) {
if (!shouldMark(debugID)) {
return;
}
var markName = debugID + '::' + markType;
lastMarkTimeStamp = performanceNow();
performance.mark(markName);
}
function markEnd(debugID, markType) {
if (!shouldMark(debugID)) {
return;
}
var markName = debugID + '::' + markType;
var displayName = ReactComponentTreeHook.getDisplayName(debugID) || 'Unknown';
// Chrome has an issue of dropping markers recorded too fast:
// https://bugs.chromium.org/p/chromium/issues/detail?id=640652
// To work around this, we will not report very small measurements.
// I determined the magic number by tweaking it back and forth.
// 0.05ms was enough to prevent the issue, but I set it to 0.1ms to be safe.
// When the bug is fixed, we can `measure()` unconditionally if we want to.
var timeStamp = performanceNow();
if (timeStamp - lastMarkTimeStamp > 0.1) {
var measurementName = displayName + ' [' + markType + ']';
performance.measure(measurementName, markName);
}
performance.clearMarks(markName);
performance.clearMeasures(measurementName);
}
var ReactDebugTool = {
addHook: function (hook) {
hooks.push(hook);
},
removeHook: function (hook) {
for (var i = 0; i < hooks.length; i++) {
if (hooks[i] === hook) {
hooks.splice(i, 1);
i--;
}
}
},
isProfiling: function () {
return isProfiling;
},
beginProfiling: function () {
if (isProfiling) {
return;
}
isProfiling = true;
flushHistory.length = 0;
resetMeasurements();
ReactDebugTool.addHook(ReactHostOperationHistoryHook);
},
endProfiling: function () {
if (!isProfiling) {
return;
}
isProfiling = false;
resetMeasurements();
ReactDebugTool.removeHook(ReactHostOperationHistoryHook);
},
getFlushHistory: function () {
return flushHistory;
},
onBeginFlush: function () {
currentFlushNesting++;
resetMeasurements();
pauseCurrentLifeCycleTimer();
emitEvent('onBeginFlush');
},
onEndFlush: function () {
resetMeasurements();
currentFlushNesting--;
resumeCurrentLifeCycleTimer();
emitEvent('onEndFlush');
},
onBeginLifeCycleTimer: function (debugID, timerType) {
checkDebugID(debugID);
emitEvent('onBeginLifeCycleTimer', debugID, timerType);
markBegin(debugID, timerType);
beginLifeCycleTimer(debugID, timerType);
},
onEndLifeCycleTimer: function (debugID, timerType) {
checkDebugID(debugID);
endLifeCycleTimer(debugID, timerType);
markEnd(debugID, timerType);
emitEvent('onEndLifeCycleTimer', debugID, timerType);
},
onBeginProcessingChildContext: function () {
emitEvent('onBeginProcessingChildContext');
},
onEndProcessingChildContext: function () {
emitEvent('onEndProcessingChildContext');
},
onHostOperation: function (operation) {
checkDebugID(operation.instanceID);
emitEvent('onHostOperation', operation);
},
onSetState: function () {
emitEvent('onSetState');
},
onSetChildren: function (debugID, childDebugIDs) {
checkDebugID(debugID);
childDebugIDs.forEach(checkDebugID);
emitEvent('onSetChildren', debugID, childDebugIDs);
},
onBeforeMountComponent: function (debugID, element, parentDebugID) {
checkDebugID(debugID);
checkDebugID(parentDebugID, true);
emitEvent('onBeforeMountComponent', debugID, element, parentDebugID);
markBegin(debugID, 'mount');
},
onMountComponent: function (debugID) {
checkDebugID(debugID);
markEnd(debugID, 'mount');
emitEvent('onMountComponent', debugID);
},
onBeforeUpdateComponent: function (debugID, element) {
checkDebugID(debugID);
emitEvent('onBeforeUpdateComponent', debugID, element);
markBegin(debugID, 'update');
},
onUpdateComponent: function (debugID) {
checkDebugID(debugID);
markEnd(debugID, 'update');
emitEvent('onUpdateComponent', debugID);
},
onBeforeUnmountComponent: function (debugID) {
checkDebugID(debugID);
emitEvent('onBeforeUnmountComponent', debugID);
markBegin(debugID, 'unmount');
},
onUnmountComponent: function (debugID) {
checkDebugID(debugID);
markEnd(debugID, 'unmount');
emitEvent('onUnmountComponent', debugID);
},
onTestEvent: function () {
emitEvent('onTestEvent');
}
};
// TODO remove these when RN/www gets updated
ReactDebugTool.addDevtool = ReactDebugTool.addHook;
ReactDebugTool.removeDevtool = ReactDebugTool.removeHook;
ReactDebugTool.addHook(ReactInvalidSetStateWarningHook);
ReactDebugTool.addHook(ReactComponentTreeHook);
var url = ExecutionEnvironment.canUseDOM && window.location.href || '';
if (/[?&]react_perf\b/.test(url)) {
ReactDebugTool.beginProfiling();
}
module.exports = ReactDebugTool;
}).call(this,require('_process'))
},{"./ReactHostOperationHistoryHook":92,"./ReactInvalidSetStateWarningHook":97,"_process":29,"fbjs/lib/ExecutionEnvironment":5,"fbjs/lib/performanceNow":24,"fbjs/lib/warning":26,"react/lib/ReactComponentTreeHook":168}],83:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var _assign = require('object-assign');
var ReactUpdates = require('./ReactUpdates');
var Transaction = require('./Transaction');
var emptyFunction = require('fbjs/lib/emptyFunction');
var RESET_BATCHED_UPDATES = {
initialize: emptyFunction,
close: function () {
ReactDefaultBatchingStrategy.isBatchingUpdates = false;
}
};
var FLUSH_BATCHED_UPDATES = {
initialize: emptyFunction,
close: ReactUpdates.flushBatchedUpdates.bind(ReactUpdates)
};
var TRANSACTION_WRAPPERS = [FLUSH_BATCHED_UPDATES, RESET_BATCHED_UPDATES];
function ReactDefaultBatchingStrategyTransaction() {
this.reinitializeTransaction();
}
_assign(ReactDefaultBatchingStrategyTransaction.prototype, Transaction, {
getTransactionWrappers: function () {
return TRANSACTION_WRAPPERS;
}
});
var transaction = new ReactDefaultBatchingStrategyTransaction();
var ReactDefaultBatchingStrategy = {
isBatchingUpdates: false,
/**
* Call the provided function in a context within which calls to `setState`
* and friends are batched such that components aren't updated unnecessarily.
*/
batchedUpdates: function (callback, a, b, c, d, e) {
var alreadyBatchingUpdates = ReactDefaultBatchingStrategy.isBatchingUpdates;
ReactDefaultBatchingStrategy.isBatchingUpdates = true;
// The code is written this way to avoid extra allocations
if (alreadyBatchingUpdates) {
return callback(a, b, c, d, e);
} else {
return transaction.perform(callback, null, a, b, c, d, e);
}
}
};
module.exports = ReactDefaultBatchingStrategy;
},{"./ReactUpdates":111,"./Transaction":129,"fbjs/lib/emptyFunction":11,"object-assign":28}],84:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var ARIADOMPropertyConfig = require('./ARIADOMPropertyConfig');
var BeforeInputEventPlugin = require('./BeforeInputEventPlugin');
var ChangeEventPlugin = require('./ChangeEventPlugin');
var DefaultEventPluginOrder = require('./DefaultEventPluginOrder');
var EnterLeaveEventPlugin = require('./EnterLeaveEventPlugin');
var HTMLDOMPropertyConfig = require('./HTMLDOMPropertyConfig');
var ReactComponentBrowserEnvironment = require('./ReactComponentBrowserEnvironment');
var ReactDOMComponent = require('./ReactDOMComponent');
var ReactDOMComponentTree = require('./ReactDOMComponentTree');
var ReactDOMEmptyComponent = require('./ReactDOMEmptyComponent');
var ReactDOMTreeTraversal = require('./ReactDOMTreeTraversal');
var ReactDOMTextComponent = require('./ReactDOMTextComponent');
var ReactDefaultBatchingStrategy = require('./ReactDefaultBatchingStrategy');
var ReactEventListener = require('./ReactEventListener');
var ReactInjection = require('./ReactInjection');
var ReactReconcileTransaction = require('./ReactReconcileTransaction');
var SVGDOMPropertyConfig = require('./SVGDOMPropertyConfig');
var SelectEventPlugin = require('./SelectEventPlugin');
var SimpleEventPlugin = require('./SimpleEventPlugin');
var alreadyInjected = false;
function inject() {
if (alreadyInjected) {
// TODO: This is currently true because these injections are shared between
// the client and the server package. They should be built independently
// and not share any injection state. Then this problem will be solved.
return;
}
alreadyInjected = true;
ReactInjection.EventEmitter.injectReactEventListener(ReactEventListener);
/**
* Inject modules for resolving DOM hierarchy and plugin ordering.
*/
ReactInjection.EventPluginHub.injectEventPluginOrder(DefaultEventPluginOrder);
ReactInjection.EventPluginUtils.injectComponentTree(ReactDOMComponentTree);
ReactInjection.EventPluginUtils.injectTreeTraversal(ReactDOMTreeTraversal);
/**
* Some important event plugins included by default (without having to require
* them).
*/
ReactInjection.EventPluginHub.injectEventPluginsByName({
SimpleEventPlugin: SimpleEventPlugin,
EnterLeaveEventPlugin: EnterLeaveEventPlugin,
ChangeEventPlugin: ChangeEventPlugin,
SelectEventPlugin: SelectEventPlugin,
BeforeInputEventPlugin: BeforeInputEventPlugin
});
ReactInjection.HostComponent.injectGenericComponentClass(ReactDOMComponent);
ReactInjection.HostComponent.injectTextComponentClass(ReactDOMTextComponent);
ReactInjection.DOMProperty.injectDOMPropertyConfig(ARIADOMPropertyConfig);
ReactInjection.DOMProperty.injectDOMPropertyConfig(HTMLDOMPropertyConfig);
ReactInjection.DOMProperty.injectDOMPropertyConfig(SVGDOMPropertyConfig);
ReactInjection.EmptyComponent.injectEmptyComponentFactory(function (instantiate) {
return new ReactDOMEmptyComponent(instantiate);
});
ReactInjection.Updates.injectReconcileTransaction(ReactReconcileTransaction);
ReactInjection.Updates.injectBatchingStrategy(ReactDefaultBatchingStrategy);
ReactInjection.Component.injectEnvironment(ReactComponentBrowserEnvironment);
}
module.exports = {
inject: inject
};
},{"./ARIADOMPropertyConfig":35,"./BeforeInputEventPlugin":37,"./ChangeEventPlugin":41,"./DefaultEventPluginOrder":48,"./EnterLeaveEventPlugin":49,"./HTMLDOMPropertyConfig":55,"./ReactComponentBrowserEnvironment":61,"./ReactDOMComponent":65,"./ReactDOMComponentTree":67,"./ReactDOMEmptyComponent":69,"./ReactDOMTextComponent":78,"./ReactDOMTreeTraversal":80,"./ReactDefaultBatchingStrategy":83,"./ReactEventListener":89,"./ReactInjection":93,"./ReactReconcileTransaction":105,"./SVGDOMPropertyConfig":113,"./SelectEventPlugin":114,"./SimpleEventPlugin":115}],85:[function(require,module,exports){
/**
* Copyright 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
'use strict';
// The Symbol used to tag the ReactElement type. If there is no native Symbol
// nor polyfill, then a plain number is used for performance.
var REACT_ELEMENT_TYPE = typeof Symbol === 'function' && Symbol['for'] && Symbol['for']('react.element') || 0xeac7;
module.exports = REACT_ELEMENT_TYPE;
},{}],86:[function(require,module,exports){
/**
* Copyright 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var emptyComponentFactory;
var ReactEmptyComponentInjection = {
injectEmptyComponentFactory: function (factory) {
emptyComponentFactory = factory;
}
};
var ReactEmptyComponent = {
create: function (instantiate) {
return emptyComponentFactory(instantiate);
}
};
ReactEmptyComponent.injection = ReactEmptyComponentInjection;
module.exports = ReactEmptyComponent;
},{}],87:[function(require,module,exports){
(function (process){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
'use strict';
var caughtError = null;
/**
* Call a function while guarding against errors that happens within it.
*
* @param {String} name of the guard to use for logging or debugging
* @param {Function} func The function to invoke
* @param {*} a First argument
* @param {*} b Second argument
*/
function invokeGuardedCallback(name, func, a) {
try {
func(a);
} catch (x) {
if (caughtError === null) {
caughtError = x;
}
}
}
var ReactErrorUtils = {
invokeGuardedCallback: invokeGuardedCallback,
/**
* Invoked by ReactTestUtils.Simulate so that any errors thrown by the event
* handler are sure to be rethrown by rethrowCaughtError.
*/
invokeGuardedCallbackWithCatch: invokeGuardedCallback,
/**
* During execution of guarded functions we will capture the first error which
* we will rethrow to be handled by the top level error handler.
*/
rethrowCaughtError: function () {
if (caughtError) {
var error = caughtError;
caughtError = null;
throw error;
}
}
};
if (process.env.NODE_ENV !== 'production') {
/**
* To help development we can get better devtools integration by simulating a
* real browser event.
*/
if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function' && typeof document !== 'undefined' && typeof document.createEvent === 'function') {
var fakeNode = document.createElement('react');
ReactErrorUtils.invokeGuardedCallback = function (name, func, a) {
var boundFunc = func.bind(null, a);
var evtType = 'react-' + name;
fakeNode.addEventListener(evtType, boundFunc, false);
var evt = document.createEvent('Event');
evt.initEvent(evtType, false, false);
fakeNode.dispatchEvent(evt);
fakeNode.removeEventListener(evtType, boundFunc, false);
};
}
}
module.exports = ReactErrorUtils;
}).call(this,require('_process'))
},{"_process":29}],88:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var EventPluginHub = require('./EventPluginHub');
function runEventQueueInBatch(events) {
EventPluginHub.enqueueEvents(events);
EventPluginHub.processEventQueue(false);
}
var ReactEventEmitterMixin = {
/**
* Streams a fired top-level event to `EventPluginHub` where plugins have the
* opportunity to create `ReactEvent`s to be dispatched.
*/
handleTopLevel: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) {
var events = EventPluginHub.extractEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget);
runEventQueueInBatch(events);
}
};
module.exports = ReactEventEmitterMixin;
},{"./EventPluginHub":50}],89:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var _assign = require('object-assign');
var EventListener = require('fbjs/lib/EventListener');
var ExecutionEnvironment = require('fbjs/lib/ExecutionEnvironment');
var PooledClass = require('./PooledClass');
var ReactDOMComponentTree = require('./ReactDOMComponentTree');
var ReactUpdates = require('./ReactUpdates');
var getEventTarget = require('./getEventTarget');
var getUnboundedScrollPosition = require('fbjs/lib/getUnboundedScrollPosition');
/**
* Find the deepest React component completely containing the root of the
* passed-in instance (for use when entire React trees are nested within each
* other). If React trees are not nested, returns null.
*/
function findParent(inst) {
// TODO: It may be a good idea to cache this to prevent unnecessary DOM
// traversal, but caching is difficult to do correctly without using a
// mutation observer to listen for all DOM changes.
while (inst._hostParent) {
inst = inst._hostParent;
}
var rootNode = ReactDOMComponentTree.getNodeFromInstance(inst);
var container = rootNode.parentNode;
return ReactDOMComponentTree.getClosestInstanceFromNode(container);
}
// Used to store ancestor hierarchy in top level callback
function TopLevelCallbackBookKeeping(topLevelType, nativeEvent) {
this.topLevelType = topLevelType;
this.nativeEvent = nativeEvent;
this.ancestors = [];
}
_assign(TopLevelCallbackBookKeeping.prototype, {
destructor: function () {
this.topLevelType = null;
this.nativeEvent = null;
this.ancestors.length = 0;
}
});
PooledClass.addPoolingTo(TopLevelCallbackBookKeeping, PooledClass.twoArgumentPooler);
function handleTopLevelImpl(bookKeeping) {
var nativeEventTarget = getEventTarget(bookKeeping.nativeEvent);
var targetInst = ReactDOMComponentTree.getClosestInstanceFromNode(nativeEventTarget);
// Loop through the hierarchy, in case there's any nested components.
// It's important that we build the array of ancestors before calling any
// event handlers, because event handlers can modify the DOM, leading to
// inconsistencies with ReactMount's node cache. See #1105.
var ancestor = targetInst;
do {
bookKeeping.ancestors.push(ancestor);
ancestor = ancestor && findParent(ancestor);
} while (ancestor);
for (var i = 0; i < bookKeeping.ancestors.length; i++) {
targetInst = bookKeeping.ancestors[i];
ReactEventListener._handleTopLevel(bookKeeping.topLevelType, targetInst, bookKeeping.nativeEvent, getEventTarget(bookKeeping.nativeEvent));
}
}
function scrollValueMonitor(cb) {
var scrollPosition = getUnboundedScrollPosition(window);
cb(scrollPosition);
}
var ReactEventListener = {
_enabled: true,
_handleTopLevel: null,
WINDOW_HANDLE: ExecutionEnvironment.canUseDOM ? window : null,
setHandleTopLevel: function (handleTopLevel) {
ReactEventListener._handleTopLevel = handleTopLevel;
},
setEnabled: function (enabled) {
ReactEventListener._enabled = !!enabled;
},
isEnabled: function () {
return ReactEventListener._enabled;
},
/**
* Traps top-level events by using event bubbling.
*
* @param {string} topLevelType Record from `EventConstants`.
* @param {string} handlerBaseName Event name (e.g. "click").
* @param {object} element Element on which to attach listener.
* @return {?object} An object with a remove function which will forcefully
* remove the listener.
* @internal
*/
trapBubbledEvent: function (topLevelType, handlerBaseName, element) {
if (!element) {
return null;
}
return EventListener.listen(element, handlerBaseName, ReactEventListener.dispatchEvent.bind(null, topLevelType));
},
/**
* Traps a top-level event by using event capturing.
*
* @param {string} topLevelType Record from `EventConstants`.
* @param {string} handlerBaseName Event name (e.g. "click").
* @param {object} element Element on which to attach listener.
* @return {?object} An object with a remove function which will forcefully
* remove the listener.
* @internal
*/
trapCapturedEvent: function (topLevelType, handlerBaseName, element) {
if (!element) {
return null;
}
return EventListener.capture(element, handlerBaseName, ReactEventListener.dispatchEvent.bind(null, topLevelType));
},
monitorScrollValue: function (refresh) {
var callback = scrollValueMonitor.bind(null, refresh);
EventListener.listen(window, 'scroll', callback);
},
dispatchEvent: function (topLevelType, nativeEvent) {
if (!ReactEventListener._enabled) {
return;
}
var bookKeeping = TopLevelCallbackBookKeeping.getPooled(topLevelType, nativeEvent);
try {
// Event queue being processed in the same cycle allows
// `preventDefault`.
ReactUpdates.batchedUpdates(handleTopLevelImpl, bookKeeping);
} finally {
TopLevelCallbackBookKeeping.release(bookKeeping);
}
}
};
module.exports = ReactEventListener;
},{"./PooledClass":58,"./ReactDOMComponentTree":67,"./ReactUpdates":111,"./getEventTarget":143,"fbjs/lib/EventListener":4,"fbjs/lib/ExecutionEnvironment":5,"fbjs/lib/getUnboundedScrollPosition":16,"object-assign":28}],90:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
'use strict';
var ReactFeatureFlags = {
// When true, call console.time() before and .timeEnd() after each top-level
// render (both initial renders and updates). Useful when looking at prod-mode
// timeline profiles in Chrome, for example.
logTopLevelRenders: false
};
module.exports = ReactFeatureFlags;
},{}],91:[function(require,module,exports){
(function (process){
/**
* Copyright 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var _prodInvariant = require('./reactProdInvariant');
var invariant = require('fbjs/lib/invariant');
var genericComponentClass = null;
var textComponentClass = null;
var ReactHostComponentInjection = {
// This accepts a class that receives the tag string. This is a catch all
// that can render any kind of tag.
injectGenericComponentClass: function (componentClass) {
genericComponentClass = componentClass;
},
// This accepts a text component class that takes the text string to be
// rendered as props.
injectTextComponentClass: function (componentClass) {
textComponentClass = componentClass;
}
};
/**
* Get a host internal component class for a specific tag.
*
* @param {ReactElement} element The element to create.
* @return {function} The internal class constructor function.
*/
function createInternalComponent(element) {
!genericComponentClass ? process.env.NODE_ENV !== 'production' ? invariant(false, 'There is no registered component for the tag %s', element.type) : _prodInvariant('111', element.type) : void 0;
return new genericComponentClass(element);
}
/**
* @param {ReactText} text
* @return {ReactComponent}
*/
function createInstanceForText(text) {
return new textComponentClass(text);
}
/**
* @param {ReactComponent} component
* @return {boolean}
*/
function isTextComponent(component) {
return component instanceof textComponentClass;
}
var ReactHostComponent = {
createInternalComponent: createInternalComponent,
createInstanceForText: createInstanceForText,
isTextComponent: isTextComponent,
injection: ReactHostComponentInjection
};
module.exports = ReactHostComponent;
}).call(this,require('_process'))
},{"./reactProdInvariant":153,"_process":29,"fbjs/lib/invariant":19}],92:[function(require,module,exports){
/**
* Copyright 2016-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
'use strict';
var history = [];
var ReactHostOperationHistoryHook = {
onHostOperation: function (operation) {
history.push(operation);
},
clearHistory: function () {
if (ReactHostOperationHistoryHook._preventClearing) {
// Should only be used for tests.
return;
}
history = [];
},
getHistory: function () {
return history;
}
};
module.exports = ReactHostOperationHistoryHook;
},{}],93:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var DOMProperty = require('./DOMProperty');
var EventPluginHub = require('./EventPluginHub');
var EventPluginUtils = require('./EventPluginUtils');
var ReactComponentEnvironment = require('./ReactComponentEnvironment');
var ReactEmptyComponent = require('./ReactEmptyComponent');
var ReactBrowserEventEmitter = require('./ReactBrowserEventEmitter');
var ReactHostComponent = require('./ReactHostComponent');
var ReactUpdates = require('./ReactUpdates');
var ReactInjection = {
Component: ReactComponentEnvironment.injection,
DOMProperty: DOMProperty.injection,
EmptyComponent: ReactEmptyComponent.injection,
EventPluginHub: EventPluginHub.injection,
EventPluginUtils: EventPluginUtils.injection,
EventEmitter: ReactBrowserEventEmitter.injection,
HostComponent: ReactHostComponent.injection,
Updates: ReactUpdates.injection
};
module.exports = ReactInjection;
},{"./DOMProperty":45,"./EventPluginHub":50,"./EventPluginUtils":52,"./ReactBrowserEventEmitter":59,"./ReactComponentEnvironment":62,"./ReactEmptyComponent":86,"./ReactHostComponent":91,"./ReactUpdates":111}],94:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var ReactDOMSelection = require('./ReactDOMSelection');
var containsNode = require('fbjs/lib/containsNode');
var focusNode = require('fbjs/lib/focusNode');
var getActiveElement = require('fbjs/lib/getActiveElement');
function isInDocument(node) {
return containsNode(document.documentElement, node);
}
/**
* @ReactInputSelection: React input selection module. Based on Selection.js,
* but modified to be suitable for react and has a couple of bug fixes (doesn't
* assume buttons have range selections allowed).
* Input selection module for React.
*/
var ReactInputSelection = {
hasSelectionCapabilities: function (elem) {
var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();
return nodeName && (nodeName === 'input' && elem.type === 'text' || nodeName === 'textarea' || elem.contentEditable === 'true');
},
getSelectionInformation: function () {
var focusedElem = getActiveElement();
return {
focusedElem: focusedElem,
selectionRange: ReactInputSelection.hasSelectionCapabilities(focusedElem) ? ReactInputSelection.getSelection(focusedElem) : null
};
},
/**
* @restoreSelection: If any selection information was potentially lost,
* restore it. This is useful when performing operations that could remove dom
* nodes and place them back in, resulting in focus being lost.
*/
restoreSelection: function (priorSelectionInformation) {
var curFocusedElem = getActiveElement();
var priorFocusedElem = priorSelectionInformation.focusedElem;
var priorSelectionRange = priorSelectionInformation.selectionRange;
if (curFocusedElem !== priorFocusedElem && isInDocument(priorFocusedElem)) {
if (ReactInputSelection.hasSelectionCapabilities(priorFocusedElem)) {
ReactInputSelection.setSelection(priorFocusedElem, priorSelectionRange);
}
focusNode(priorFocusedElem);
}
},
/**
* @getSelection: Gets the selection bounds of a focused textarea, input or
* contentEditable node.
* -@input: Look up selection bounds of this input
* -@return {start: selectionStart, end: selectionEnd}
*/
getSelection: function (input) {
var selection;
if ('selectionStart' in input) {
// Modern browser with input or textarea.
selection = {
start: input.selectionStart,
end: input.selectionEnd
};
} else if (document.selection && input.nodeName && input.nodeName.toLowerCase() === 'input') {
// IE8 input.
var range = document.selection.createRange();
// There can only be one selection per document in IE, so it must
// be in our element.
if (range.parentElement() === input) {
selection = {
start: -range.moveStart('character', -input.value.length),
end: -range.moveEnd('character', -input.value.length)
};
}
} else {
// Content editable or old IE textarea.
selection = ReactDOMSelection.getOffsets(input);
}
return selection || { start: 0, end: 0 };
},
/**
* @setSelection: Sets the selection bounds of a textarea or input and focuses
* the input.
* -@input Set selection bounds of this input or textarea
* -@offsets Object of same form that is returned from get*
*/
setSelection: function (input, offsets) {
var start = offsets.start;
var end = offsets.end;
if (end === undefined) {
end = start;
}
if ('selectionStart' in input) {
input.selectionStart = start;
input.selectionEnd = Math.min(end, input.value.length);
} else if (document.selection && input.nodeName && input.nodeName.toLowerCase() === 'input') {
var range = input.createTextRange();
range.collapse(true);
range.moveStart('character', start);
range.moveEnd('character', end - start);
range.select();
} else {
ReactDOMSelection.setOffsets(input, offsets);
}
}
};
module.exports = ReactInputSelection;
},{"./ReactDOMSelection":77,"fbjs/lib/containsNode":8,"fbjs/lib/focusNode":13,"fbjs/lib/getActiveElement":14}],95:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
/**
* `ReactInstanceMap` maintains a mapping from a public facing stateful
* instance (key) and the internal representation (value). This allows public
* methods to accept the user facing instance as an argument and map them back
* to internal methods.
*/
// TODO: Replace this with ES6: var ReactInstanceMap = new Map();
var ReactInstanceMap = {
/**
* This API should be called `delete` but we'd have to make sure to always
* transform these to strings for IE support. When this transform is fully
* supported we can rename it.
*/
remove: function (key) {
key._reactInternalInstance = undefined;
},
get: function (key) {
return key._reactInternalInstance;
},
has: function (key) {
return key._reactInternalInstance !== undefined;
},
set: function (key, value) {
key._reactInternalInstance = value;
}
};
module.exports = ReactInstanceMap;
},{}],96:[function(require,module,exports){
(function (process){
/**
* Copyright 2016-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
'use strict';
// Trust the developer to only use ReactInstrumentation with a __DEV__ check
var debugTool = null;
if (process.env.NODE_ENV !== 'production') {
var ReactDebugTool = require('./ReactDebugTool');
debugTool = ReactDebugTool;
}
module.exports = { debugTool: debugTool };
}).call(this,require('_process'))
},{"./ReactDebugTool":82,"_process":29}],97:[function(require,module,exports){
(function (process){
/**
* Copyright 2016-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
'use strict';
var warning = require('fbjs/lib/warning');
if (process.env.NODE_ENV !== 'production') {
var processingChildContext = false;
var warnInvalidSetState = function () {
process.env.NODE_ENV !== 'production' ? warning(!processingChildContext, 'setState(...): Cannot call setState() inside getChildContext()') : void 0;
};
}
var ReactInvalidSetStateWarningHook = {
onBeginProcessingChildContext: function () {
processingChildContext = true;
},
onEndProcessingChildContext: function () {
processingChildContext = false;
},
onSetState: function () {
warnInvalidSetState();
}
};
module.exports = ReactInvalidSetStateWarningHook;
}).call(this,require('_process'))
},{"_process":29,"fbjs/lib/warning":26}],98:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var adler32 = require('./adler32');
var TAG_END = /\/?>/;
var COMMENT_START = /^<\!\-\-/;
var ReactMarkupChecksum = {
CHECKSUM_ATTR_NAME: 'data-react-checksum',
/**
* @param {string} markup Markup string
* @return {string} Markup string with checksum attribute attached
*/
addChecksumToMarkup: function (markup) {
var checksum = adler32(markup);
// Add checksum (handle both parent tags, comments and self-closing tags)
if (COMMENT_START.test(markup)) {
return markup;
} else {
return markup.replace(TAG_END, ' ' + ReactMarkupChecksum.CHECKSUM_ATTR_NAME + '="' + checksum + '"$&');
}
},
/**
* @param {string} markup to use
* @param {DOMElement} element root React element
* @returns {boolean} whether or not the markup is the same
*/
canReuseMarkup: function (markup, element) {
var existingChecksum = element.getAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME);
existingChecksum = existingChecksum && parseInt(existingChecksum, 10);
var markupChecksum = adler32(markup);
return markupChecksum === existingChecksum;
}
};
module.exports = ReactMarkupChecksum;
},{"./adler32":132}],99:[function(require,module,exports){
(function (process){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var _prodInvariant = require('./reactProdInvariant');
var DOMLazyTree = require('./DOMLazyTree');
var DOMProperty = require('./DOMProperty');
var React = require('react/lib/React');
var ReactBrowserEventEmitter = require('./ReactBrowserEventEmitter');
var ReactCurrentOwner = require('react/lib/ReactCurrentOwner');
var ReactDOMComponentTree = require('./ReactDOMComponentTree');
var ReactDOMContainerInfo = require('./ReactDOMContainerInfo');
var ReactDOMFeatureFlags = require('./ReactDOMFeatureFlags');
var ReactFeatureFlags = require('./ReactFeatureFlags');
var ReactInstanceMap = require('./ReactInstanceMap');
var ReactInstrumentation = require('./ReactInstrumentation');
var ReactMarkupChecksum = require('./ReactMarkupChecksum');
var ReactReconciler = require('./ReactReconciler');
var ReactUpdateQueue = require('./ReactUpdateQueue');
var ReactUpdates = require('./ReactUpdates');
var emptyObject = require('fbjs/lib/emptyObject');
var instantiateReactComponent = require('./instantiateReactComponent');
var invariant = require('fbjs/lib/invariant');
var setInnerHTML = require('./setInnerHTML');
var shouldUpdateReactComponent = require('./shouldUpdateReactComponent');
var warning = require('fbjs/lib/warning');
var ATTR_NAME = DOMProperty.ID_ATTRIBUTE_NAME;
var ROOT_ATTR_NAME = DOMProperty.ROOT_ATTRIBUTE_NAME;
var ELEMENT_NODE_TYPE = 1;
var DOC_NODE_TYPE = 9;
var DOCUMENT_FRAGMENT_NODE_TYPE = 11;
var instancesByReactRootID = {};
/**
* Finds the index of the first character
* that's not common between the two given strings.
*
* @return {number} the index of the character where the strings diverge
*/
function firstDifferenceIndex(string1, string2) {
var minLen = Math.min(string1.length, string2.length);
for (var i = 0; i < minLen; i++) {
if (string1.charAt(i) !== string2.charAt(i)) {
return i;
}
}
return string1.length === string2.length ? -1 : minLen;
}
/**
* @param {DOMElement|DOMDocument} container DOM element that may contain
* a React component
* @return {?*} DOM element that may have the reactRoot ID, or null.
*/
function getReactRootElementInContainer(container) {
if (!container) {
return null;
}
if (container.nodeType === DOC_NODE_TYPE) {
return container.documentElement;
} else {
return container.firstChild;
}
}
function internalGetID(node) {
// If node is something like a window, document, or text node, none of
// which support attributes or a .getAttribute method, gracefully return
// the empty string, as if the attribute were missing.
return node.getAttribute && node.getAttribute(ATTR_NAME) || '';
}
/**
* Mounts this component and inserts it into the DOM.
*
* @param {ReactComponent} componentInstance The instance to mount.
* @param {DOMElement} container DOM element to mount into.
* @param {ReactReconcileTransaction} transaction
* @param {boolean} shouldReuseMarkup If true, do not insert markup
*/
function mountComponentIntoNode(wrapperInstance, container, transaction, shouldReuseMarkup, context) {
var markerName;
if (ReactFeatureFlags.logTopLevelRenders) {
var wrappedElement = wrapperInstance._currentElement.props.child;
var type = wrappedElement.type;
markerName = 'React mount: ' + (typeof type === 'string' ? type : type.displayName || type.name);
console.time(markerName);
}
var markup = ReactReconciler.mountComponent(wrapperInstance, transaction, null, ReactDOMContainerInfo(wrapperInstance, container), context, 0 /* parentDebugID */
);
if (markerName) {
console.timeEnd(markerName);
}
wrapperInstance._renderedComponent._topLevelWrapper = wrapperInstance;
ReactMount._mountImageIntoNode(markup, container, wrapperInstance, shouldReuseMarkup, transaction);
}
/**
* Batched mount.
*
* @param {ReactComponent} componentInstance The instance to mount.
* @param {DOMElement} container DOM element to mount into.
* @param {boolean} shouldReuseMarkup If true, do not insert markup
*/
function batchedMountComponentIntoNode(componentInstance, container, shouldReuseMarkup, context) {
var transaction = ReactUpdates.ReactReconcileTransaction.getPooled(
/* useCreateElement */
!shouldReuseMarkup && ReactDOMFeatureFlags.useCreateElement);
transaction.perform(mountComponentIntoNode, null, componentInstance, container, transaction, shouldReuseMarkup, context);
ReactUpdates.ReactReconcileTransaction.release(transaction);
}
/**
* Unmounts a component and removes it from the DOM.
*
* @param {ReactComponent} instance React component instance.
* @param {DOMElement} container DOM element to unmount from.
* @final
* @internal
* @see {ReactMount.unmountComponentAtNode}
*/
function unmountComponentFromNode(instance, container, safely) {
if (process.env.NODE_ENV !== 'production') {
ReactInstrumentation.debugTool.onBeginFlush();
}
ReactReconciler.unmountComponent(instance, safely);
if (process.env.NODE_ENV !== 'production') {
ReactInstrumentation.debugTool.onEndFlush();
}
if (container.nodeType === DOC_NODE_TYPE) {
container = container.documentElement;
}
// http://jsperf.com/emptying-a-node
while (container.lastChild) {
container.removeChild(container.lastChild);
}
}
/**
* True if the supplied DOM node has a direct React-rendered child that is
* not a React root element. Useful for warning in `render`,
* `unmountComponentAtNode`, etc.
*
* @param {?DOMElement} node The candidate DOM node.
* @return {boolean} True if the DOM element contains a direct child that was
* rendered by React but is not a root element.
* @internal
*/
function hasNonRootReactChild(container) {
var rootEl = getReactRootElementInContainer(container);
if (rootEl) {
var inst = ReactDOMComponentTree.getInstanceFromNode(rootEl);
return !!(inst && inst._hostParent);
}
}
/**
* True if the supplied DOM node is a React DOM element and
* it has been rendered by another copy of React.
*
* @param {?DOMElement} node The candidate DOM node.
* @return {boolean} True if the DOM has been rendered by another copy of React
* @internal
*/
function nodeIsRenderedByOtherInstance(container) {
var rootEl = getReactRootElementInContainer(container);
return !!(rootEl && isReactNode(rootEl) && !ReactDOMComponentTree.getInstanceFromNode(rootEl));
}
/**
* True if the supplied DOM node is a valid node element.
*
* @param {?DOMElement} node The candidate DOM node.
* @return {boolean} True if the DOM is a valid DOM node.
* @internal
*/
function isValidContainer(node) {
return !!(node && (node.nodeType === ELEMENT_NODE_TYPE || node.nodeType === DOC_NODE_TYPE || node.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE));
}
/**
* True if the supplied DOM node is a valid React node element.
*
* @param {?DOMElement} node The candidate DOM node.
* @return {boolean} True if the DOM is a valid React DOM node.
* @internal
*/
function isReactNode(node) {
return isValidContainer(node) && (node.hasAttribute(ROOT_ATTR_NAME) || node.hasAttribute(ATTR_NAME));
}
function getHostRootInstanceInContainer(container) {
var rootEl = getReactRootElementInContainer(container);
var prevHostInstance = rootEl && ReactDOMComponentTree.getInstanceFromNode(rootEl);
return prevHostInstance && !prevHostInstance._hostParent ? prevHostInstance : null;
}
function getTopLevelWrapperInContainer(container) {
var root = getHostRootInstanceInContainer(container);
return root ? root._hostContainerInfo._topLevelWrapper : null;
}
/**
* Temporary (?) hack so that we can store all top-level pending updates on
* composites instead of having to worry about different types of components
* here.
*/
var topLevelRootCounter = 1;
var TopLevelWrapper = function () {
this.rootID = topLevelRootCounter++;
};
TopLevelWrapper.prototype.isReactComponent = {};
if (process.env.NODE_ENV !== 'production') {
TopLevelWrapper.displayName = 'TopLevelWrapper';
}
TopLevelWrapper.prototype.render = function () {
return this.props.child;
};
TopLevelWrapper.isReactTopLevelWrapper = true;
/**
* Mounting is the process of initializing a React component by creating its
* representative DOM elements and inserting them into a supplied `container`.
* Any prior content inside `container` is destroyed in the process.
*
* ReactMount.render(
* component,
* document.getElementById('container')
* );
*
* <div id="container"> <-- Supplied `container`.
* <div data-reactid=".3"> <-- Rendered reactRoot of React
* // ... component.
* </div>
* </div>
*
* Inside of `container`, the first element rendered is the "reactRoot".
*/
var ReactMount = {
TopLevelWrapper: TopLevelWrapper,
/**
* Used by devtools. The keys are not important.
*/
_instancesByReactRootID: instancesByReactRootID,
/**
* This is a hook provided to support rendering React components while
* ensuring that the apparent scroll position of its `container` does not
* change.
*
* @param {DOMElement} container The `container` being rendered into.
* @param {function} renderCallback This must be called once to do the render.
*/
scrollMonitor: function (container, renderCallback) {
renderCallback();
},
/**
* Take a component that's already mounted into the DOM and replace its props
* @param {ReactComponent} prevComponent component instance already in the DOM
* @param {ReactElement} nextElement component instance to render
* @param {DOMElement} container container to render into
* @param {?function} callback function triggered on completion
*/
_updateRootComponent: function (prevComponent, nextElement, nextContext, container, callback) {
ReactMount.scrollMonitor(container, function () {
ReactUpdateQueue.enqueueElementInternal(prevComponent, nextElement, nextContext);
if (callback) {
ReactUpdateQueue.enqueueCallbackInternal(prevComponent, callback);
}
});
return prevComponent;
},
/**
* Render a new component into the DOM. Hooked by hooks!
*
* @param {ReactElement} nextElement element to render
* @param {DOMElement} container container to render into
* @param {boolean} shouldReuseMarkup if we should skip the markup insertion
* @return {ReactComponent} nextComponent
*/
_renderNewRootComponent: function (nextElement, container, shouldReuseMarkup, context) {
// Various parts of our code (such as ReactCompositeComponent's
// _renderValidatedComponent) assume that calls to render aren't nested;
// verify that that's the case.
process.env.NODE_ENV !== 'production' ? warning(ReactCurrentOwner.current == null, '_renderNewRootComponent(): Render methods should be a pure function ' + 'of props and state; triggering nested component updates from ' + 'render is not allowed. If necessary, trigger nested updates in ' + 'componentDidUpdate. Check the render method of %s.', ReactCurrentOwner.current && ReactCurrentOwner.current.getName() || 'ReactCompositeComponent') : void 0;
!isValidContainer(container) ? process.env.NODE_ENV !== 'production' ? invariant(false, '_registerComponent(...): Target container is not a DOM element.') : _prodInvariant('37') : void 0;
ReactBrowserEventEmitter.ensureScrollValueMonitoring();
var componentInstance = instantiateReactComponent(nextElement, false);
// The initial render is synchronous but any updates that happen during
// rendering, in componentWillMount or componentDidMount, will be batched
// according to the current batching strategy.
ReactUpdates.batchedUpdates(batchedMountComponentIntoNode, componentInstance, container, shouldReuseMarkup, context);
var wrapperID = componentInstance._instance.rootID;
instancesByReactRootID[wrapperID] = componentInstance;
return componentInstance;
},
/**
* Renders a React component into the DOM in the supplied `container`.
*
* If the React component was previously rendered into `container`, this will
* perform an update on it and only mutate the DOM as necessary to reflect the
* latest React component.
*
* @param {ReactComponent} parentComponent The conceptual parent of this render tree.
* @param {ReactElement} nextElement Component element to render.
* @param {DOMElement} container DOM element to render into.
* @param {?function} callback function triggered on completion
* @return {ReactComponent} Component instance rendered in `container`.
*/
renderSubtreeIntoContainer: function (parentComponent, nextElement, container, callback) {
!(parentComponent != null && ReactInstanceMap.has(parentComponent)) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'parentComponent must be a valid React Component') : _prodInvariant('38') : void 0;
return ReactMount._renderSubtreeIntoContainer(parentComponent, nextElement, container, callback);
},
_renderSubtreeIntoContainer: function (parentComponent, nextElement, container, callback) {
ReactUpdateQueue.validateCallback(callback, 'ReactDOM.render');
!React.isValidElement(nextElement) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactDOM.render(): Invalid component element.%s', typeof nextElement === 'string' ? ' Instead of passing a string like \'div\', pass ' + 'React.createElement(\'div\') or <div />.' : typeof nextElement === 'function' ? ' Instead of passing a class like Foo, pass ' + 'React.createElement(Foo) or <Foo />.' :
// Check if it quacks like an element
nextElement != null && nextElement.props !== undefined ? ' This may be caused by unintentionally loading two independent ' + 'copies of React.' : '') : _prodInvariant('39', typeof nextElement === 'string' ? ' Instead of passing a string like \'div\', pass ' + 'React.createElement(\'div\') or <div />.' : typeof nextElement === 'function' ? ' Instead of passing a class like Foo, pass ' + 'React.createElement(Foo) or <Foo />.' : nextElement != null && nextElement.props !== undefined ? ' This may be caused by unintentionally loading two independent ' + 'copies of React.' : '') : void 0;
process.env.NODE_ENV !== 'production' ? warning(!container || !container.tagName || container.tagName.toUpperCase() !== 'BODY', 'render(): Rendering components directly into document.body is ' + 'discouraged, since its children are often manipulated by third-party ' + 'scripts and browser extensions. This may lead to subtle ' + 'reconciliation issues. Try rendering into a container element created ' + 'for your app.') : void 0;
var nextWrappedElement = React.createElement(TopLevelWrapper, { child: nextElement });
var nextContext;
if (parentComponent) {
var parentInst = ReactInstanceMap.get(parentComponent);
nextContext = parentInst._processChildContext(parentInst._context);
} else {
nextContext = emptyObject;
}
var prevComponent = getTopLevelWrapperInContainer(container);
if (prevComponent) {
var prevWrappedElement = prevComponent._currentElement;
var prevElement = prevWrappedElement.props.child;
if (shouldUpdateReactComponent(prevElement, nextElement)) {
var publicInst = prevComponent._renderedComponent.getPublicInstance();
var updatedCallback = callback && function () {
callback.call(publicInst);
};
ReactMount._updateRootComponent(prevComponent, nextWrappedElement, nextContext, container, updatedCallback);
return publicInst;
} else {
ReactMount.unmountComponentAtNode(container);
}
}
var reactRootElement = getReactRootElementInContainer(container);
var containerHasReactMarkup = reactRootElement && !!internalGetID(reactRootElement);
var containerHasNonRootReactChild = hasNonRootReactChild(container);
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(!containerHasNonRootReactChild, 'render(...): Replacing React-rendered children with a new root ' + 'component. If you intended to update the children of this node, ' + 'you should instead have the existing children update their state ' + 'and render the new components instead of calling ReactDOM.render.') : void 0;
if (!containerHasReactMarkup || reactRootElement.nextSibling) {
var rootElementSibling = reactRootElement;
while (rootElementSibling) {
if (internalGetID(rootElementSibling)) {
process.env.NODE_ENV !== 'production' ? warning(false, 'render(): Target node has markup rendered by React, but there ' + 'are unrelated nodes as well. This is most commonly caused by ' + 'white-space inserted around server-rendered markup.') : void 0;
break;
}
rootElementSibling = rootElementSibling.nextSibling;
}
}
}
var shouldReuseMarkup = containerHasReactMarkup && !prevComponent && !containerHasNonRootReactChild;
var component = ReactMount._renderNewRootComponent(nextWrappedElement, container, shouldReuseMarkup, nextContext)._renderedComponent.getPublicInstance();
if (callback) {
callback.call(component);
}
return component;
},
/**
* Renders a React component into the DOM in the supplied `container`.
* See https://facebook.github.io/react/docs/top-level-api.html#reactdom.render
*
* If the React component was previously rendered into `container`, this will
* perform an update on it and only mutate the DOM as necessary to reflect the
* latest React component.
*
* @param {ReactElement} nextElement Component element to render.
* @param {DOMElement} container DOM element to render into.
* @param {?function} callback function triggered on completion
* @return {ReactComponent} Component instance rendered in `container`.
*/
render: function (nextElement, container, callback) {
return ReactMount._renderSubtreeIntoContainer(null, nextElement, container, callback);
},
/**
* Unmounts and destroys the React component rendered in the `container`.
* See https://facebook.github.io/react/docs/top-level-api.html#reactdom.unmountcomponentatnode
*
* @param {DOMElement} container DOM element containing a React component.
* @return {boolean} True if a component was found in and unmounted from
* `container`
*/
unmountComponentAtNode: function (container) {
// Various parts of our code (such as ReactCompositeComponent's
// _renderValidatedComponent) assume that calls to render aren't nested;
// verify that that's the case. (Strictly speaking, unmounting won't cause a
// render but we still don't expect to be in a render call here.)
process.env.NODE_ENV !== 'production' ? warning(ReactCurrentOwner.current == null, 'unmountComponentAtNode(): Render methods should be a pure function ' + 'of props and state; triggering nested component updates from render ' + 'is not allowed. If necessary, trigger nested updates in ' + 'componentDidUpdate. Check the render method of %s.', ReactCurrentOwner.current && ReactCurrentOwner.current.getName() || 'ReactCompositeComponent') : void 0;
!isValidContainer(container) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'unmountComponentAtNode(...): Target container is not a DOM element.') : _prodInvariant('40') : void 0;
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(!nodeIsRenderedByOtherInstance(container), 'unmountComponentAtNode(): The node you\'re attempting to unmount ' + 'was rendered by another copy of React.') : void 0;
}
var prevComponent = getTopLevelWrapperInContainer(container);
if (!prevComponent) {
// Check if the node being unmounted was rendered by React, but isn't a
// root node.
var containerHasNonRootReactChild = hasNonRootReactChild(container);
// Check if the container itself is a React root node.
var isContainerReactRoot = container.nodeType === 1 && container.hasAttribute(ROOT_ATTR_NAME);
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(!containerHasNonRootReactChild, 'unmountComponentAtNode(): The node you\'re attempting to unmount ' + 'was rendered by React and is not a top-level container. %s', isContainerReactRoot ? 'You may have accidentally passed in a React root node instead ' + 'of its container.' : 'Instead, have the parent component update its state and ' + 'rerender in order to remove this component.') : void 0;
}
return false;
}
delete instancesByReactRootID[prevComponent._instance.rootID];
ReactUpdates.batchedUpdates(unmountComponentFromNode, prevComponent, container, false);
return true;
},
_mountImageIntoNode: function (markup, container, instance, shouldReuseMarkup, transaction) {
!isValidContainer(container) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'mountComponentIntoNode(...): Target container is not valid.') : _prodInvariant('41') : void 0;
if (shouldReuseMarkup) {
var rootElement = getReactRootElementInContainer(container);
if (ReactMarkupChecksum.canReuseMarkup(markup, rootElement)) {
ReactDOMComponentTree.precacheNode(instance, rootElement);
return;
} else {
var checksum = rootElement.getAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME);
rootElement.removeAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME);
var rootMarkup = rootElement.outerHTML;
rootElement.setAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME, checksum);
var normalizedMarkup = markup;
if (process.env.NODE_ENV !== 'production') {
// because rootMarkup is retrieved from the DOM, various normalizations
// will have occurred which will not be present in `markup`. Here,
// insert markup into a <div> or <iframe> depending on the container
// type to perform the same normalizations before comparing.
var normalizer;
if (container.nodeType === ELEMENT_NODE_TYPE) {
normalizer = document.createElement('div');
normalizer.innerHTML = markup;
normalizedMarkup = normalizer.innerHTML;
} else {
normalizer = document.createElement('iframe');
document.body.appendChild(normalizer);
normalizer.contentDocument.write(markup);
normalizedMarkup = normalizer.contentDocument.documentElement.outerHTML;
document.body.removeChild(normalizer);
}
}
var diffIndex = firstDifferenceIndex(normalizedMarkup, rootMarkup);
var difference = ' (client) ' + normalizedMarkup.substring(diffIndex - 20, diffIndex + 20) + '\n (server) ' + rootMarkup.substring(diffIndex - 20, diffIndex + 20);
!(container.nodeType !== DOC_NODE_TYPE) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'You\'re trying to render a component to the document using server rendering but the checksum was invalid. This usually means you rendered a different component type or props on the client from the one on the server, or your render() methods are impure. React cannot handle this case due to cross-browser quirks by rendering at the document root. You should look for environment dependent code in your components and ensure the props are the same client and server side:\n%s', difference) : _prodInvariant('42', difference) : void 0;
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(false, 'React attempted to reuse markup in a container but the ' + 'checksum was invalid. This generally means that you are ' + 'using server rendering and the markup generated on the ' + 'server was not what the client was expecting. React injected ' + 'new markup to compensate which works but you have lost many ' + 'of the benefits of server rendering. Instead, figure out ' + 'why the markup being generated is different on the client ' + 'or server:\n%s', difference) : void 0;
}
}
}
!(container.nodeType !== DOC_NODE_TYPE) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'You\'re trying to render a component to the document but you didn\'t use server rendering. We can\'t do this without using server rendering due to cross-browser quirks. See ReactDOMServer.renderToString() for server rendering.') : _prodInvariant('43') : void 0;
if (transaction.useCreateElement) {
while (container.lastChild) {
container.removeChild(container.lastChild);
}
DOMLazyTree.insertTreeBefore(container, markup, null);
} else {
setInnerHTML(container, markup);
ReactDOMComponentTree.precacheNode(instance, container.firstChild);
}
if (process.env.NODE_ENV !== 'production') {
var hostNode = ReactDOMComponentTree.getInstanceFromNode(container.firstChild);
if (hostNode._debugID !== 0) {
ReactInstrumentation.debugTool.onHostOperation({
instanceID: hostNode._debugID,
type: 'mount',
payload: markup.toString()
});
}
}
}
};
module.exports = ReactMount;
}).call(this,require('_process'))
},{"./DOMLazyTree":43,"./DOMProperty":45,"./ReactBrowserEventEmitter":59,"./ReactDOMComponentTree":67,"./ReactDOMContainerInfo":68,"./ReactDOMFeatureFlags":70,"./ReactFeatureFlags":90,"./ReactInstanceMap":95,"./ReactInstrumentation":96,"./ReactMarkupChecksum":98,"./ReactReconciler":106,"./ReactUpdateQueue":110,"./ReactUpdates":111,"./instantiateReactComponent":149,"./reactProdInvariant":153,"./setInnerHTML":155,"./shouldUpdateReactComponent":157,"_process":29,"fbjs/lib/emptyObject":12,"fbjs/lib/invariant":19,"fbjs/lib/warning":26,"react/lib/React":165,"react/lib/ReactCurrentOwner":169}],100:[function(require,module,exports){
(function (process){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var _prodInvariant = require('./reactProdInvariant');
var ReactComponentEnvironment = require('./ReactComponentEnvironment');
var ReactInstanceMap = require('./ReactInstanceMap');
var ReactInstrumentation = require('./ReactInstrumentation');
var ReactCurrentOwner = require('react/lib/ReactCurrentOwner');
var ReactReconciler = require('./ReactReconciler');
var ReactChildReconciler = require('./ReactChildReconciler');
var emptyFunction = require('fbjs/lib/emptyFunction');
var flattenChildren = require('./flattenChildren');
var invariant = require('fbjs/lib/invariant');
/**
* Make an update for markup to be rendered and inserted at a supplied index.
*
* @param {string} markup Markup that renders into an element.
* @param {number} toIndex Destination index.
* @private
*/
function makeInsertMarkup(markup, afterNode, toIndex) {
// NOTE: Null values reduce hidden classes.
return {
type: 'INSERT_MARKUP',
content: markup,
fromIndex: null,
fromNode: null,
toIndex: toIndex,
afterNode: afterNode
};
}
/**
* Make an update for moving an existing element to another index.
*
* @param {number} fromIndex Source index of the existing element.
* @param {number} toIndex Destination index of the element.
* @private
*/
function makeMove(child, afterNode, toIndex) {
// NOTE: Null values reduce hidden classes.
return {
type: 'MOVE_EXISTING',
content: null,
fromIndex: child._mountIndex,
fromNode: ReactReconciler.getHostNode(child),
toIndex: toIndex,
afterNode: afterNode
};
}
/**
* Make an update for removing an element at an index.
*
* @param {number} fromIndex Index of the element to remove.
* @private
*/
function makeRemove(child, node) {
// NOTE: Null values reduce hidden classes.
return {
type: 'REMOVE_NODE',
content: null,
fromIndex: child._mountIndex,
fromNode: node,
toIndex: null,
afterNode: null
};
}
/**
* Make an update for setting the markup of a node.
*
* @param {string} markup Markup that renders into an element.
* @private
*/
function makeSetMarkup(markup) {
// NOTE: Null values reduce hidden classes.
return {
type: 'SET_MARKUP',
content: markup,
fromIndex: null,
fromNode: null,
toIndex: null,
afterNode: null
};
}
/**
* Make an update for setting the text content.
*
* @param {string} textContent Text content to set.
* @private
*/
function makeTextContent(textContent) {
// NOTE: Null values reduce hidden classes.
return {
type: 'TEXT_CONTENT',
content: textContent,
fromIndex: null,
fromNode: null,
toIndex: null,
afterNode: null
};
}
/**
* Push an update, if any, onto the queue. Creates a new queue if none is
* passed and always returns the queue. Mutative.
*/
function enqueue(queue, update) {
if (update) {
queue = queue || [];
queue.push(update);
}
return queue;
}
/**
* Processes any enqueued updates.
*
* @private
*/
function processQueue(inst, updateQueue) {
ReactComponentEnvironment.processChildrenUpdates(inst, updateQueue);
}
var setChildrenForInstrumentation = emptyFunction;
if (process.env.NODE_ENV !== 'production') {
var getDebugID = function (inst) {
if (!inst._debugID) {
// Check for ART-like instances. TODO: This is silly/gross.
var internal;
if (internal = ReactInstanceMap.get(inst)) {
inst = internal;
}
}
return inst._debugID;
};
setChildrenForInstrumentation = function (children) {
var debugID = getDebugID(this);
// TODO: React Native empty components are also multichild.
// This means they still get into this method but don't have _debugID.
if (debugID !== 0) {
ReactInstrumentation.debugTool.onSetChildren(debugID, children ? Object.keys(children).map(function (key) {
return children[key]._debugID;
}) : []);
}
};
}
/**
* ReactMultiChild are capable of reconciling multiple children.
*
* @class ReactMultiChild
* @internal
*/
var ReactMultiChild = {
/**
* Provides common functionality for components that must reconcile multiple
* children. This is used by `ReactDOMComponent` to mount, update, and
* unmount child components.
*
* @lends {ReactMultiChild.prototype}
*/
Mixin: {
_reconcilerInstantiateChildren: function (nestedChildren, transaction, context) {
if (process.env.NODE_ENV !== 'production') {
var selfDebugID = getDebugID(this);
if (this._currentElement) {
try {
ReactCurrentOwner.current = this._currentElement._owner;
return ReactChildReconciler.instantiateChildren(nestedChildren, transaction, context, selfDebugID);
} finally {
ReactCurrentOwner.current = null;
}
}
}
return ReactChildReconciler.instantiateChildren(nestedChildren, transaction, context);
},
_reconcilerUpdateChildren: function (prevChildren, nextNestedChildrenElements, mountImages, removedNodes, transaction, context) {
var nextChildren;
var selfDebugID = 0;
if (process.env.NODE_ENV !== 'production') {
selfDebugID = getDebugID(this);
if (this._currentElement) {
try {
ReactCurrentOwner.current = this._currentElement._owner;
nextChildren = flattenChildren(nextNestedChildrenElements, selfDebugID);
} finally {
ReactCurrentOwner.current = null;
}
ReactChildReconciler.updateChildren(prevChildren, nextChildren, mountImages, removedNodes, transaction, this, this._hostContainerInfo, context, selfDebugID);
return nextChildren;
}
}
nextChildren = flattenChildren(nextNestedChildrenElements, selfDebugID);
ReactChildReconciler.updateChildren(prevChildren, nextChildren, mountImages, removedNodes, transaction, this, this._hostContainerInfo, context, selfDebugID);
return nextChildren;
},
/**
* Generates a "mount image" for each of the supplied children. In the case
* of `ReactDOMComponent`, a mount image is a string of markup.
*
* @param {?object} nestedChildren Nested child maps.
* @return {array} An array of mounted representations.
* @internal
*/
mountChildren: function (nestedChildren, transaction, context) {
var children = this._reconcilerInstantiateChildren(nestedChildren, transaction, context);
this._renderedChildren = children;
var mountImages = [];
var index = 0;
for (var name in children) {
if (children.hasOwnProperty(name)) {
var child = children[name];
var selfDebugID = 0;
if (process.env.NODE_ENV !== 'production') {
selfDebugID = getDebugID(this);
}
var mountImage = ReactReconciler.mountComponent(child, transaction, this, this._hostContainerInfo, context, selfDebugID);
child._mountIndex = index++;
mountImages.push(mountImage);
}
}
if (process.env.NODE_ENV !== 'production') {
setChildrenForInstrumentation.call(this, children);
}
return mountImages;
},
/**
* Replaces any rendered children with a text content string.
*
* @param {string} nextContent String of content.
* @internal
*/
updateTextContent: function (nextContent) {
var prevChildren = this._renderedChildren;
// Remove any rendered children.
ReactChildReconciler.unmountChildren(prevChildren, false);
for (var name in prevChildren) {
if (prevChildren.hasOwnProperty(name)) {
!false ? process.env.NODE_ENV !== 'production' ? invariant(false, 'updateTextContent called on non-empty component.') : _prodInvariant('118') : void 0;
}
}
// Set new text content.
var updates = [makeTextContent(nextContent)];
processQueue(this, updates);
},
/**
* Replaces any rendered children with a markup string.
*
* @param {string} nextMarkup String of markup.
* @internal
*/
updateMarkup: function (nextMarkup) {
var prevChildren = this._renderedChildren;
// Remove any rendered children.
ReactChildReconciler.unmountChildren(prevChildren, false);
for (var name in prevChildren) {
if (prevChildren.hasOwnProperty(name)) {
!false ? process.env.NODE_ENV !== 'production' ? invariant(false, 'updateTextContent called on non-empty component.') : _prodInvariant('118') : void 0;
}
}
var updates = [makeSetMarkup(nextMarkup)];
processQueue(this, updates);
},
/**
* Updates the rendered children with new children.
*
* @param {?object} nextNestedChildrenElements Nested child element maps.
* @param {ReactReconcileTransaction} transaction
* @internal
*/
updateChildren: function (nextNestedChildrenElements, transaction, context) {
// Hook used by React ART
this._updateChildren(nextNestedChildrenElements, transaction, context);
},
/**
* @param {?object} nextNestedChildrenElements Nested child element maps.
* @param {ReactReconcileTransaction} transaction
* @final
* @protected
*/
_updateChildren: function (nextNestedChildrenElements, transaction, context) {
var prevChildren = this._renderedChildren;
var removedNodes = {};
var mountImages = [];
var nextChildren = this._reconcilerUpdateChildren(prevChildren, nextNestedChildrenElements, mountImages, removedNodes, transaction, context);
if (!nextChildren && !prevChildren) {
return;
}
var updates = null;
var name;
// `nextIndex` will increment for each child in `nextChildren`, but
// `lastIndex` will be the last index visited in `prevChildren`.
var nextIndex = 0;
var lastIndex = 0;
// `nextMountIndex` will increment for each newly mounted child.
var nextMountIndex = 0;
var lastPlacedNode = null;
for (name in nextChildren) {
if (!nextChildren.hasOwnProperty(name)) {
continue;
}
var prevChild = prevChildren && prevChildren[name];
var nextChild = nextChildren[name];
if (prevChild === nextChild) {
updates = enqueue(updates, this.moveChild(prevChild, lastPlacedNode, nextIndex, lastIndex));
lastIndex = Math.max(prevChild._mountIndex, lastIndex);
prevChild._mountIndex = nextIndex;
} else {
if (prevChild) {
// Update `lastIndex` before `_mountIndex` gets unset by unmounting.
lastIndex = Math.max(prevChild._mountIndex, lastIndex);
// The `removedNodes` loop below will actually remove the child.
}
// The child must be instantiated before it's mounted.
updates = enqueue(updates, this._mountChildAtIndex(nextChild, mountImages[nextMountIndex], lastPlacedNode, nextIndex, transaction, context));
nextMountIndex++;
}
nextIndex++;
lastPlacedNode = ReactReconciler.getHostNode(nextChild);
}
// Remove children that are no longer present.
for (name in removedNodes) {
if (removedNodes.hasOwnProperty(name)) {
updates = enqueue(updates, this._unmountChild(prevChildren[name], removedNodes[name]));
}
}
if (updates) {
processQueue(this, updates);
}
this._renderedChildren = nextChildren;
if (process.env.NODE_ENV !== 'production') {
setChildrenForInstrumentation.call(this, nextChildren);
}
},
/**
* Unmounts all rendered children. This should be used to clean up children
* when this component is unmounted. It does not actually perform any
* backend operations.
*
* @internal
*/
unmountChildren: function (safely) {
var renderedChildren = this._renderedChildren;
ReactChildReconciler.unmountChildren(renderedChildren, safely);
this._renderedChildren = null;
},
/**
* Moves a child component to the supplied index.
*
* @param {ReactComponent} child Component to move.
* @param {number} toIndex Destination index of the element.
* @param {number} lastIndex Last index visited of the siblings of `child`.
* @protected
*/
moveChild: function (child, afterNode, toIndex, lastIndex) {
// If the index of `child` is less than `lastIndex`, then it needs to
// be moved. Otherwise, we do not need to move it because a child will be
// inserted or moved before `child`.
if (child._mountIndex < lastIndex) {
return makeMove(child, afterNode, toIndex);
}
},
/**
* Creates a child component.
*
* @param {ReactComponent} child Component to create.
* @param {string} mountImage Markup to insert.
* @protected
*/
createChild: function (child, afterNode, mountImage) {
return makeInsertMarkup(mountImage, afterNode, child._mountIndex);
},
/**
* Removes a child component.
*
* @param {ReactComponent} child Child to remove.
* @protected
*/
removeChild: function (child, node) {
return makeRemove(child, node);
},
/**
* Mounts a child with the supplied name.
*
* NOTE: This is part of `updateChildren` and is here for readability.
*
* @param {ReactComponent} child Component to mount.
* @param {string} name Name of the child.
* @param {number} index Index at which to insert the child.
* @param {ReactReconcileTransaction} transaction
* @private
*/
_mountChildAtIndex: function (child, mountImage, afterNode, index, transaction, context) {
child._mountIndex = index;
return this.createChild(child, afterNode, mountImage);
},
/**
* Unmounts a rendered child.
*
* NOTE: This is part of `updateChildren` and is here for readability.
*
* @param {ReactComponent} child Component to unmount.
* @private
*/
_unmountChild: function (child, node) {
var update = this.removeChild(child, node);
child._mountIndex = null;
return update;
}
}
};
module.exports = ReactMultiChild;
}).call(this,require('_process'))
},{"./ReactChildReconciler":60,"./ReactComponentEnvironment":62,"./ReactInstanceMap":95,"./ReactInstrumentation":96,"./ReactReconciler":106,"./flattenChildren":138,"./reactProdInvariant":153,"_process":29,"fbjs/lib/emptyFunction":11,"fbjs/lib/invariant":19,"react/lib/ReactCurrentOwner":169}],101:[function(require,module,exports){
(function (process){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
'use strict';
var _prodInvariant = require('./reactProdInvariant');
var React = require('react/lib/React');
var invariant = require('fbjs/lib/invariant');
var ReactNodeTypes = {
HOST: 0,
COMPOSITE: 1,
EMPTY: 2,
getType: function (node) {
if (node === null || node === false) {
return ReactNodeTypes.EMPTY;
} else if (React.isValidElement(node)) {
if (typeof node.type === 'function') {
return ReactNodeTypes.COMPOSITE;
} else {
return ReactNodeTypes.HOST;
}
}
!false ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Unexpected node: %s', node) : _prodInvariant('26', node) : void 0;
}
};
module.exports = ReactNodeTypes;
}).call(this,require('_process'))
},{"./reactProdInvariant":153,"_process":29,"fbjs/lib/invariant":19,"react/lib/React":165}],102:[function(require,module,exports){
(function (process){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
'use strict';
var _prodInvariant = require('./reactProdInvariant');
var invariant = require('fbjs/lib/invariant');
/**
* @param {?object} object
* @return {boolean} True if `object` is a valid owner.
* @final
*/
function isValidOwner(object) {
return !!(object && typeof object.attachRef === 'function' && typeof object.detachRef === 'function');
}
/**
* ReactOwners are capable of storing references to owned components.
*
* All components are capable of //being// referenced by owner components, but
* only ReactOwner components are capable of //referencing// owned components.
* The named reference is known as a "ref".
*
* Refs are available when mounted and updated during reconciliation.
*
* var MyComponent = React.createClass({
* render: function() {
* return (
* <div onClick={this.handleClick}>
* <CustomComponent ref="custom" />
* </div>
* );
* },
* handleClick: function() {
* this.refs.custom.handleClick();
* },
* componentDidMount: function() {
* this.refs.custom.initialize();
* }
* });
*
* Refs should rarely be used. When refs are used, they should only be done to
* control data that is not handled by React's data flow.
*
* @class ReactOwner
*/
var ReactOwner = {
/**
* Adds a component by ref to an owner component.
*
* @param {ReactComponent} component Component to reference.
* @param {string} ref Name by which to refer to the component.
* @param {ReactOwner} owner Component on which to record the ref.
* @final
* @internal
*/
addComponentAsRefTo: function (component, ref, owner) {
!isValidOwner(owner) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'addComponentAsRefTo(...): Only a ReactOwner can have refs. You might be adding a ref to a component that was not created inside a component\'s `render` method, or you have multiple copies of React loaded (details: https://fb.me/react-refs-must-have-owner).') : _prodInvariant('119') : void 0;
owner.attachRef(ref, component);
},
/**
* Removes a component by ref from an owner component.
*
* @param {ReactComponent} component Component to dereference.
* @param {string} ref Name of the ref to remove.
* @param {ReactOwner} owner Component on which the ref is recorded.
* @final
* @internal
*/
removeComponentAsRefFrom: function (component, ref, owner) {
!isValidOwner(owner) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'removeComponentAsRefFrom(...): Only a ReactOwner can have refs. You might be removing a ref to a component that was not created inside a component\'s `render` method, or you have multiple copies of React loaded (details: https://fb.me/react-refs-must-have-owner).') : _prodInvariant('120') : void 0;
var ownerPublicInstance = owner.getPublicInstance();
// Check that `component`'s owner is still alive and that `component` is still the current ref
// because we do not want to detach the ref if another component stole it.
if (ownerPublicInstance && ownerPublicInstance.refs[ref] === component.getPublicInstance()) {
owner.detachRef(ref);
}
}
};
module.exports = ReactOwner;
}).call(this,require('_process'))
},{"./reactProdInvariant":153,"_process":29,"fbjs/lib/invariant":19}],103:[function(require,module,exports){
(function (process){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
'use strict';
var ReactPropTypeLocationNames = {};
if (process.env.NODE_ENV !== 'production') {
ReactPropTypeLocationNames = {
prop: 'prop',
context: 'context',
childContext: 'child context'
};
}
module.exports = ReactPropTypeLocationNames;
}).call(this,require('_process'))
},{"_process":29}],104:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
'use strict';
var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';
module.exports = ReactPropTypesSecret;
},{}],105:[function(require,module,exports){
(function (process){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var _assign = require('object-assign');
var CallbackQueue = require('./CallbackQueue');
var PooledClass = require('./PooledClass');
var ReactBrowserEventEmitter = require('./ReactBrowserEventEmitter');
var ReactInputSelection = require('./ReactInputSelection');
var ReactInstrumentation = require('./ReactInstrumentation');
var Transaction = require('./Transaction');
var ReactUpdateQueue = require('./ReactUpdateQueue');
/**
* Ensures that, when possible, the selection range (currently selected text
* input) is not disturbed by performing the transaction.
*/
var SELECTION_RESTORATION = {
/**
* @return {Selection} Selection information.
*/
initialize: ReactInputSelection.getSelectionInformation,
/**
* @param {Selection} sel Selection information returned from `initialize`.
*/
close: ReactInputSelection.restoreSelection
};
/**
* Suppresses events (blur/focus) that could be inadvertently dispatched due to
* high level DOM manipulations (like temporarily removing a text input from the
* DOM).
*/
var EVENT_SUPPRESSION = {
/**
* @return {boolean} The enabled status of `ReactBrowserEventEmitter` before
* the reconciliation.
*/
initialize: function () {
var currentlyEnabled = ReactBrowserEventEmitter.isEnabled();
ReactBrowserEventEmitter.setEnabled(false);
return currentlyEnabled;
},
/**
* @param {boolean} previouslyEnabled Enabled status of
* `ReactBrowserEventEmitter` before the reconciliation occurred. `close`
* restores the previous value.
*/
close: function (previouslyEnabled) {
ReactBrowserEventEmitter.setEnabled(previouslyEnabled);
}
};
/**
* Provides a queue for collecting `componentDidMount` and
* `componentDidUpdate` callbacks during the transaction.
*/
var ON_DOM_READY_QUEUEING = {
/**
* Initializes the internal `onDOMReady` queue.
*/
initialize: function () {
this.reactMountReady.reset();
},
/**
* After DOM is flushed, invoke all registered `onDOMReady` callbacks.
*/
close: function () {
this.reactMountReady.notifyAll();
}
};
/**
* Executed within the scope of the `Transaction` instance. Consider these as
* being member methods, but with an implied ordering while being isolated from
* each other.
*/
var TRANSACTION_WRAPPERS = [SELECTION_RESTORATION, EVENT_SUPPRESSION, ON_DOM_READY_QUEUEING];
if (process.env.NODE_ENV !== 'production') {
TRANSACTION_WRAPPERS.push({
initialize: ReactInstrumentation.debugTool.onBeginFlush,
close: ReactInstrumentation.debugTool.onEndFlush
});
}
/**
* Currently:
* - The order that these are listed in the transaction is critical:
* - Suppresses events.
* - Restores selection range.
*
* Future:
* - Restore document/overflow scroll positions that were unintentionally
* modified via DOM insertions above the top viewport boundary.
* - Implement/integrate with customized constraint based layout system and keep
* track of which dimensions must be remeasured.
*
* @class ReactReconcileTransaction
*/
function ReactReconcileTransaction(useCreateElement) {
this.reinitializeTransaction();
// Only server-side rendering really needs this option (see
// `ReactServerRendering`), but server-side uses
// `ReactServerRenderingTransaction` instead. This option is here so that it's
// accessible and defaults to false when `ReactDOMComponent` and
// `ReactDOMTextComponent` checks it in `mountComponent`.`
this.renderToStaticMarkup = false;
this.reactMountReady = CallbackQueue.getPooled(null);
this.useCreateElement = useCreateElement;
}
var Mixin = {
/**
* @see Transaction
* @abstract
* @final
* @return {array<object>} List of operation wrap procedures.
* TODO: convert to array<TransactionWrapper>
*/
getTransactionWrappers: function () {
return TRANSACTION_WRAPPERS;
},
/**
* @return {object} The queue to collect `onDOMReady` callbacks with.
*/
getReactMountReady: function () {
return this.reactMountReady;
},
/**
* @return {object} The queue to collect React async events.
*/
getUpdateQueue: function () {
return ReactUpdateQueue;
},
/**
* Save current transaction state -- if the return value from this method is
* passed to `rollback`, the transaction will be reset to that state.
*/
checkpoint: function () {
// reactMountReady is the our only stateful wrapper
return this.reactMountReady.checkpoint();
},
rollback: function (checkpoint) {
this.reactMountReady.rollback(checkpoint);
},
/**
* `PooledClass` looks for this, and will invoke this before allowing this
* instance to be reused.
*/
destructor: function () {
CallbackQueue.release(this.reactMountReady);
this.reactMountReady = null;
}
};
_assign(ReactReconcileTransaction.prototype, Transaction, Mixin);
PooledClass.addPoolingTo(ReactReconcileTransaction);
module.exports = ReactReconcileTransaction;
}).call(this,require('_process'))
},{"./CallbackQueue":40,"./PooledClass":58,"./ReactBrowserEventEmitter":59,"./ReactInputSelection":94,"./ReactInstrumentation":96,"./ReactUpdateQueue":110,"./Transaction":129,"_process":29,"object-assign":28}],106:[function(require,module,exports){
(function (process){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var ReactRef = require('./ReactRef');
var ReactInstrumentation = require('./ReactInstrumentation');
var warning = require('fbjs/lib/warning');
/**
* Helper to call ReactRef.attachRefs with this composite component, split out
* to avoid allocations in the transaction mount-ready queue.
*/
function attachRefs() {
ReactRef.attachRefs(this, this._currentElement);
}
var ReactReconciler = {
/**
* Initializes the component, renders markup, and registers event listeners.
*
* @param {ReactComponent} internalInstance
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @param {?object} the containing host component instance
* @param {?object} info about the host container
* @return {?string} Rendered markup to be inserted into the DOM.
* @final
* @internal
*/
mountComponent: function (internalInstance, transaction, hostParent, hostContainerInfo, context, parentDebugID // 0 in production and for roots
) {
if (process.env.NODE_ENV !== 'production') {
if (internalInstance._debugID !== 0) {
ReactInstrumentation.debugTool.onBeforeMountComponent(internalInstance._debugID, internalInstance._currentElement, parentDebugID);
}
}
var markup = internalInstance.mountComponent(transaction, hostParent, hostContainerInfo, context, parentDebugID);
if (internalInstance._currentElement && internalInstance._currentElement.ref != null) {
transaction.getReactMountReady().enqueue(attachRefs, internalInstance);
}
if (process.env.NODE_ENV !== 'production') {
if (internalInstance._debugID !== 0) {
ReactInstrumentation.debugTool.onMountComponent(internalInstance._debugID);
}
}
return markup;
},
/**
* Returns a value that can be passed to
* ReactComponentEnvironment.replaceNodeWithMarkup.
*/
getHostNode: function (internalInstance) {
return internalInstance.getHostNode();
},
/**
* Releases any resources allocated by `mountComponent`.
*
* @final
* @internal
*/
unmountComponent: function (internalInstance, safely) {
if (process.env.NODE_ENV !== 'production') {
if (internalInstance._debugID !== 0) {
ReactInstrumentation.debugTool.onBeforeUnmountComponent(internalInstance._debugID);
}
}
ReactRef.detachRefs(internalInstance, internalInstance._currentElement);
internalInstance.unmountComponent(safely);
if (process.env.NODE_ENV !== 'production') {
if (internalInstance._debugID !== 0) {
ReactInstrumentation.debugTool.onUnmountComponent(internalInstance._debugID);
}
}
},
/**
* Update a component using a new element.
*
* @param {ReactComponent} internalInstance
* @param {ReactElement} nextElement
* @param {ReactReconcileTransaction} transaction
* @param {object} context
* @internal
*/
receiveComponent: function (internalInstance, nextElement, transaction, context) {
var prevElement = internalInstance._currentElement;
if (nextElement === prevElement && context === internalInstance._context) {
// Since elements are immutable after the owner is rendered,
// we can do a cheap identity compare here to determine if this is a
// superfluous reconcile. It's possible for state to be mutable but such
// change should trigger an update of the owner which would recreate
// the element. We explicitly check for the existence of an owner since
// it's possible for an element created outside a composite to be
// deeply mutated and reused.
// TODO: Bailing out early is just a perf optimization right?
// TODO: Removing the return statement should affect correctness?
return;
}
if (process.env.NODE_ENV !== 'production') {
if (internalInstance._debugID !== 0) {
ReactInstrumentation.debugTool.onBeforeUpdateComponent(internalInstance._debugID, nextElement);
}
}
var refsChanged = ReactRef.shouldUpdateRefs(prevElement, nextElement);
if (refsChanged) {
ReactRef.detachRefs(internalInstance, prevElement);
}
internalInstance.receiveComponent(nextElement, transaction, context);
if (refsChanged && internalInstance._currentElement && internalInstance._currentElement.ref != null) {
transaction.getReactMountReady().enqueue(attachRefs, internalInstance);
}
if (process.env.NODE_ENV !== 'production') {
if (internalInstance._debugID !== 0) {
ReactInstrumentation.debugTool.onUpdateComponent(internalInstance._debugID);
}
}
},
/**
* Flush any dirty changes in a component.
*
* @param {ReactComponent} internalInstance
* @param {ReactReconcileTransaction} transaction
* @internal
*/
performUpdateIfNecessary: function (internalInstance, transaction, updateBatchNumber) {
if (internalInstance._updateBatchNumber !== updateBatchNumber) {
// The component's enqueued batch number should always be the current
// batch or the following one.
process.env.NODE_ENV !== 'production' ? warning(internalInstance._updateBatchNumber == null || internalInstance._updateBatchNumber === updateBatchNumber + 1, 'performUpdateIfNecessary: Unexpected batch number (current %s, ' + 'pending %s)', updateBatchNumber, internalInstance._updateBatchNumber) : void 0;
return;
}
if (process.env.NODE_ENV !== 'production') {
if (internalInstance._debugID !== 0) {
ReactInstrumentation.debugTool.onBeforeUpdateComponent(internalInstance._debugID, internalInstance._currentElement);
}
}
internalInstance.performUpdateIfNecessary(transaction);
if (process.env.NODE_ENV !== 'production') {
if (internalInstance._debugID !== 0) {
ReactInstrumentation.debugTool.onUpdateComponent(internalInstance._debugID);
}
}
}
};
module.exports = ReactReconciler;
}).call(this,require('_process'))
},{"./ReactInstrumentation":96,"./ReactRef":107,"_process":29,"fbjs/lib/warning":26}],107:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
'use strict';
var ReactOwner = require('./ReactOwner');
var ReactRef = {};
function attachRef(ref, component, owner) {
if (typeof ref === 'function') {
ref(component.getPublicInstance());
} else {
// Legacy ref
ReactOwner.addComponentAsRefTo(component, ref, owner);
}
}
function detachRef(ref, component, owner) {
if (typeof ref === 'function') {
ref(null);
} else {
// Legacy ref
ReactOwner.removeComponentAsRefFrom(component, ref, owner);
}
}
ReactRef.attachRefs = function (instance, element) {
if (element === null || typeof element !== 'object') {
return;
}
var ref = element.ref;
if (ref != null) {
attachRef(ref, instance, element._owner);
}
};
ReactRef.shouldUpdateRefs = function (prevElement, nextElement) {
// If either the owner or a `ref` has changed, make sure the newest owner
// has stored a reference to `this`, and the previous owner (if different)
// has forgotten the reference to `this`. We use the element instead
// of the public this.props because the post processing cannot determine
// a ref. The ref conceptually lives on the element.
// TODO: Should this even be possible? The owner cannot change because
// it's forbidden by shouldUpdateReactComponent. The ref can change
// if you swap the keys of but not the refs. Reconsider where this check
// is made. It probably belongs where the key checking and
// instantiateReactComponent is done.
var prevRef = null;
var prevOwner = null;
if (prevElement !== null && typeof prevElement === 'object') {
prevRef = prevElement.ref;
prevOwner = prevElement._owner;
}
var nextRef = null;
var nextOwner = null;
if (nextElement !== null && typeof nextElement === 'object') {
nextRef = nextElement.ref;
nextOwner = nextElement._owner;
}
return prevRef !== nextRef ||
// If owner changes but we have an unchanged function ref, don't update refs
typeof nextRef === 'string' && nextOwner !== prevOwner;
};
ReactRef.detachRefs = function (instance, element) {
if (element === null || typeof element !== 'object') {
return;
}
var ref = element.ref;
if (ref != null) {
detachRef(ref, instance, element._owner);
}
};
module.exports = ReactRef;
},{"./ReactOwner":102}],108:[function(require,module,exports){
(function (process){
/**
* Copyright 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var _assign = require('object-assign');
var PooledClass = require('./PooledClass');
var Transaction = require('./Transaction');
var ReactInstrumentation = require('./ReactInstrumentation');
var ReactServerUpdateQueue = require('./ReactServerUpdateQueue');
/**
* Executed within the scope of the `Transaction` instance. Consider these as
* being member methods, but with an implied ordering while being isolated from
* each other.
*/
var TRANSACTION_WRAPPERS = [];
if (process.env.NODE_ENV !== 'production') {
TRANSACTION_WRAPPERS.push({
initialize: ReactInstrumentation.debugTool.onBeginFlush,
close: ReactInstrumentation.debugTool.onEndFlush
});
}
var noopCallbackQueue = {
enqueue: function () {}
};
/**
* @class ReactServerRenderingTransaction
* @param {boolean} renderToStaticMarkup
*/
function ReactServerRenderingTransaction(renderToStaticMarkup) {
this.reinitializeTransaction();
this.renderToStaticMarkup = renderToStaticMarkup;
this.useCreateElement = false;
this.updateQueue = new ReactServerUpdateQueue(this);
}
var Mixin = {
/**
* @see Transaction
* @abstract
* @final
* @return {array} Empty list of operation wrap procedures.
*/
getTransactionWrappers: function () {
return TRANSACTION_WRAPPERS;
},
/**
* @return {object} The queue to collect `onDOMReady` callbacks with.
*/
getReactMountReady: function () {
return noopCallbackQueue;
},
/**
* @return {object} The queue to collect React async events.
*/
getUpdateQueue: function () {
return this.updateQueue;
},
/**
* `PooledClass` looks for this, and will invoke this before allowing this
* instance to be reused.
*/
destructor: function () {},
checkpoint: function () {},
rollback: function () {}
};
_assign(ReactServerRenderingTransaction.prototype, Transaction, Mixin);
PooledClass.addPoolingTo(ReactServerRenderingTransaction);
module.exports = ReactServerRenderingTransaction;
}).call(this,require('_process'))
},{"./PooledClass":58,"./ReactInstrumentation":96,"./ReactServerUpdateQueue":109,"./Transaction":129,"_process":29,"object-assign":28}],109:[function(require,module,exports){
(function (process){
/**
* Copyright 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
'use strict';
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var ReactUpdateQueue = require('./ReactUpdateQueue');
var warning = require('fbjs/lib/warning');
function warnNoop(publicInstance, callerName) {
if (process.env.NODE_ENV !== 'production') {
var constructor = publicInstance.constructor;
process.env.NODE_ENV !== 'production' ? warning(false, '%s(...): Can only update a mounting component. ' + 'This usually means you called %s() outside componentWillMount() on the server. ' + 'This is a no-op. Please check the code for the %s component.', callerName, callerName, constructor && (constructor.displayName || constructor.name) || 'ReactClass') : void 0;
}
}
/**
* This is the update queue used for server rendering.
* It delegates to ReactUpdateQueue while server rendering is in progress and
* switches to ReactNoopUpdateQueue after the transaction has completed.
* @class ReactServerUpdateQueue
* @param {Transaction} transaction
*/
var ReactServerUpdateQueue = function () {
function ReactServerUpdateQueue(transaction) {
_classCallCheck(this, ReactServerUpdateQueue);
this.transaction = transaction;
}
/**
* Checks whether or not this composite component is mounted.
* @param {ReactClass} publicInstance The instance we want to test.
* @return {boolean} True if mounted, false otherwise.
* @protected
* @final
*/
ReactServerUpdateQueue.prototype.isMounted = function isMounted(publicInstance) {
return false;
};
/**
* Enqueue a callback that will be executed after all the pending updates
* have processed.
*
* @param {ReactClass} publicInstance The instance to use as `this` context.
* @param {?function} callback Called after state is updated.
* @internal
*/
ReactServerUpdateQueue.prototype.enqueueCallback = function enqueueCallback(publicInstance, callback, callerName) {
if (this.transaction.isInTransaction()) {
ReactUpdateQueue.enqueueCallback(publicInstance, callback, callerName);
}
};
/**
* Forces an update. This should only be invoked when it is known with
* certainty that we are **not** in a DOM transaction.
*
* You may want to call this when you know that some deeper aspect of the
* component's state has changed but `setState` was not called.
*
* This will not invoke `shouldComponentUpdate`, but it will invoke
* `componentWillUpdate` and `componentDidUpdate`.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @internal
*/
ReactServerUpdateQueue.prototype.enqueueForceUpdate = function enqueueForceUpdate(publicInstance) {
if (this.transaction.isInTransaction()) {
ReactUpdateQueue.enqueueForceUpdate(publicInstance);
} else {
warnNoop(publicInstance, 'forceUpdate');
}
};
/**
* Replaces all of the state. Always use this or `setState` to mutate state.
* You should treat `this.state` as immutable.
*
* There is no guarantee that `this.state` will be immediately updated, so
* accessing `this.state` after calling this method may return the old value.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @param {object|function} completeState Next state.
* @internal
*/
ReactServerUpdateQueue.prototype.enqueueReplaceState = function enqueueReplaceState(publicInstance, completeState) {
if (this.transaction.isInTransaction()) {
ReactUpdateQueue.enqueueReplaceState(publicInstance, completeState);
} else {
warnNoop(publicInstance, 'replaceState');
}
};
/**
* Sets a subset of the state. This only exists because _pendingState is
* internal. This provides a merging strategy that is not available to deep
* properties which is confusing. TODO: Expose pendingState or don't use it
* during the merge.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @param {object|function} partialState Next partial state to be merged with state.
* @internal
*/
ReactServerUpdateQueue.prototype.enqueueSetState = function enqueueSetState(publicInstance, partialState) {
if (this.transaction.isInTransaction()) {
ReactUpdateQueue.enqueueSetState(publicInstance, partialState);
} else {
warnNoop(publicInstance, 'setState');
}
};
return ReactServerUpdateQueue;
}();
module.exports = ReactServerUpdateQueue;
}).call(this,require('_process'))
},{"./ReactUpdateQueue":110,"_process":29,"fbjs/lib/warning":26}],110:[function(require,module,exports){
(function (process){
/**
* Copyright 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var _prodInvariant = require('./reactProdInvariant');
var ReactCurrentOwner = require('react/lib/ReactCurrentOwner');
var ReactInstanceMap = require('./ReactInstanceMap');
var ReactInstrumentation = require('./ReactInstrumentation');
var ReactUpdates = require('./ReactUpdates');
var invariant = require('fbjs/lib/invariant');
var warning = require('fbjs/lib/warning');
function enqueueUpdate(internalInstance) {
ReactUpdates.enqueueUpdate(internalInstance);
}
function formatUnexpectedArgument(arg) {
var type = typeof arg;
if (type !== 'object') {
return type;
}
var displayName = arg.constructor && arg.constructor.name || type;
var keys = Object.keys(arg);
if (keys.length > 0 && keys.length < 20) {
return displayName + ' (keys: ' + keys.join(', ') + ')';
}
return displayName;
}
function getInternalInstanceReadyForUpdate(publicInstance, callerName) {
var internalInstance = ReactInstanceMap.get(publicInstance);
if (!internalInstance) {
if (process.env.NODE_ENV !== 'production') {
var ctor = publicInstance.constructor;
// Only warn when we have a callerName. Otherwise we should be silent.
// We're probably calling from enqueueCallback. We don't want to warn
// there because we already warned for the corresponding lifecycle method.
process.env.NODE_ENV !== 'production' ? warning(!callerName, '%s(...): Can only update a mounted or mounting component. ' + 'This usually means you called %s() on an unmounted component. ' + 'This is a no-op. Please check the code for the %s component.', callerName, callerName, ctor && (ctor.displayName || ctor.name) || 'ReactClass') : void 0;
}
return null;
}
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(ReactCurrentOwner.current == null, '%s(...): Cannot update during an existing state transition (such as ' + 'within `render` or another component\'s constructor). Render methods ' + 'should be a pure function of props and state; constructor ' + 'side-effects are an anti-pattern, but can be moved to ' + '`componentWillMount`.', callerName) : void 0;
}
return internalInstance;
}
/**
* ReactUpdateQueue allows for state updates to be scheduled into a later
* reconciliation step.
*/
var ReactUpdateQueue = {
/**
* Checks whether or not this composite component is mounted.
* @param {ReactClass} publicInstance The instance we want to test.
* @return {boolean} True if mounted, false otherwise.
* @protected
* @final
*/
isMounted: function (publicInstance) {
if (process.env.NODE_ENV !== 'production') {
var owner = ReactCurrentOwner.current;
if (owner !== null) {
process.env.NODE_ENV !== 'production' ? warning(owner._warnedAboutRefsInRender, '%s is accessing isMounted inside its render() function. ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', owner.getName() || 'A component') : void 0;
owner._warnedAboutRefsInRender = true;
}
}
var internalInstance = ReactInstanceMap.get(publicInstance);
if (internalInstance) {
// During componentWillMount and render this will still be null but after
// that will always render to something. At least for now. So we can use
// this hack.
return !!internalInstance._renderedComponent;
} else {
return false;
}
},
/**
* Enqueue a callback that will be executed after all the pending updates
* have processed.
*
* @param {ReactClass} publicInstance The instance to use as `this` context.
* @param {?function} callback Called after state is updated.
* @param {string} callerName Name of the calling function in the public API.
* @internal
*/
enqueueCallback: function (publicInstance, callback, callerName) {
ReactUpdateQueue.validateCallback(callback, callerName);
var internalInstance = getInternalInstanceReadyForUpdate(publicInstance);
// Previously we would throw an error if we didn't have an internal
// instance. Since we want to make it a no-op instead, we mirror the same
// behavior we have in other enqueue* methods.
// We also need to ignore callbacks in componentWillMount. See
// enqueueUpdates.
if (!internalInstance) {
return null;
}
if (internalInstance._pendingCallbacks) {
internalInstance._pendingCallbacks.push(callback);
} else {
internalInstance._pendingCallbacks = [callback];
}
// TODO: The callback here is ignored when setState is called from
// componentWillMount. Either fix it or disallow doing so completely in
// favor of getInitialState. Alternatively, we can disallow
// componentWillMount during server-side rendering.
enqueueUpdate(internalInstance);
},
enqueueCallbackInternal: function (internalInstance, callback) {
if (internalInstance._pendingCallbacks) {
internalInstance._pendingCallbacks.push(callback);
} else {
internalInstance._pendingCallbacks = [callback];
}
enqueueUpdate(internalInstance);
},
/**
* Forces an update. This should only be invoked when it is known with
* certainty that we are **not** in a DOM transaction.
*
* You may want to call this when you know that some deeper aspect of the
* component's state has changed but `setState` was not called.
*
* This will not invoke `shouldComponentUpdate`, but it will invoke
* `componentWillUpdate` and `componentDidUpdate`.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @internal
*/
enqueueForceUpdate: function (publicInstance) {
var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'forceUpdate');
if (!internalInstance) {
return;
}
internalInstance._pendingForceUpdate = true;
enqueueUpdate(internalInstance);
},
/**
* Replaces all of the state. Always use this or `setState` to mutate state.
* You should treat `this.state` as immutable.
*
* There is no guarantee that `this.state` will be immediately updated, so
* accessing `this.state` after calling this method may return the old value.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @param {object} completeState Next state.
* @internal
*/
enqueueReplaceState: function (publicInstance, completeState, callback) {
var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'replaceState');
if (!internalInstance) {
return;
}
internalInstance._pendingStateQueue = [completeState];
internalInstance._pendingReplaceState = true;
// Future-proof 15.5
if (callback !== undefined && callback !== null) {
ReactUpdateQueue.validateCallback(callback, 'replaceState');
if (internalInstance._pendingCallbacks) {
internalInstance._pendingCallbacks.push(callback);
} else {
internalInstance._pendingCallbacks = [callback];
}
}
enqueueUpdate(internalInstance);
},
/**
* Sets a subset of the state. This only exists because _pendingState is
* internal. This provides a merging strategy that is not available to deep
* properties which is confusing. TODO: Expose pendingState or don't use it
* during the merge.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @param {object} partialState Next partial state to be merged with state.
* @internal
*/
enqueueSetState: function (publicInstance, partialState) {
if (process.env.NODE_ENV !== 'production') {
ReactInstrumentation.debugTool.onSetState();
process.env.NODE_ENV !== 'production' ? warning(partialState != null, 'setState(...): You passed an undefined or null state object; ' + 'instead, use forceUpdate().') : void 0;
}
var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'setState');
if (!internalInstance) {
return;
}
var queue = internalInstance._pendingStateQueue || (internalInstance._pendingStateQueue = []);
queue.push(partialState);
enqueueUpdate(internalInstance);
},
enqueueElementInternal: function (internalInstance, nextElement, nextContext) {
internalInstance._pendingElement = nextElement;
// TODO: introduce _pendingContext instead of setting it directly.
internalInstance._context = nextContext;
enqueueUpdate(internalInstance);
},
validateCallback: function (callback, callerName) {
!(!callback || typeof callback === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s(...): Expected the last optional `callback` argument to be a function. Instead received: %s.', callerName, formatUnexpectedArgument(callback)) : _prodInvariant('122', callerName, formatUnexpectedArgument(callback)) : void 0;
}
};
module.exports = ReactUpdateQueue;
}).call(this,require('_process'))
},{"./ReactInstanceMap":95,"./ReactInstrumentation":96,"./ReactUpdates":111,"./reactProdInvariant":153,"_process":29,"fbjs/lib/invariant":19,"fbjs/lib/warning":26,"react/lib/ReactCurrentOwner":169}],111:[function(require,module,exports){
(function (process){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var _prodInvariant = require('./reactProdInvariant'),
_assign = require('object-assign');
var CallbackQueue = require('./CallbackQueue');
var PooledClass = require('./PooledClass');
var ReactFeatureFlags = require('./ReactFeatureFlags');
var ReactReconciler = require('./ReactReconciler');
var Transaction = require('./Transaction');
var invariant = require('fbjs/lib/invariant');
var dirtyComponents = [];
var updateBatchNumber = 0;
var asapCallbackQueue = CallbackQueue.getPooled();
var asapEnqueued = false;
var batchingStrategy = null;
function ensureInjected() {
!(ReactUpdates.ReactReconcileTransaction && batchingStrategy) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must inject a reconcile transaction class and batching strategy') : _prodInvariant('123') : void 0;
}
var NESTED_UPDATES = {
initialize: function () {
this.dirtyComponentsLength = dirtyComponents.length;
},
close: function () {
if (this.dirtyComponentsLength !== dirtyComponents.length) {
// Additional updates were enqueued by componentDidUpdate handlers or
// similar; before our own UPDATE_QUEUEING wrapper closes, we want to run
// these new updates so that if A's componentDidUpdate calls setState on
// B, B will update before the callback A's updater provided when calling
// setState.
dirtyComponents.splice(0, this.dirtyComponentsLength);
flushBatchedUpdates();
} else {
dirtyComponents.length = 0;
}
}
};
var UPDATE_QUEUEING = {
initialize: function () {
this.callbackQueue.reset();
},
close: function () {
this.callbackQueue.notifyAll();
}
};
var TRANSACTION_WRAPPERS = [NESTED_UPDATES, UPDATE_QUEUEING];
function ReactUpdatesFlushTransaction() {
this.reinitializeTransaction();
this.dirtyComponentsLength = null;
this.callbackQueue = CallbackQueue.getPooled();
this.reconcileTransaction = ReactUpdates.ReactReconcileTransaction.getPooled(
/* useCreateElement */true);
}
_assign(ReactUpdatesFlushTransaction.prototype, Transaction, {
getTransactionWrappers: function () {
return TRANSACTION_WRAPPERS;
},
destructor: function () {
this.dirtyComponentsLength = null;
CallbackQueue.release(this.callbackQueue);
this.callbackQueue = null;
ReactUpdates.ReactReconcileTransaction.release(this.reconcileTransaction);
this.reconcileTransaction = null;
},
perform: function (method, scope, a) {
// Essentially calls `this.reconcileTransaction.perform(method, scope, a)`
// with this transaction's wrappers around it.
return Transaction.perform.call(this, this.reconcileTransaction.perform, this.reconcileTransaction, method, scope, a);
}
});
PooledClass.addPoolingTo(ReactUpdatesFlushTransaction);
function batchedUpdates(callback, a, b, c, d, e) {
ensureInjected();
return batchingStrategy.batchedUpdates(callback, a, b, c, d, e);
}
/**
* Array comparator for ReactComponents by mount ordering.
*
* @param {ReactComponent} c1 first component you're comparing
* @param {ReactComponent} c2 second component you're comparing
* @return {number} Return value usable by Array.prototype.sort().
*/
function mountOrderComparator(c1, c2) {
return c1._mountOrder - c2._mountOrder;
}
function runBatchedUpdates(transaction) {
var len = transaction.dirtyComponentsLength;
!(len === dirtyComponents.length) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected flush transaction\'s stored dirty-components length (%s) to match dirty-components array length (%s).', len, dirtyComponents.length) : _prodInvariant('124', len, dirtyComponents.length) : void 0;
// Since reconciling a component higher in the owner hierarchy usually (not
// always -- see shouldComponentUpdate()) will reconcile children, reconcile
// them before their children by sorting the array.
dirtyComponents.sort(mountOrderComparator);
// Any updates enqueued while reconciling must be performed after this entire
// batch. Otherwise, if dirtyComponents is [A, B] where A has children B and
// C, B could update twice in a single batch if C's render enqueues an update
// to B (since B would have already updated, we should skip it, and the only
// way we can know to do so is by checking the batch counter).
updateBatchNumber++;
for (var i = 0; i < len; i++) {
// If a component is unmounted before pending changes apply, it will still
// be here, but we assume that it has cleared its _pendingCallbacks and
// that performUpdateIfNecessary is a noop.
var component = dirtyComponents[i];
// If performUpdateIfNecessary happens to enqueue any new updates, we
// shouldn't execute the callbacks until the next render happens, so
// stash the callbacks first
var callbacks = component._pendingCallbacks;
component._pendingCallbacks = null;
var markerName;
if (ReactFeatureFlags.logTopLevelRenders) {
var namedComponent = component;
// Duck type TopLevelWrapper. This is probably always true.
if (component._currentElement.type.isReactTopLevelWrapper) {
namedComponent = component._renderedComponent;
}
markerName = 'React update: ' + namedComponent.getName();
console.time(markerName);
}
ReactReconciler.performUpdateIfNecessary(component, transaction.reconcileTransaction, updateBatchNumber);
if (markerName) {
console.timeEnd(markerName);
}
if (callbacks) {
for (var j = 0; j < callbacks.length; j++) {
transaction.callbackQueue.enqueue(callbacks[j], component.getPublicInstance());
}
}
}
}
var flushBatchedUpdates = function () {
// ReactUpdatesFlushTransaction's wrappers will clear the dirtyComponents
// array and perform any updates enqueued by mount-ready handlers (i.e.,
// componentDidUpdate) but we need to check here too in order to catch
// updates enqueued by setState callbacks and asap calls.
while (dirtyComponents.length || asapEnqueued) {
if (dirtyComponents.length) {
var transaction = ReactUpdatesFlushTransaction.getPooled();
transaction.perform(runBatchedUpdates, null, transaction);
ReactUpdatesFlushTransaction.release(transaction);
}
if (asapEnqueued) {
asapEnqueued = false;
var queue = asapCallbackQueue;
asapCallbackQueue = CallbackQueue.getPooled();
queue.notifyAll();
CallbackQueue.release(queue);
}
}
};
/**
* Mark a component as needing a rerender, adding an optional callback to a
* list of functions which will be executed once the rerender occurs.
*/
function enqueueUpdate(component) {
ensureInjected();
// Various parts of our code (such as ReactCompositeComponent's
// _renderValidatedComponent) assume that calls to render aren't nested;
// verify that that's the case. (This is called by each top-level update
// function, like setState, forceUpdate, etc.; creation and
// destruction of top-level components is guarded in ReactMount.)
if (!batchingStrategy.isBatchingUpdates) {
batchingStrategy.batchedUpdates(enqueueUpdate, component);
return;
}
dirtyComponents.push(component);
if (component._updateBatchNumber == null) {
component._updateBatchNumber = updateBatchNumber + 1;
}
}
/**
* Enqueue a callback to be run at the end of the current batching cycle. Throws
* if no updates are currently being performed.
*/
function asap(callback, context) {
!batchingStrategy.isBatchingUpdates ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates.asap: Can\'t enqueue an asap callback in a context whereupdates are not being batched.') : _prodInvariant('125') : void 0;
asapCallbackQueue.enqueue(callback, context);
asapEnqueued = true;
}
var ReactUpdatesInjection = {
injectReconcileTransaction: function (ReconcileTransaction) {
!ReconcileTransaction ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must provide a reconcile transaction class') : _prodInvariant('126') : void 0;
ReactUpdates.ReactReconcileTransaction = ReconcileTransaction;
},
injectBatchingStrategy: function (_batchingStrategy) {
!_batchingStrategy ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must provide a batching strategy') : _prodInvariant('127') : void 0;
!(typeof _batchingStrategy.batchedUpdates === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must provide a batchedUpdates() function') : _prodInvariant('128') : void 0;
!(typeof _batchingStrategy.isBatchingUpdates === 'boolean') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must provide an isBatchingUpdates boolean attribute') : _prodInvariant('129') : void 0;
batchingStrategy = _batchingStrategy;
}
};
var ReactUpdates = {
/**
* React references `ReactReconcileTransaction` using this property in order
* to allow dependency injection.
*
* @internal
*/
ReactReconcileTransaction: null,
batchedUpdates: batchedUpdates,
enqueueUpdate: enqueueUpdate,
flushBatchedUpdates: flushBatchedUpdates,
injection: ReactUpdatesInjection,
asap: asap
};
module.exports = ReactUpdates;
}).call(this,require('_process'))
},{"./CallbackQueue":40,"./PooledClass":58,"./ReactFeatureFlags":90,"./ReactReconciler":106,"./Transaction":129,"./reactProdInvariant":153,"_process":29,"fbjs/lib/invariant":19,"object-assign":28}],112:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
module.exports = '15.5.3';
},{}],113:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var NS = {
xlink: 'http://www.w3.org/1999/xlink',
xml: 'http://www.w3.org/XML/1998/namespace'
};
// We use attributes for everything SVG so let's avoid some duplication and run
// code instead.
// The following are all specified in the HTML config already so we exclude here.
// - class (as className)
// - color
// - height
// - id
// - lang
// - max
// - media
// - method
// - min
// - name
// - style
// - target
// - type
// - width
var ATTRS = {
accentHeight: 'accent-height',
accumulate: 0,
additive: 0,
alignmentBaseline: 'alignment-baseline',
allowReorder: 'allowReorder',
alphabetic: 0,
amplitude: 0,
arabicForm: 'arabic-form',
ascent: 0,
attributeName: 'attributeName',
attributeType: 'attributeType',
autoReverse: 'autoReverse',
azimuth: 0,
baseFrequency: 'baseFrequency',
baseProfile: 'baseProfile',
baselineShift: 'baseline-shift',
bbox: 0,
begin: 0,
bias: 0,
by: 0,
calcMode: 'calcMode',
capHeight: 'cap-height',
clip: 0,
clipPath: 'clip-path',
clipRule: 'clip-rule',
clipPathUnits: 'clipPathUnits',
colorInterpolation: 'color-interpolation',
colorInterpolationFilters: 'color-interpolation-filters',
colorProfile: 'color-profile',
colorRendering: 'color-rendering',
contentScriptType: 'contentScriptType',
contentStyleType: 'contentStyleType',
cursor: 0,
cx: 0,
cy: 0,
d: 0,
decelerate: 0,
descent: 0,
diffuseConstant: 'diffuseConstant',
direction: 0,
display: 0,
divisor: 0,
dominantBaseline: 'dominant-baseline',
dur: 0,
dx: 0,
dy: 0,
edgeMode: 'edgeMode',
elevation: 0,
enableBackground: 'enable-background',
end: 0,
exponent: 0,
externalResourcesRequired: 'externalResourcesRequired',
fill: 0,
fillOpacity: 'fill-opacity',
fillRule: 'fill-rule',
filter: 0,
filterRes: 'filterRes',
filterUnits: 'filterUnits',
floodColor: 'flood-color',
floodOpacity: 'flood-opacity',
focusable: 0,
fontFamily: 'font-family',
fontSize: 'font-size',
fontSizeAdjust: 'font-size-adjust',
fontStretch: 'font-stretch',
fontStyle: 'font-style',
fontVariant: 'font-variant',
fontWeight: 'font-weight',
format: 0,
from: 0,
fx: 0,
fy: 0,
g1: 0,
g2: 0,
glyphName: 'glyph-name',
glyphOrientationHorizontal: 'glyph-orientation-horizontal',
glyphOrientationVertical: 'glyph-orientation-vertical',
glyphRef: 'glyphRef',
gradientTransform: 'gradientTransform',
gradientUnits: 'gradientUnits',
hanging: 0,
horizAdvX: 'horiz-adv-x',
horizOriginX: 'horiz-origin-x',
ideographic: 0,
imageRendering: 'image-rendering',
'in': 0,
in2: 0,
intercept: 0,
k: 0,
k1: 0,
k2: 0,
k3: 0,
k4: 0,
kernelMatrix: 'kernelMatrix',
kernelUnitLength: 'kernelUnitLength',
kerning: 0,
keyPoints: 'keyPoints',
keySplines: 'keySplines',
keyTimes: 'keyTimes',
lengthAdjust: 'lengthAdjust',
letterSpacing: 'letter-spacing',
lightingColor: 'lighting-color',
limitingConeAngle: 'limitingConeAngle',
local: 0,
markerEnd: 'marker-end',
markerMid: 'marker-mid',
markerStart: 'marker-start',
markerHeight: 'markerHeight',
markerUnits: 'markerUnits',
markerWidth: 'markerWidth',
mask: 0,
maskContentUnits: 'maskContentUnits',
maskUnits: 'maskUnits',
mathematical: 0,
mode: 0,
numOctaves: 'numOctaves',
offset: 0,
opacity: 0,
operator: 0,
order: 0,
orient: 0,
orientation: 0,
origin: 0,
overflow: 0,
overlinePosition: 'overline-position',
overlineThickness: 'overline-thickness',
paintOrder: 'paint-order',
panose1: 'panose-1',
pathLength: 'pathLength',
patternContentUnits: 'patternContentUnits',
patternTransform: 'patternTransform',
patternUnits: 'patternUnits',
pointerEvents: 'pointer-events',
points: 0,
pointsAtX: 'pointsAtX',
pointsAtY: 'pointsAtY',
pointsAtZ: 'pointsAtZ',
preserveAlpha: 'preserveAlpha',
preserveAspectRatio: 'preserveAspectRatio',
primitiveUnits: 'primitiveUnits',
r: 0,
radius: 0,
refX: 'refX',
refY: 'refY',
renderingIntent: 'rendering-intent',
repeatCount: 'repeatCount',
repeatDur: 'repeatDur',
requiredExtensions: 'requiredExtensions',
requiredFeatures: 'requiredFeatures',
restart: 0,
result: 0,
rotate: 0,
rx: 0,
ry: 0,
scale: 0,
seed: 0,
shapeRendering: 'shape-rendering',
slope: 0,
spacing: 0,
specularConstant: 'specularConstant',
specularExponent: 'specularExponent',
speed: 0,
spreadMethod: 'spreadMethod',
startOffset: 'startOffset',
stdDeviation: 'stdDeviation',
stemh: 0,
stemv: 0,
stitchTiles: 'stitchTiles',
stopColor: 'stop-color',
stopOpacity: 'stop-opacity',
strikethroughPosition: 'strikethrough-position',
strikethroughThickness: 'strikethrough-thickness',
string: 0,
stroke: 0,
strokeDasharray: 'stroke-dasharray',
strokeDashoffset: 'stroke-dashoffset',
strokeLinecap: 'stroke-linecap',
strokeLinejoin: 'stroke-linejoin',
strokeMiterlimit: 'stroke-miterlimit',
strokeOpacity: 'stroke-opacity',
strokeWidth: 'stroke-width',
surfaceScale: 'surfaceScale',
systemLanguage: 'systemLanguage',
tableValues: 'tableValues',
targetX: 'targetX',
targetY: 'targetY',
textAnchor: 'text-anchor',
textDecoration: 'text-decoration',
textRendering: 'text-rendering',
textLength: 'textLength',
to: 0,
transform: 0,
u1: 0,
u2: 0,
underlinePosition: 'underline-position',
underlineThickness: 'underline-thickness',
unicode: 0,
unicodeBidi: 'unicode-bidi',
unicodeRange: 'unicode-range',
unitsPerEm: 'units-per-em',
vAlphabetic: 'v-alphabetic',
vHanging: 'v-hanging',
vIdeographic: 'v-ideographic',
vMathematical: 'v-mathematical',
values: 0,
vectorEffect: 'vector-effect',
version: 0,
vertAdvY: 'vert-adv-y',
vertOriginX: 'vert-origin-x',
vertOriginY: 'vert-origin-y',
viewBox: 'viewBox',
viewTarget: 'viewTarget',
visibility: 0,
widths: 0,
wordSpacing: 'word-spacing',
writingMode: 'writing-mode',
x: 0,
xHeight: 'x-height',
x1: 0,
x2: 0,
xChannelSelector: 'xChannelSelector',
xlinkActuate: 'xlink:actuate',
xlinkArcrole: 'xlink:arcrole',
xlinkHref: 'xlink:href',
xlinkRole: 'xlink:role',
xlinkShow: 'xlink:show',
xlinkTitle: 'xlink:title',
xlinkType: 'xlink:type',
xmlBase: 'xml:base',
xmlns: 0,
xmlnsXlink: 'xmlns:xlink',
xmlLang: 'xml:lang',
xmlSpace: 'xml:space',
y: 0,
y1: 0,
y2: 0,
yChannelSelector: 'yChannelSelector',
z: 0,
zoomAndPan: 'zoomAndPan'
};
var SVGDOMPropertyConfig = {
Properties: {},
DOMAttributeNamespaces: {
xlinkActuate: NS.xlink,
xlinkArcrole: NS.xlink,
xlinkHref: NS.xlink,
xlinkRole: NS.xlink,
xlinkShow: NS.xlink,
xlinkTitle: NS.xlink,
xlinkType: NS.xlink,
xmlBase: NS.xml,
xmlLang: NS.xml,
xmlSpace: NS.xml
},
DOMAttributeNames: {}
};
Object.keys(ATTRS).forEach(function (key) {
SVGDOMPropertyConfig.Properties[key] = 0;
if (ATTRS[key]) {
SVGDOMPropertyConfig.DOMAttributeNames[key] = ATTRS[key];
}
});
module.exports = SVGDOMPropertyConfig;
},{}],114:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var EventPropagators = require('./EventPropagators');
var ExecutionEnvironment = require('fbjs/lib/ExecutionEnvironment');
var ReactDOMComponentTree = require('./ReactDOMComponentTree');
var ReactInputSelection = require('./ReactInputSelection');
var SyntheticEvent = require('./SyntheticEvent');
var getActiveElement = require('fbjs/lib/getActiveElement');
var isTextInputElement = require('./isTextInputElement');
var shallowEqual = require('fbjs/lib/shallowEqual');
var skipSelectionChangeEvent = ExecutionEnvironment.canUseDOM && 'documentMode' in document && document.documentMode <= 11;
var eventTypes = {
select: {
phasedRegistrationNames: {
bubbled: 'onSelect',
captured: 'onSelectCapture'
},
dependencies: ['topBlur', 'topContextMenu', 'topFocus', 'topKeyDown', 'topKeyUp', 'topMouseDown', 'topMouseUp', 'topSelectionChange']
}
};
var activeElement = null;
var activeElementInst = null;
var lastSelection = null;
var mouseDown = false;
// Track whether a listener exists for this plugin. If none exist, we do
// not extract events. See #3639.
var hasListener = false;
/**
* Get an object which is a unique representation of the current selection.
*
* The return value will not be consistent across nodes or browsers, but
* two identical selections on the same node will return identical objects.
*
* @param {DOMElement} node
* @return {object}
*/
function getSelection(node) {
if ('selectionStart' in node && ReactInputSelection.hasSelectionCapabilities(node)) {
return {
start: node.selectionStart,
end: node.selectionEnd
};
} else if (window.getSelection) {
var selection = window.getSelection();
return {
anchorNode: selection.anchorNode,
anchorOffset: selection.anchorOffset,
focusNode: selection.focusNode,
focusOffset: selection.focusOffset
};
} else if (document.selection) {
var range = document.selection.createRange();
return {
parentElement: range.parentElement(),
text: range.text,
top: range.boundingTop,
left: range.boundingLeft
};
}
}
/**
* Poll selection to see whether it's changed.
*
* @param {object} nativeEvent
* @return {?SyntheticEvent}
*/
function constructSelectEvent(nativeEvent, nativeEventTarget) {
// Ensure we have the right element, and that the user is not dragging a
// selection (this matches native `select` event behavior). In HTML5, select
// fires only on input and textarea thus if there's no focused element we
// won't dispatch.
if (mouseDown || activeElement == null || activeElement !== getActiveElement()) {
return null;
}
// Only fire when selection has actually changed.
var currentSelection = getSelection(activeElement);
if (!lastSelection || !shallowEqual(lastSelection, currentSelection)) {
lastSelection = currentSelection;
var syntheticEvent = SyntheticEvent.getPooled(eventTypes.select, activeElementInst, nativeEvent, nativeEventTarget);
syntheticEvent.type = 'select';
syntheticEvent.target = activeElement;
EventPropagators.accumulateTwoPhaseDispatches(syntheticEvent);
return syntheticEvent;
}
return null;
}
/**
* This plugin creates an `onSelect` event that normalizes select events
* across form elements.
*
* Supported elements are:
* - input (see `isTextInputElement`)
* - textarea
* - contentEditable
*
* This differs from native browser implementations in the following ways:
* - Fires on contentEditable fields as well as inputs.
* - Fires for collapsed selection.
* - Fires after user input.
*/
var SelectEventPlugin = {
eventTypes: eventTypes,
extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) {
if (!hasListener) {
return null;
}
var targetNode = targetInst ? ReactDOMComponentTree.getNodeFromInstance(targetInst) : window;
switch (topLevelType) {
// Track the input node that has focus.
case 'topFocus':
if (isTextInputElement(targetNode) || targetNode.contentEditable === 'true') {
activeElement = targetNode;
activeElementInst = targetInst;
lastSelection = null;
}
break;
case 'topBlur':
activeElement = null;
activeElementInst = null;
lastSelection = null;
break;
// Don't fire the event while the user is dragging. This matches the
// semantics of the native select event.
case 'topMouseDown':
mouseDown = true;
break;
case 'topContextMenu':
case 'topMouseUp':
mouseDown = false;
return constructSelectEvent(nativeEvent, nativeEventTarget);
// Chrome and IE fire non-standard event when selection is changed (and
// sometimes when it hasn't). IE's event fires out of order with respect
// to key and input events on deletion, so we discard it.
//
// Firefox doesn't support selectionchange, so check selection status
// after each key entry. The selection changes after keydown and before
// keyup, but we check on keydown as well in the case of holding down a
// key, when multiple keydown events are fired but only one keyup is.
// This is also our approach for IE handling, for the reason above.
case 'topSelectionChange':
if (skipSelectionChangeEvent) {
break;
}
// falls through
case 'topKeyDown':
case 'topKeyUp':
return constructSelectEvent(nativeEvent, nativeEventTarget);
}
return null;
},
didPutListener: function (inst, registrationName, listener) {
if (registrationName === 'onSelect') {
hasListener = true;
}
}
};
module.exports = SelectEventPlugin;
},{"./EventPropagators":53,"./ReactDOMComponentTree":67,"./ReactInputSelection":94,"./SyntheticEvent":120,"./isTextInputElement":151,"fbjs/lib/ExecutionEnvironment":5,"fbjs/lib/getActiveElement":14,"fbjs/lib/shallowEqual":25}],115:[function(require,module,exports){
(function (process){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
'use strict';
var _prodInvariant = require('./reactProdInvariant');
var EventListener = require('fbjs/lib/EventListener');
var EventPropagators = require('./EventPropagators');
var ReactDOMComponentTree = require('./ReactDOMComponentTree');
var SyntheticAnimationEvent = require('./SyntheticAnimationEvent');
var SyntheticClipboardEvent = require('./SyntheticClipboardEvent');
var SyntheticEvent = require('./SyntheticEvent');
var SyntheticFocusEvent = require('./SyntheticFocusEvent');
var SyntheticKeyboardEvent = require('./SyntheticKeyboardEvent');
var SyntheticMouseEvent = require('./SyntheticMouseEvent');
var SyntheticDragEvent = require('./SyntheticDragEvent');
var SyntheticTouchEvent = require('./SyntheticTouchEvent');
var SyntheticTransitionEvent = require('./SyntheticTransitionEvent');
var SyntheticUIEvent = require('./SyntheticUIEvent');
var SyntheticWheelEvent = require('./SyntheticWheelEvent');
var emptyFunction = require('fbjs/lib/emptyFunction');
var getEventCharCode = require('./getEventCharCode');
var invariant = require('fbjs/lib/invariant');
/**
* Turns
* ['abort', ...]
* into
* eventTypes = {
* 'abort': {
* phasedRegistrationNames: {
* bubbled: 'onAbort',
* captured: 'onAbortCapture',
* },
* dependencies: ['topAbort'],
* },
* ...
* };
* topLevelEventsToDispatchConfig = {
* 'topAbort': { sameConfig }
* };
*/
var eventTypes = {};
var topLevelEventsToDispatchConfig = {};
['abort', 'animationEnd', 'animationIteration', 'animationStart', 'blur', 'canPlay', 'canPlayThrough', 'click', 'contextMenu', 'copy', 'cut', 'doubleClick', 'drag', 'dragEnd', 'dragEnter', 'dragExit', 'dragLeave', 'dragOver', 'dragStart', 'drop', 'durationChange', 'emptied', 'encrypted', 'ended', 'error', 'focus', 'input', 'invalid', 'keyDown', 'keyPress', 'keyUp', 'load', 'loadedData', 'loadedMetadata', 'loadStart', 'mouseDown', 'mouseMove', 'mouseOut', 'mouseOver', 'mouseUp', 'paste', 'pause', 'play', 'playing', 'progress', 'rateChange', 'reset', 'scroll', 'seeked', 'seeking', 'stalled', 'submit', 'suspend', 'timeUpdate', 'touchCancel', 'touchEnd', 'touchMove', 'touchStart', 'transitionEnd', 'volumeChange', 'waiting', 'wheel'].forEach(function (event) {
var capitalizedEvent = event[0].toUpperCase() + event.slice(1);
var onEvent = 'on' + capitalizedEvent;
var topEvent = 'top' + capitalizedEvent;
var type = {
phasedRegistrationNames: {
bubbled: onEvent,
captured: onEvent + 'Capture'
},
dependencies: [topEvent]
};
eventTypes[event] = type;
topLevelEventsToDispatchConfig[topEvent] = type;
});
var onClickListeners = {};
function getDictionaryKey(inst) {
// Prevents V8 performance issue:
// https://github.com/facebook/react/pull/7232
return '.' + inst._rootNodeID;
}
function isInteractive(tag) {
return tag === 'button' || tag === 'input' || tag === 'select' || tag === 'textarea';
}
var SimpleEventPlugin = {
eventTypes: eventTypes,
extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) {
var dispatchConfig = topLevelEventsToDispatchConfig[topLevelType];
if (!dispatchConfig) {
return null;
}
var EventConstructor;
switch (topLevelType) {
case 'topAbort':
case 'topCanPlay':
case 'topCanPlayThrough':
case 'topDurationChange':
case 'topEmptied':
case 'topEncrypted':
case 'topEnded':
case 'topError':
case 'topInput':
case 'topInvalid':
case 'topLoad':
case 'topLoadedData':
case 'topLoadedMetadata':
case 'topLoadStart':
case 'topPause':
case 'topPlay':
case 'topPlaying':
case 'topProgress':
case 'topRateChange':
case 'topReset':
case 'topSeeked':
case 'topSeeking':
case 'topStalled':
case 'topSubmit':
case 'topSuspend':
case 'topTimeUpdate':
case 'topVolumeChange':
case 'topWaiting':
// HTML Events
// @see http://www.w3.org/TR/html5/index.html#events-0
EventConstructor = SyntheticEvent;
break;
case 'topKeyPress':
// Firefox creates a keypress event for function keys too. This removes
// the unwanted keypress events. Enter is however both printable and
// non-printable. One would expect Tab to be as well (but it isn't).
if (getEventCharCode(nativeEvent) === 0) {
return null;
}
/* falls through */
case 'topKeyDown':
case 'topKeyUp':
EventConstructor = SyntheticKeyboardEvent;
break;
case 'topBlur':
case 'topFocus':
EventConstructor = SyntheticFocusEvent;
break;
case 'topClick':
// Firefox creates a click event on right mouse clicks. This removes the
// unwanted click events.
if (nativeEvent.button === 2) {
return null;
}
/* falls through */
case 'topDoubleClick':
case 'topMouseDown':
case 'topMouseMove':
case 'topMouseUp':
// TODO: Disabled elements should not respond to mouse events
/* falls through */
case 'topMouseOut':
case 'topMouseOver':
case 'topContextMenu':
EventConstructor = SyntheticMouseEvent;
break;
case 'topDrag':
case 'topDragEnd':
case 'topDragEnter':
case 'topDragExit':
case 'topDragLeave':
case 'topDragOver':
case 'topDragStart':
case 'topDrop':
EventConstructor = SyntheticDragEvent;
break;
case 'topTouchCancel':
case 'topTouchEnd':
case 'topTouchMove':
case 'topTouchStart':
EventConstructor = SyntheticTouchEvent;
break;
case 'topAnimationEnd':
case 'topAnimationIteration':
case 'topAnimationStart':
EventConstructor = SyntheticAnimationEvent;
break;
case 'topTransitionEnd':
EventConstructor = SyntheticTransitionEvent;
break;
case 'topScroll':
EventConstructor = SyntheticUIEvent;
break;
case 'topWheel':
EventConstructor = SyntheticWheelEvent;
break;
case 'topCopy':
case 'topCut':
case 'topPaste':
EventConstructor = SyntheticClipboardEvent;
break;
}
!EventConstructor ? process.env.NODE_ENV !== 'production' ? invariant(false, 'SimpleEventPlugin: Unhandled event type, `%s`.', topLevelType) : _prodInvariant('86', topLevelType) : void 0;
var event = EventConstructor.getPooled(dispatchConfig, targetInst, nativeEvent, nativeEventTarget);
EventPropagators.accumulateTwoPhaseDispatches(event);
return event;
},
didPutListener: function (inst, registrationName, listener) {
// Mobile Safari does not fire properly bubble click events on
// non-interactive elements, which means delegated click listeners do not
// fire. The workaround for this bug involves attaching an empty click
// listener on the target node.
// http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html
if (registrationName === 'onClick' && !isInteractive(inst._tag)) {
var key = getDictionaryKey(inst);
var node = ReactDOMComponentTree.getNodeFromInstance(inst);
if (!onClickListeners[key]) {
onClickListeners[key] = EventListener.listen(node, 'click', emptyFunction);
}
}
},
willDeleteListener: function (inst, registrationName) {
if (registrationName === 'onClick' && !isInteractive(inst._tag)) {
var key = getDictionaryKey(inst);
onClickListeners[key].remove();
delete onClickListeners[key];
}
}
};
module.exports = SimpleEventPlugin;
}).call(this,require('_process'))
},{"./EventPropagators":53,"./ReactDOMComponentTree":67,"./SyntheticAnimationEvent":116,"./SyntheticClipboardEvent":117,"./SyntheticDragEvent":119,"./SyntheticEvent":120,"./SyntheticFocusEvent":121,"./SyntheticKeyboardEvent":123,"./SyntheticMouseEvent":124,"./SyntheticTouchEvent":125,"./SyntheticTransitionEvent":126,"./SyntheticUIEvent":127,"./SyntheticWheelEvent":128,"./getEventCharCode":140,"./reactProdInvariant":153,"_process":29,"fbjs/lib/EventListener":4,"fbjs/lib/emptyFunction":11,"fbjs/lib/invariant":19}],116:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var SyntheticEvent = require('./SyntheticEvent');
/**
* @interface Event
* @see http://www.w3.org/TR/css3-animations/#AnimationEvent-interface
* @see https://developer.mozilla.org/en-US/docs/Web/API/AnimationEvent
*/
var AnimationEventInterface = {
animationName: null,
elapsedTime: null,
pseudoElement: null
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticEvent}
*/
function SyntheticAnimationEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticEvent.augmentClass(SyntheticAnimationEvent, AnimationEventInterface);
module.exports = SyntheticAnimationEvent;
},{"./SyntheticEvent":120}],117:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var SyntheticEvent = require('./SyntheticEvent');
/**
* @interface Event
* @see http://www.w3.org/TR/clipboard-apis/
*/
var ClipboardEventInterface = {
clipboardData: function (event) {
return 'clipboardData' in event ? event.clipboardData : window.clipboardData;
}
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticClipboardEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticEvent.augmentClass(SyntheticClipboardEvent, ClipboardEventInterface);
module.exports = SyntheticClipboardEvent;
},{"./SyntheticEvent":120}],118:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var SyntheticEvent = require('./SyntheticEvent');
/**
* @interface Event
* @see http://www.w3.org/TR/DOM-Level-3-Events/#events-compositionevents
*/
var CompositionEventInterface = {
data: null
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticCompositionEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticEvent.augmentClass(SyntheticCompositionEvent, CompositionEventInterface);
module.exports = SyntheticCompositionEvent;
},{"./SyntheticEvent":120}],119:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var SyntheticMouseEvent = require('./SyntheticMouseEvent');
/**
* @interface DragEvent
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
var DragEventInterface = {
dataTransfer: null
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticDragEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
return SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticMouseEvent.augmentClass(SyntheticDragEvent, DragEventInterface);
module.exports = SyntheticDragEvent;
},{"./SyntheticMouseEvent":124}],120:[function(require,module,exports){
(function (process){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var _assign = require('object-assign');
var PooledClass = require('./PooledClass');
var emptyFunction = require('fbjs/lib/emptyFunction');
var warning = require('fbjs/lib/warning');
var didWarnForAddedNewProperty = false;
var isProxySupported = typeof Proxy === 'function';
var shouldBeReleasedProperties = ['dispatchConfig', '_targetInst', 'nativeEvent', 'isDefaultPrevented', 'isPropagationStopped', '_dispatchListeners', '_dispatchInstances'];
/**
* @interface Event
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
var EventInterface = {
type: null,
target: null,
// currentTarget is set when dispatching; no use in copying it here
currentTarget: emptyFunction.thatReturnsNull,
eventPhase: null,
bubbles: null,
cancelable: null,
timeStamp: function (event) {
return event.timeStamp || Date.now();
},
defaultPrevented: null,
isTrusted: null
};
/**
* Synthetic events are dispatched by event plugins, typically in response to a
* top-level event delegation handler.
*
* These systems should generally use pooling to reduce the frequency of garbage
* collection. The system should check `isPersistent` to determine whether the
* event should be released into the pool after being dispatched. Users that
* need a persisted event should invoke `persist`.
*
* Synthetic events (and subclasses) implement the DOM Level 3 Events API by
* normalizing browser quirks. Subclasses do not necessarily have to implement a
* DOM interface; custom application-specific events can also subclass this.
*
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {*} targetInst Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @param {DOMEventTarget} nativeEventTarget Target node.
*/
function SyntheticEvent(dispatchConfig, targetInst, nativeEvent, nativeEventTarget) {
if (process.env.NODE_ENV !== 'production') {
// these have a getter/setter for warnings
delete this.nativeEvent;
delete this.preventDefault;
delete this.stopPropagation;
}
this.dispatchConfig = dispatchConfig;
this._targetInst = targetInst;
this.nativeEvent = nativeEvent;
var Interface = this.constructor.Interface;
for (var propName in Interface) {
if (!Interface.hasOwnProperty(propName)) {
continue;
}
if (process.env.NODE_ENV !== 'production') {
delete this[propName]; // this has a getter/setter for warnings
}
var normalize = Interface[propName];
if (normalize) {
this[propName] = normalize(nativeEvent);
} else {
if (propName === 'target') {
this.target = nativeEventTarget;
} else {
this[propName] = nativeEvent[propName];
}
}
}
var defaultPrevented = nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false;
if (defaultPrevented) {
this.isDefaultPrevented = emptyFunction.thatReturnsTrue;
} else {
this.isDefaultPrevented = emptyFunction.thatReturnsFalse;
}
this.isPropagationStopped = emptyFunction.thatReturnsFalse;
return this;
}
_assign(SyntheticEvent.prototype, {
preventDefault: function () {
this.defaultPrevented = true;
var event = this.nativeEvent;
if (!event) {
return;
}
if (event.preventDefault) {
event.preventDefault();
} else if (typeof event.returnValue !== 'unknown') {
// eslint-disable-line valid-typeof
event.returnValue = false;
}
this.isDefaultPrevented = emptyFunction.thatReturnsTrue;
},
stopPropagation: function () {
var event = this.nativeEvent;
if (!event) {
return;
}
if (event.stopPropagation) {
event.stopPropagation();
} else if (typeof event.cancelBubble !== 'unknown') {
// eslint-disable-line valid-typeof
// The ChangeEventPlugin registers a "propertychange" event for
// IE. This event does not support bubbling or cancelling, and
// any references to cancelBubble throw "Member not found". A
// typeof check of "unknown" circumvents this issue (and is also
// IE specific).
event.cancelBubble = true;
}
this.isPropagationStopped = emptyFunction.thatReturnsTrue;
},
/**
* We release all dispatched `SyntheticEvent`s after each event loop, adding
* them back into the pool. This allows a way to hold onto a reference that
* won't be added back into the pool.
*/
persist: function () {
this.isPersistent = emptyFunction.thatReturnsTrue;
},
/**
* Checks if this event should be released back into the pool.
*
* @return {boolean} True if this should not be released, false otherwise.
*/
isPersistent: emptyFunction.thatReturnsFalse,
/**
* `PooledClass` looks for `destructor` on each instance it releases.
*/
destructor: function () {
var Interface = this.constructor.Interface;
for (var propName in Interface) {
if (process.env.NODE_ENV !== 'production') {
Object.defineProperty(this, propName, getPooledWarningPropertyDefinition(propName, Interface[propName]));
} else {
this[propName] = null;
}
}
for (var i = 0; i < shouldBeReleasedProperties.length; i++) {
this[shouldBeReleasedProperties[i]] = null;
}
if (process.env.NODE_ENV !== 'production') {
Object.defineProperty(this, 'nativeEvent', getPooledWarningPropertyDefinition('nativeEvent', null));
Object.defineProperty(this, 'preventDefault', getPooledWarningPropertyDefinition('preventDefault', emptyFunction));
Object.defineProperty(this, 'stopPropagation', getPooledWarningPropertyDefinition('stopPropagation', emptyFunction));
}
}
});
SyntheticEvent.Interface = EventInterface;
if (process.env.NODE_ENV !== 'production') {
if (isProxySupported) {
/*eslint-disable no-func-assign */
SyntheticEvent = new Proxy(SyntheticEvent, {
construct: function (target, args) {
return this.apply(target, Object.create(target.prototype), args);
},
apply: function (constructor, that, args) {
return new Proxy(constructor.apply(that, args), {
set: function (target, prop, value) {
if (prop !== 'isPersistent' && !target.constructor.Interface.hasOwnProperty(prop) && shouldBeReleasedProperties.indexOf(prop) === -1) {
process.env.NODE_ENV !== 'production' ? warning(didWarnForAddedNewProperty || target.isPersistent(), 'This synthetic event is reused for performance reasons. If you\'re ' + 'seeing this, you\'re adding a new property in the synthetic event object. ' + 'The property is never released. See ' + 'https://fb.me/react-event-pooling for more information.') : void 0;
didWarnForAddedNewProperty = true;
}
target[prop] = value;
return true;
}
});
}
});
/*eslint-enable no-func-assign */
}
}
/**
* Helper to reduce boilerplate when creating subclasses.
*
* @param {function} Class
* @param {?object} Interface
*/
SyntheticEvent.augmentClass = function (Class, Interface) {
var Super = this;
var E = function () {};
E.prototype = Super.prototype;
var prototype = new E();
_assign(prototype, Class.prototype);
Class.prototype = prototype;
Class.prototype.constructor = Class;
Class.Interface = _assign({}, Super.Interface, Interface);
Class.augmentClass = Super.augmentClass;
PooledClass.addPoolingTo(Class, PooledClass.fourArgumentPooler);
};
PooledClass.addPoolingTo(SyntheticEvent, PooledClass.fourArgumentPooler);
module.exports = SyntheticEvent;
/**
* Helper to nullify syntheticEvent instance properties when destructing
*
* @param {object} SyntheticEvent
* @param {String} propName
* @return {object} defineProperty object
*/
function getPooledWarningPropertyDefinition(propName, getVal) {
var isFunction = typeof getVal === 'function';
return {
configurable: true,
set: set,
get: get
};
function set(val) {
var action = isFunction ? 'setting the method' : 'setting the property';
warn(action, 'This is effectively a no-op');
return val;
}
function get() {
var action = isFunction ? 'accessing the method' : 'accessing the property';
var result = isFunction ? 'This is a no-op function' : 'This is set to null';
warn(action, result);
return getVal;
}
function warn(action, result) {
var warningCondition = false;
process.env.NODE_ENV !== 'production' ? warning(warningCondition, 'This synthetic event is reused for performance reasons. If you\'re seeing this, ' + 'you\'re %s `%s` on a released/nullified synthetic event. %s. ' + 'If you must keep the original synthetic event around, use event.persist(). ' + 'See https://fb.me/react-event-pooling for more information.', action, propName, result) : void 0;
}
}
}).call(this,require('_process'))
},{"./PooledClass":58,"_process":29,"fbjs/lib/emptyFunction":11,"fbjs/lib/warning":26,"object-assign":28}],121:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var SyntheticUIEvent = require('./SyntheticUIEvent');
/**
* @interface FocusEvent
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
var FocusEventInterface = {
relatedTarget: null
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticFocusEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
return SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticUIEvent.augmentClass(SyntheticFocusEvent, FocusEventInterface);
module.exports = SyntheticFocusEvent;
},{"./SyntheticUIEvent":127}],122:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var SyntheticEvent = require('./SyntheticEvent');
/**
* @interface Event
* @see http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105
* /#events-inputevents
*/
var InputEventInterface = {
data: null
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticInputEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticEvent.augmentClass(SyntheticInputEvent, InputEventInterface);
module.exports = SyntheticInputEvent;
},{"./SyntheticEvent":120}],123:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var SyntheticUIEvent = require('./SyntheticUIEvent');
var getEventCharCode = require('./getEventCharCode');
var getEventKey = require('./getEventKey');
var getEventModifierState = require('./getEventModifierState');
/**
* @interface KeyboardEvent
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
var KeyboardEventInterface = {
key: getEventKey,
location: null,
ctrlKey: null,
shiftKey: null,
altKey: null,
metaKey: null,
repeat: null,
locale: null,
getModifierState: getEventModifierState,
// Legacy Interface
charCode: function (event) {
// `charCode` is the result of a KeyPress event and represents the value of
// the actual printable character.
// KeyPress is deprecated, but its replacement is not yet final and not
// implemented in any major browser. Only KeyPress has charCode.
if (event.type === 'keypress') {
return getEventCharCode(event);
}
return 0;
},
keyCode: function (event) {
// `keyCode` is the result of a KeyDown/Up event and represents the value of
// physical keyboard key.
// The actual meaning of the value depends on the users' keyboard layout
// which cannot be detected. Assuming that it is a US keyboard layout
// provides a surprisingly accurate mapping for US and European users.
// Due to this, it is left to the user to implement at this time.
if (event.type === 'keydown' || event.type === 'keyup') {
return event.keyCode;
}
return 0;
},
which: function (event) {
// `which` is an alias for either `keyCode` or `charCode` depending on the
// type of the event.
if (event.type === 'keypress') {
return getEventCharCode(event);
}
if (event.type === 'keydown' || event.type === 'keyup') {
return event.keyCode;
}
return 0;
}
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticKeyboardEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
return SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticUIEvent.augmentClass(SyntheticKeyboardEvent, KeyboardEventInterface);
module.exports = SyntheticKeyboardEvent;
},{"./SyntheticUIEvent":127,"./getEventCharCode":140,"./getEventKey":141,"./getEventModifierState":142}],124:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var SyntheticUIEvent = require('./SyntheticUIEvent');
var ViewportMetrics = require('./ViewportMetrics');
var getEventModifierState = require('./getEventModifierState');
/**
* @interface MouseEvent
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
var MouseEventInterface = {
screenX: null,
screenY: null,
clientX: null,
clientY: null,
ctrlKey: null,
shiftKey: null,
altKey: null,
metaKey: null,
getModifierState: getEventModifierState,
button: function (event) {
// Webkit, Firefox, IE9+
// which: 1 2 3
// button: 0 1 2 (standard)
var button = event.button;
if ('which' in event) {
return button;
}
// IE<9
// which: undefined
// button: 0 0 0
// button: 1 4 2 (onmouseup)
return button === 2 ? 2 : button === 4 ? 1 : 0;
},
buttons: null,
relatedTarget: function (event) {
return event.relatedTarget || (event.fromElement === event.srcElement ? event.toElement : event.fromElement);
},
// "Proprietary" Interface.
pageX: function (event) {
return 'pageX' in event ? event.pageX : event.clientX + ViewportMetrics.currentScrollLeft;
},
pageY: function (event) {
return 'pageY' in event ? event.pageY : event.clientY + ViewportMetrics.currentScrollTop;
}
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticMouseEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
return SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticUIEvent.augmentClass(SyntheticMouseEvent, MouseEventInterface);
module.exports = SyntheticMouseEvent;
},{"./SyntheticUIEvent":127,"./ViewportMetrics":130,"./getEventModifierState":142}],125:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var SyntheticUIEvent = require('./SyntheticUIEvent');
var getEventModifierState = require('./getEventModifierState');
/**
* @interface TouchEvent
* @see http://www.w3.org/TR/touch-events/
*/
var TouchEventInterface = {
touches: null,
targetTouches: null,
changedTouches: null,
altKey: null,
metaKey: null,
ctrlKey: null,
shiftKey: null,
getModifierState: getEventModifierState
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticTouchEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
return SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticUIEvent.augmentClass(SyntheticTouchEvent, TouchEventInterface);
module.exports = SyntheticTouchEvent;
},{"./SyntheticUIEvent":127,"./getEventModifierState":142}],126:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var SyntheticEvent = require('./SyntheticEvent');
/**
* @interface Event
* @see http://www.w3.org/TR/2009/WD-css3-transitions-20090320/#transition-events-
* @see https://developer.mozilla.org/en-US/docs/Web/API/TransitionEvent
*/
var TransitionEventInterface = {
propertyName: null,
elapsedTime: null,
pseudoElement: null
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticEvent}
*/
function SyntheticTransitionEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticEvent.augmentClass(SyntheticTransitionEvent, TransitionEventInterface);
module.exports = SyntheticTransitionEvent;
},{"./SyntheticEvent":120}],127:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var SyntheticEvent = require('./SyntheticEvent');
var getEventTarget = require('./getEventTarget');
/**
* @interface UIEvent
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
var UIEventInterface = {
view: function (event) {
if (event.view) {
return event.view;
}
var target = getEventTarget(event);
if (target.window === target) {
// target is a window object
return target;
}
var doc = target.ownerDocument;
// TODO: Figure out why `ownerDocument` is sometimes undefined in IE8.
if (doc) {
return doc.defaultView || doc.parentWindow;
} else {
return window;
}
},
detail: function (event) {
return event.detail || 0;
}
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticEvent}
*/
function SyntheticUIEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticEvent.augmentClass(SyntheticUIEvent, UIEventInterface);
module.exports = SyntheticUIEvent;
},{"./SyntheticEvent":120,"./getEventTarget":143}],128:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var SyntheticMouseEvent = require('./SyntheticMouseEvent');
/**
* @interface WheelEvent
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
var WheelEventInterface = {
deltaX: function (event) {
return 'deltaX' in event ? event.deltaX :
// Fallback to `wheelDeltaX` for Webkit and normalize (right is positive).
'wheelDeltaX' in event ? -event.wheelDeltaX : 0;
},
deltaY: function (event) {
return 'deltaY' in event ? event.deltaY :
// Fallback to `wheelDeltaY` for Webkit and normalize (down is positive).
'wheelDeltaY' in event ? -event.wheelDeltaY :
// Fallback to `wheelDelta` for IE<9 and normalize (down is positive).
'wheelDelta' in event ? -event.wheelDelta : 0;
},
deltaZ: null,
// Browsers without "deltaMode" is reporting in raw wheel delta where one
// notch on the scroll is always +/- 120, roughly equivalent to pixels.
// A good approximation of DOM_DELTA_LINE (1) is 5% of viewport size or
// ~40 pixels, for DOM_DELTA_SCREEN (2) it is 87.5% of viewport size.
deltaMode: null
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticMouseEvent}
*/
function SyntheticWheelEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
return SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticMouseEvent.augmentClass(SyntheticWheelEvent, WheelEventInterface);
module.exports = SyntheticWheelEvent;
},{"./SyntheticMouseEvent":124}],129:[function(require,module,exports){
(function (process){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
'use strict';
var _prodInvariant = require('./reactProdInvariant');
var invariant = require('fbjs/lib/invariant');
var OBSERVED_ERROR = {};
/**
* `Transaction` creates a black box that is able to wrap any method such that
* certain invariants are maintained before and after the method is invoked
* (Even if an exception is thrown while invoking the wrapped method). Whoever
* instantiates a transaction can provide enforcers of the invariants at
* creation time. The `Transaction` class itself will supply one additional
* automatic invariant for you - the invariant that any transaction instance
* should not be run while it is already being run. You would typically create a
* single instance of a `Transaction` for reuse multiple times, that potentially
* is used to wrap several different methods. Wrappers are extremely simple -
* they only require implementing two methods.
*
* <pre>
* wrappers (injected at creation time)
* + +
* | |
* +-----------------|--------|--------------+
* | v | |
* | +---------------+ | |
* | +--| wrapper1 |---|----+ |
* | | +---------------+ v | |
* | | +-------------+ | |
* | | +----| wrapper2 |--------+ |
* | | | +-------------+ | | |
* | | | | | |
* | v v v v | wrapper
* | +---+ +---+ +---------+ +---+ +---+ | invariants
* perform(anyMethod) | | | | | | | | | | | | maintained
* +----------------->|-|---|-|---|-->|anyMethod|---|---|-|---|-|-------->
* | | | | | | | | | | | |
* | | | | | | | | | | | |
* | | | | | | | | | | | |
* | +---+ +---+ +---------+ +---+ +---+ |
* | initialize close |
* +-----------------------------------------+
* </pre>
*
* Use cases:
* - Preserving the input selection ranges before/after reconciliation.
* Restoring selection even in the event of an unexpected error.
* - Deactivating events while rearranging the DOM, preventing blurs/focuses,
* while guaranteeing that afterwards, the event system is reactivated.
* - Flushing a queue of collected DOM mutations to the main UI thread after a
* reconciliation takes place in a worker thread.
* - Invoking any collected `componentDidUpdate` callbacks after rendering new
* content.
* - (Future use case): Wrapping particular flushes of the `ReactWorker` queue
* to preserve the `scrollTop` (an automatic scroll aware DOM).
* - (Future use case): Layout calculations before and after DOM updates.
*
* Transactional plugin API:
* - A module that has an `initialize` method that returns any precomputation.
* - and a `close` method that accepts the precomputation. `close` is invoked
* when the wrapped process is completed, or has failed.
*
* @param {Array<TransactionalWrapper>} transactionWrapper Wrapper modules
* that implement `initialize` and `close`.
* @return {Transaction} Single transaction for reuse in thread.
*
* @class Transaction
*/
var TransactionImpl = {
/**
* Sets up this instance so that it is prepared for collecting metrics. Does
* so such that this setup method may be used on an instance that is already
* initialized, in a way that does not consume additional memory upon reuse.
* That can be useful if you decide to make your subclass of this mixin a
* "PooledClass".
*/
reinitializeTransaction: function () {
this.transactionWrappers = this.getTransactionWrappers();
if (this.wrapperInitData) {
this.wrapperInitData.length = 0;
} else {
this.wrapperInitData = [];
}
this._isInTransaction = false;
},
_isInTransaction: false,
/**
* @abstract
* @return {Array<TransactionWrapper>} Array of transaction wrappers.
*/
getTransactionWrappers: null,
isInTransaction: function () {
return !!this._isInTransaction;
},
/**
* Executes the function within a safety window. Use this for the top level
* methods that result in large amounts of computation/mutations that would
* need to be safety checked. The optional arguments helps prevent the need
* to bind in many cases.
*
* @param {function} method Member of scope to call.
* @param {Object} scope Scope to invoke from.
* @param {Object?=} a Argument to pass to the method.
* @param {Object?=} b Argument to pass to the method.
* @param {Object?=} c Argument to pass to the method.
* @param {Object?=} d Argument to pass to the method.
* @param {Object?=} e Argument to pass to the method.
* @param {Object?=} f Argument to pass to the method.
*
* @return {*} Return value from `method`.
*/
perform: function (method, scope, a, b, c, d, e, f) {
!!this.isInTransaction() ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Transaction.perform(...): Cannot initialize a transaction when there is already an outstanding transaction.') : _prodInvariant('27') : void 0;
var errorThrown;
var ret;
try {
this._isInTransaction = true;
// Catching errors makes debugging more difficult, so we start with
// errorThrown set to true before setting it to false after calling
// close -- if it's still set to true in the finally block, it means
// one of these calls threw.
errorThrown = true;
this.initializeAll(0);
ret = method.call(scope, a, b, c, d, e, f);
errorThrown = false;
} finally {
try {
if (errorThrown) {
// If `method` throws, prefer to show that stack trace over any thrown
// by invoking `closeAll`.
try {
this.closeAll(0);
} catch (err) {}
} else {
// Since `method` didn't throw, we don't want to silence the exception
// here.
this.closeAll(0);
}
} finally {
this._isInTransaction = false;
}
}
return ret;
},
initializeAll: function (startIndex) {
var transactionWrappers = this.transactionWrappers;
for (var i = startIndex; i < transactionWrappers.length; i++) {
var wrapper = transactionWrappers[i];
try {
// Catching errors makes debugging more difficult, so we start with the
// OBSERVED_ERROR state before overwriting it with the real return value
// of initialize -- if it's still set to OBSERVED_ERROR in the finally
// block, it means wrapper.initialize threw.
this.wrapperInitData[i] = OBSERVED_ERROR;
this.wrapperInitData[i] = wrapper.initialize ? wrapper.initialize.call(this) : null;
} finally {
if (this.wrapperInitData[i] === OBSERVED_ERROR) {
// The initializer for wrapper i threw an error; initialize the
// remaining wrappers but silence any exceptions from them to ensure
// that the first error is the one to bubble up.
try {
this.initializeAll(i + 1);
} catch (err) {}
}
}
}
},
/**
* Invokes each of `this.transactionWrappers.close[i]` functions, passing into
* them the respective return values of `this.transactionWrappers.init[i]`
* (`close`rs that correspond to initializers that failed will not be
* invoked).
*/
closeAll: function (startIndex) {
!this.isInTransaction() ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Transaction.closeAll(): Cannot close transaction when none are open.') : _prodInvariant('28') : void 0;
var transactionWrappers = this.transactionWrappers;
for (var i = startIndex; i < transactionWrappers.length; i++) {
var wrapper = transactionWrappers[i];
var initData = this.wrapperInitData[i];
var errorThrown;
try {
// Catching errors makes debugging more difficult, so we start with
// errorThrown set to true before setting it to false after calling
// close -- if it's still set to true in the finally block, it means
// wrapper.close threw.
errorThrown = true;
if (initData !== OBSERVED_ERROR && wrapper.close) {
wrapper.close.call(this, initData);
}
errorThrown = false;
} finally {
if (errorThrown) {
// The closer for wrapper i threw an error; close the remaining
// wrappers but silence any exceptions from them to ensure that the
// first error is the one to bubble up.
try {
this.closeAll(i + 1);
} catch (e) {}
}
}
}
this.wrapperInitData.length = 0;
}
};
module.exports = TransactionImpl;
}).call(this,require('_process'))
},{"./reactProdInvariant":153,"_process":29,"fbjs/lib/invariant":19}],130:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var ViewportMetrics = {
currentScrollLeft: 0,
currentScrollTop: 0,
refreshScrollValues: function (scrollPosition) {
ViewportMetrics.currentScrollLeft = scrollPosition.x;
ViewportMetrics.currentScrollTop = scrollPosition.y;
}
};
module.exports = ViewportMetrics;
},{}],131:[function(require,module,exports){
(function (process){
/**
* Copyright 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
'use strict';
var _prodInvariant = require('./reactProdInvariant');
var invariant = require('fbjs/lib/invariant');
/**
* Accumulates items that must not be null or undefined into the first one. This
* is used to conserve memory by avoiding array allocations, and thus sacrifices
* API cleanness. Since `current` can be null before being passed in and not
* null after this function, make sure to assign it back to `current`:
*
* `a = accumulateInto(a, b);`
*
* This API should be sparingly used. Try `accumulate` for something cleaner.
*
* @return {*|array<*>} An accumulation of items.
*/
function accumulateInto(current, next) {
!(next != null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'accumulateInto(...): Accumulated items must not be null or undefined.') : _prodInvariant('30') : void 0;
if (current == null) {
return next;
}
// Both are not empty. Warning: Never call x.concat(y) when you are not
// certain that x is an Array (x could be a string with concat method).
if (Array.isArray(current)) {
if (Array.isArray(next)) {
current.push.apply(current, next);
return current;
}
current.push(next);
return current;
}
if (Array.isArray(next)) {
// A bit too dangerous to mutate `next`.
return [current].concat(next);
}
return [current, next];
}
module.exports = accumulateInto;
}).call(this,require('_process'))
},{"./reactProdInvariant":153,"_process":29,"fbjs/lib/invariant":19}],132:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
'use strict';
var MOD = 65521;
// adler32 is not cryptographically strong, and is only used to sanity check that
// markup generated on the server matches the markup generated on the client.
// This implementation (a modified version of the SheetJS version) has been optimized
// for our use case, at the expense of conforming to the adler32 specification
// for non-ascii inputs.
function adler32(data) {
var a = 1;
var b = 0;
var i = 0;
var l = data.length;
var m = l & ~0x3;
while (i < m) {
var n = Math.min(i + 4096, m);
for (; i < n; i += 4) {
b += (a += data.charCodeAt(i)) + (a += data.charCodeAt(i + 1)) + (a += data.charCodeAt(i + 2)) + (a += data.charCodeAt(i + 3));
}
a %= MOD;
b %= MOD;
}
for (; i < l; i++) {
b += a += data.charCodeAt(i);
}
a %= MOD;
b %= MOD;
return a | b << 16;
}
module.exports = adler32;
},{}],133:[function(require,module,exports){
(function (process){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var _prodInvariant = require('./reactProdInvariant');
var ReactPropTypeLocationNames = require('./ReactPropTypeLocationNames');
var ReactPropTypesSecret = require('./ReactPropTypesSecret');
var invariant = require('fbjs/lib/invariant');
var warning = require('fbjs/lib/warning');
var ReactComponentTreeHook;
if (typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'test') {
// Temporary hack.
// Inline requires don't work well with Jest:
// https://github.com/facebook/react/issues/7240
// Remove the inline requires when we don't need them anymore:
// https://github.com/facebook/react/pull/7178
ReactComponentTreeHook = require('react/lib/ReactComponentTreeHook');
}
var loggedTypeFailures = {};
/**
* Assert that the values match with the type specs.
* Error messages are memorized and will only be shown once.
*
* @param {object} typeSpecs Map of name to a ReactPropType
* @param {object} values Runtime values that need to be type-checked
* @param {string} location e.g. "prop", "context", "child context"
* @param {string} componentName Name of the component for error messages.
* @param {?object} element The React element that is being type-checked
* @param {?number} debugID The React component instance that is being type-checked
* @private
*/
function checkReactTypeSpec(typeSpecs, values, location, componentName, element, debugID) {
for (var typeSpecName in typeSpecs) {
if (typeSpecs.hasOwnProperty(typeSpecName)) {
var error;
// Prop type validation may throw. In case they do, we don't want to
// fail the render phase where it didn't fail before. So we log it.
// After these have been cleaned up, we'll let them throw.
try {
// This is intentionally an invariant that gets caught. It's the same
// behavior as without this statement except with a better message.
!(typeof typeSpecs[typeSpecName] === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s: %s type `%s` is invalid; it must be a function, usually from React.PropTypes.', componentName || 'React class', ReactPropTypeLocationNames[location], typeSpecName) : _prodInvariant('84', componentName || 'React class', ReactPropTypeLocationNames[location], typeSpecName) : void 0;
error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret);
} catch (ex) {
error = ex;
}
process.env.NODE_ENV !== 'production' ? warning(!error || error instanceof Error, '%s: type specification of %s `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', ReactPropTypeLocationNames[location], typeSpecName, typeof error) : void 0;
if (error instanceof Error && !(error.message in loggedTypeFailures)) {
// Only monitor this failure once because there tends to be a lot of the
// same error.
loggedTypeFailures[error.message] = true;
var componentStackInfo = '';
if (process.env.NODE_ENV !== 'production') {
if (!ReactComponentTreeHook) {
ReactComponentTreeHook = require('react/lib/ReactComponentTreeHook');
}
if (debugID !== null) {
componentStackInfo = ReactComponentTreeHook.getStackAddendumByID(debugID);
} else if (element !== null) {
componentStackInfo = ReactComponentTreeHook.getCurrentStackAddendum(element);
}
}
process.env.NODE_ENV !== 'production' ? warning(false, 'Failed %s type: %s%s', location, error.message, componentStackInfo) : void 0;
}
}
}
}
module.exports = checkReactTypeSpec;
}).call(this,require('_process'))
},{"./ReactPropTypeLocationNames":103,"./ReactPropTypesSecret":104,"./reactProdInvariant":153,"_process":29,"fbjs/lib/invariant":19,"fbjs/lib/warning":26,"react/lib/ReactComponentTreeHook":168}],134:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
/* globals MSApp */
'use strict';
/**
* Create a function which has 'unsafe' privileges (required by windows8 apps)
*/
var createMicrosoftUnsafeLocalFunction = function (func) {
if (typeof MSApp !== 'undefined' && MSApp.execUnsafeLocalFunction) {
return function (arg0, arg1, arg2, arg3) {
MSApp.execUnsafeLocalFunction(function () {
return func(arg0, arg1, arg2, arg3);
});
};
} else {
return func;
}
};
module.exports = createMicrosoftUnsafeLocalFunction;
},{}],135:[function(require,module,exports){
(function (process){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var CSSProperty = require('./CSSProperty');
var warning = require('fbjs/lib/warning');
var isUnitlessNumber = CSSProperty.isUnitlessNumber;
var styleWarnings = {};
/**
* Convert a value into the proper css writable value. The style name `name`
* should be logical (no hyphens), as specified
* in `CSSProperty.isUnitlessNumber`.
*
* @param {string} name CSS property name such as `topMargin`.
* @param {*} value CSS property value such as `10px`.
* @param {ReactDOMComponent} component
* @return {string} Normalized style value with dimensions applied.
*/
function dangerousStyleValue(name, value, component) {
// Note that we've removed escapeTextForBrowser() calls here since the
// whole string will be escaped when the attribute is injected into
// the markup. If you provide unsafe user data here they can inject
// arbitrary CSS which may be problematic (I couldn't repro this):
// https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet
// http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/
// This is not an XSS hole but instead a potential CSS injection issue
// which has lead to a greater discussion about how we're going to
// trust URLs moving forward. See #2115901
var isEmpty = value == null || typeof value === 'boolean' || value === '';
if (isEmpty) {
return '';
}
var isNonNumeric = isNaN(value);
if (isNonNumeric || value === 0 || isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name]) {
return '' + value; // cast to string
}
if (typeof value === 'string') {
if (process.env.NODE_ENV !== 'production') {
// Allow '0' to pass through without warning. 0 is already special and
// doesn't require units, so we don't need to warn about it.
if (component && value !== '0') {
var owner = component._currentElement._owner;
var ownerName = owner ? owner.getName() : null;
if (ownerName && !styleWarnings[ownerName]) {
styleWarnings[ownerName] = {};
}
var warned = false;
if (ownerName) {
var warnings = styleWarnings[ownerName];
warned = warnings[name];
if (!warned) {
warnings[name] = true;
}
}
if (!warned) {
process.env.NODE_ENV !== 'production' ? warning(false, 'a `%s` tag (owner: `%s`) was passed a numeric string value ' + 'for CSS property `%s` (value: `%s`) which will be treated ' + 'as a unitless number in a future version of React.', component._currentElement.type, ownerName || 'unknown', name, value) : void 0;
}
}
}
value = value.trim();
}
return value + 'px';
}
module.exports = dangerousStyleValue;
}).call(this,require('_process'))
},{"./CSSProperty":38,"_process":29,"fbjs/lib/warning":26}],136:[function(require,module,exports){
/**
* Copyright 2016-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* Based on the escape-html library, which is used under the MIT License below:
*
* Copyright (c) 2012-2013 TJ Holowaychuk
* Copyright (c) 2015 Andreas Lubbe
* Copyright (c) 2015 Tiancheng "Timothy" Gu
*
* 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.
*
*/
'use strict';
// code copied and modified from escape-html
/**
* Module variables.
* @private
*/
var matchHtmlRegExp = /["'&<>]/;
/**
* Escape special characters in the given string of html.
*
* @param {string} string The string to escape for inserting into HTML
* @return {string}
* @public
*/
function escapeHtml(string) {
var str = '' + string;
var match = matchHtmlRegExp.exec(str);
if (!match) {
return str;
}
var escape;
var html = '';
var index = 0;
var lastIndex = 0;
for (index = match.index; index < str.length; index++) {
switch (str.charCodeAt(index)) {
case 34:
// "
escape = '"';
break;
case 38:
// &
escape = '&';
break;
case 39:
// '
escape = '''; // modified from escape-html; used to be '''
break;
case 60:
// <
escape = '<';
break;
case 62:
// >
escape = '>';
break;
default:
continue;
}
if (lastIndex !== index) {
html += str.substring(lastIndex, index);
}
lastIndex = index + 1;
html += escape;
}
return lastIndex !== index ? html + str.substring(lastIndex, index) : html;
}
// end code copied and modified from escape-html
/**
* Escapes text to prevent scripting attacks.
*
* @param {*} text Text value to escape.
* @return {string} An escaped string.
*/
function escapeTextContentForBrowser(text) {
if (typeof text === 'boolean' || typeof text === 'number') {
// this shortcircuit helps perf for types that we know will never have
// special characters, especially given that this function is used often
// for numeric dom ids.
return '' + text;
}
return escapeHtml(text);
}
module.exports = escapeTextContentForBrowser;
},{}],137:[function(require,module,exports){
(function (process){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var _prodInvariant = require('./reactProdInvariant');
var ReactCurrentOwner = require('react/lib/ReactCurrentOwner');
var ReactDOMComponentTree = require('./ReactDOMComponentTree');
var ReactInstanceMap = require('./ReactInstanceMap');
var getHostComponentFromComposite = require('./getHostComponentFromComposite');
var invariant = require('fbjs/lib/invariant');
var warning = require('fbjs/lib/warning');
/**
* Returns the DOM node rendered by this element.
*
* See https://facebook.github.io/react/docs/top-level-api.html#reactdom.finddomnode
*
* @param {ReactComponent|DOMElement} componentOrElement
* @return {?DOMElement} The root node of this element.
*/
function findDOMNode(componentOrElement) {
if (process.env.NODE_ENV !== 'production') {
var owner = ReactCurrentOwner.current;
if (owner !== null) {
process.env.NODE_ENV !== 'production' ? warning(owner._warnedAboutRefsInRender, '%s is accessing findDOMNode inside its render(). ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', owner.getName() || 'A component') : void 0;
owner._warnedAboutRefsInRender = true;
}
}
if (componentOrElement == null) {
return null;
}
if (componentOrElement.nodeType === 1) {
return componentOrElement;
}
var inst = ReactInstanceMap.get(componentOrElement);
if (inst) {
inst = getHostComponentFromComposite(inst);
return inst ? ReactDOMComponentTree.getNodeFromInstance(inst) : null;
}
if (typeof componentOrElement.render === 'function') {
!false ? process.env.NODE_ENV !== 'production' ? invariant(false, 'findDOMNode was called on an unmounted component.') : _prodInvariant('44') : void 0;
} else {
!false ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Element appears to be neither ReactComponent nor DOMNode (keys: %s)', Object.keys(componentOrElement)) : _prodInvariant('45', Object.keys(componentOrElement)) : void 0;
}
}
module.exports = findDOMNode;
}).call(this,require('_process'))
},{"./ReactDOMComponentTree":67,"./ReactInstanceMap":95,"./getHostComponentFromComposite":144,"./reactProdInvariant":153,"_process":29,"fbjs/lib/invariant":19,"fbjs/lib/warning":26,"react/lib/ReactCurrentOwner":169}],138:[function(require,module,exports){
(function (process){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
'use strict';
var KeyEscapeUtils = require('./KeyEscapeUtils');
var traverseAllChildren = require('./traverseAllChildren');
var warning = require('fbjs/lib/warning');
var ReactComponentTreeHook;
if (typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'test') {
// Temporary hack.
// Inline requires don't work well with Jest:
// https://github.com/facebook/react/issues/7240
// Remove the inline requires when we don't need them anymore:
// https://github.com/facebook/react/pull/7178
ReactComponentTreeHook = require('react/lib/ReactComponentTreeHook');
}
/**
* @param {function} traverseContext Context passed through traversal.
* @param {?ReactComponent} child React child component.
* @param {!string} name String name of key path to child.
* @param {number=} selfDebugID Optional debugID of the current internal instance.
*/
function flattenSingleChildIntoContext(traverseContext, child, name, selfDebugID) {
// We found a component instance.
if (traverseContext && typeof traverseContext === 'object') {
var result = traverseContext;
var keyUnique = result[name] === undefined;
if (process.env.NODE_ENV !== 'production') {
if (!ReactComponentTreeHook) {
ReactComponentTreeHook = require('react/lib/ReactComponentTreeHook');
}
if (!keyUnique) {
process.env.NODE_ENV !== 'production' ? warning(false, 'flattenChildren(...): Encountered two children with the same key, ' + '`%s`. Child keys must be unique; when two children share a key, only ' + 'the first child will be used.%s', KeyEscapeUtils.unescape(name), ReactComponentTreeHook.getStackAddendumByID(selfDebugID)) : void 0;
}
}
if (keyUnique && child != null) {
result[name] = child;
}
}
}
/**
* Flattens children that are typically specified as `props.children`. Any null
* children will not be included in the resulting object.
* @return {!object} flattened children keyed by name.
*/
function flattenChildren(children, selfDebugID) {
if (children == null) {
return children;
}
var result = {};
if (process.env.NODE_ENV !== 'production') {
traverseAllChildren(children, function (traverseContext, child, name) {
return flattenSingleChildIntoContext(traverseContext, child, name, selfDebugID);
}, result);
} else {
traverseAllChildren(children, flattenSingleChildIntoContext, result);
}
return result;
}
module.exports = flattenChildren;
}).call(this,require('_process'))
},{"./KeyEscapeUtils":56,"./traverseAllChildren":158,"_process":29,"fbjs/lib/warning":26,"react/lib/ReactComponentTreeHook":168}],139:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
'use strict';
/**
* @param {array} arr an "accumulation" of items which is either an Array or
* a single item. Useful when paired with the `accumulate` module. This is a
* simple utility that allows us to reason about a collection of items, but
* handling the case when there is exactly one item (and we do not need to
* allocate an array).
*/
function forEachAccumulated(arr, cb, scope) {
if (Array.isArray(arr)) {
arr.forEach(cb, scope);
} else if (arr) {
cb.call(scope, arr);
}
}
module.exports = forEachAccumulated;
},{}],140:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
/**
* `charCode` represents the actual "character code" and is safe to use with
* `String.fromCharCode`. As such, only keys that correspond to printable
* characters produce a valid `charCode`, the only exception to this is Enter.
* The Tab-key is considered non-printable and does not have a `charCode`,
* presumably because it does not produce a tab-character in browsers.
*
* @param {object} nativeEvent Native browser event.
* @return {number} Normalized `charCode` property.
*/
function getEventCharCode(nativeEvent) {
var charCode;
var keyCode = nativeEvent.keyCode;
if ('charCode' in nativeEvent) {
charCode = nativeEvent.charCode;
// FF does not set `charCode` for the Enter-key, check against `keyCode`.
if (charCode === 0 && keyCode === 13) {
charCode = 13;
}
} else {
// IE8 does not implement `charCode`, but `keyCode` has the correct value.
charCode = keyCode;
}
// Some non-printable keys are reported in `charCode`/`keyCode`, discard them.
// Must not discard the (non-)printable Enter-key.
if (charCode >= 32 || charCode === 13) {
return charCode;
}
return 0;
}
module.exports = getEventCharCode;
},{}],141:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var getEventCharCode = require('./getEventCharCode');
/**
* Normalization of deprecated HTML5 `key` values
* @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names
*/
var normalizeKey = {
'Esc': 'Escape',
'Spacebar': ' ',
'Left': 'ArrowLeft',
'Up': 'ArrowUp',
'Right': 'ArrowRight',
'Down': 'ArrowDown',
'Del': 'Delete',
'Win': 'OS',
'Menu': 'ContextMenu',
'Apps': 'ContextMenu',
'Scroll': 'ScrollLock',
'MozPrintableKey': 'Unidentified'
};
/**
* Translation from legacy `keyCode` to HTML5 `key`
* Only special keys supported, all others depend on keyboard layout or browser
* @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names
*/
var translateToKey = {
8: 'Backspace',
9: 'Tab',
12: 'Clear',
13: 'Enter',
16: 'Shift',
17: 'Control',
18: 'Alt',
19: 'Pause',
20: 'CapsLock',
27: 'Escape',
32: ' ',
33: 'PageUp',
34: 'PageDown',
35: 'End',
36: 'Home',
37: 'ArrowLeft',
38: 'ArrowUp',
39: 'ArrowRight',
40: 'ArrowDown',
45: 'Insert',
46: 'Delete',
112: 'F1', 113: 'F2', 114: 'F3', 115: 'F4', 116: 'F5', 117: 'F6',
118: 'F7', 119: 'F8', 120: 'F9', 121: 'F10', 122: 'F11', 123: 'F12',
144: 'NumLock',
145: 'ScrollLock',
224: 'Meta'
};
/**
* @param {object} nativeEvent Native browser event.
* @return {string} Normalized `key` property.
*/
function getEventKey(nativeEvent) {
if (nativeEvent.key) {
// Normalize inconsistent values reported by browsers due to
// implementations of a working draft specification.
// FireFox implements `key` but returns `MozPrintableKey` for all
// printable characters (normalized to `Unidentified`), ignore it.
var key = normalizeKey[nativeEvent.key] || nativeEvent.key;
if (key !== 'Unidentified') {
return key;
}
}
// Browser does not implement `key`, polyfill as much of it as we can.
if (nativeEvent.type === 'keypress') {
var charCode = getEventCharCode(nativeEvent);
// The enter-key is technically both printable and non-printable and can
// thus be captured by `keypress`, no other non-printable key should.
return charCode === 13 ? 'Enter' : String.fromCharCode(charCode);
}
if (nativeEvent.type === 'keydown' || nativeEvent.type === 'keyup') {
// While user keyboard layout determines the actual meaning of each
// `keyCode` value, almost all function keys have a universal value.
return translateToKey[nativeEvent.keyCode] || 'Unidentified';
}
return '';
}
module.exports = getEventKey;
},{"./getEventCharCode":140}],142:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
/**
* Translation from modifier key to the associated property in the event.
* @see http://www.w3.org/TR/DOM-Level-3-Events/#keys-Modifiers
*/
var modifierKeyToProp = {
'Alt': 'altKey',
'Control': 'ctrlKey',
'Meta': 'metaKey',
'Shift': 'shiftKey'
};
// IE8 does not implement getModifierState so we simply map it to the only
// modifier keys exposed by the event itself, does not support Lock-keys.
// Currently, all major browsers except Chrome seems to support Lock-keys.
function modifierStateGetter(keyArg) {
var syntheticEvent = this;
var nativeEvent = syntheticEvent.nativeEvent;
if (nativeEvent.getModifierState) {
return nativeEvent.getModifierState(keyArg);
}
var keyProp = modifierKeyToProp[keyArg];
return keyProp ? !!nativeEvent[keyProp] : false;
}
function getEventModifierState(nativeEvent) {
return modifierStateGetter;
}
module.exports = getEventModifierState;
},{}],143:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
/**
* Gets the target node from a native browser event by accounting for
* inconsistencies in browser DOM APIs.
*
* @param {object} nativeEvent Native browser event.
* @return {DOMEventTarget} Target node.
*/
function getEventTarget(nativeEvent) {
var target = nativeEvent.target || nativeEvent.srcElement || window;
// Normalize SVG <use> element events #4963
if (target.correspondingUseElement) {
target = target.correspondingUseElement;
}
// Safari may fire events on text nodes (Node.TEXT_NODE is 3).
// @see http://www.quirksmode.org/js/events_properties.html
return target.nodeType === 3 ? target.parentNode : target;
}
module.exports = getEventTarget;
},{}],144:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var ReactNodeTypes = require('./ReactNodeTypes');
function getHostComponentFromComposite(inst) {
var type;
while ((type = inst._renderedNodeType) === ReactNodeTypes.COMPOSITE) {
inst = inst._renderedComponent;
}
if (type === ReactNodeTypes.HOST) {
return inst._renderedComponent;
} else if (type === ReactNodeTypes.EMPTY) {
return null;
}
}
module.exports = getHostComponentFromComposite;
},{"./ReactNodeTypes":101}],145:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
'use strict';
/* global Symbol */
var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec.
/**
* Returns the iterator method function contained on the iterable object.
*
* Be sure to invoke the function with the iterable as context:
*
* var iteratorFn = getIteratorFn(myIterable);
* if (iteratorFn) {
* var iterator = iteratorFn.call(myIterable);
* ...
* }
*
* @param {?object} maybeIterable
* @return {?function}
*/
function getIteratorFn(maybeIterable) {
var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]);
if (typeof iteratorFn === 'function') {
return iteratorFn;
}
}
module.exports = getIteratorFn;
},{}],146:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
/**
* Given any node return the first leaf node without children.
*
* @param {DOMElement|DOMTextNode} node
* @return {DOMElement|DOMTextNode}
*/
function getLeafNode(node) {
while (node && node.firstChild) {
node = node.firstChild;
}
return node;
}
/**
* Get the next sibling within a container. This will walk up the
* DOM if a node's siblings have been exhausted.
*
* @param {DOMElement|DOMTextNode} node
* @return {?DOMElement|DOMTextNode}
*/
function getSiblingNode(node) {
while (node) {
if (node.nextSibling) {
return node.nextSibling;
}
node = node.parentNode;
}
}
/**
* Get object describing the nodes which contain characters at offset.
*
* @param {DOMElement|DOMTextNode} root
* @param {number} offset
* @return {?object}
*/
function getNodeForCharacterOffset(root, offset) {
var node = getLeafNode(root);
var nodeStart = 0;
var nodeEnd = 0;
while (node) {
if (node.nodeType === 3) {
nodeEnd = nodeStart + node.textContent.length;
if (nodeStart <= offset && nodeEnd >= offset) {
return {
node: node,
offset: offset - nodeStart
};
}
nodeStart = nodeEnd;
}
node = getLeafNode(getSiblingNode(node));
}
}
module.exports = getNodeForCharacterOffset;
},{}],147:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var ExecutionEnvironment = require('fbjs/lib/ExecutionEnvironment');
var contentKey = null;
/**
* Gets the key used to access text content on a DOM node.
*
* @return {?string} Key used to access text content.
* @internal
*/
function getTextContentAccessor() {
if (!contentKey && ExecutionEnvironment.canUseDOM) {
// Prefer textContent to innerText because many browsers support both but
// SVG <text> elements don't support innerText even when <div> does.
contentKey = 'textContent' in document.documentElement ? 'textContent' : 'innerText';
}
return contentKey;
}
module.exports = getTextContentAccessor;
},{"fbjs/lib/ExecutionEnvironment":5}],148:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var ExecutionEnvironment = require('fbjs/lib/ExecutionEnvironment');
/**
* Generate a mapping of standard vendor prefixes using the defined style property and event name.
*
* @param {string} styleProp
* @param {string} eventName
* @returns {object}
*/
function makePrefixMap(styleProp, eventName) {
var prefixes = {};
prefixes[styleProp.toLowerCase()] = eventName.toLowerCase();
prefixes['Webkit' + styleProp] = 'webkit' + eventName;
prefixes['Moz' + styleProp] = 'moz' + eventName;
prefixes['ms' + styleProp] = 'MS' + eventName;
prefixes['O' + styleProp] = 'o' + eventName.toLowerCase();
return prefixes;
}
/**
* A list of event names to a configurable list of vendor prefixes.
*/
var vendorPrefixes = {
animationend: makePrefixMap('Animation', 'AnimationEnd'),
animationiteration: makePrefixMap('Animation', 'AnimationIteration'),
animationstart: makePrefixMap('Animation', 'AnimationStart'),
transitionend: makePrefixMap('Transition', 'TransitionEnd')
};
/**
* Event names that have already been detected and prefixed (if applicable).
*/
var prefixedEventNames = {};
/**
* Element to check for prefixes on.
*/
var style = {};
/**
* Bootstrap if a DOM exists.
*/
if (ExecutionEnvironment.canUseDOM) {
style = document.createElement('div').style;
// On some platforms, in particular some releases of Android 4.x,
// the un-prefixed "animation" and "transition" properties are defined on the
// style object but the events that fire will still be prefixed, so we need
// to check if the un-prefixed events are usable, and if not remove them from the map.
if (!('AnimationEvent' in window)) {
delete vendorPrefixes.animationend.animation;
delete vendorPrefixes.animationiteration.animation;
delete vendorPrefixes.animationstart.animation;
}
// Same as above
if (!('TransitionEvent' in window)) {
delete vendorPrefixes.transitionend.transition;
}
}
/**
* Attempts to determine the correct vendor prefixed event name.
*
* @param {string} eventName
* @returns {string}
*/
function getVendorPrefixedEventName(eventName) {
if (prefixedEventNames[eventName]) {
return prefixedEventNames[eventName];
} else if (!vendorPrefixes[eventName]) {
return eventName;
}
var prefixMap = vendorPrefixes[eventName];
for (var styleProp in prefixMap) {
if (prefixMap.hasOwnProperty(styleProp) && styleProp in style) {
return prefixedEventNames[eventName] = prefixMap[styleProp];
}
}
return '';
}
module.exports = getVendorPrefixedEventName;
},{"fbjs/lib/ExecutionEnvironment":5}],149:[function(require,module,exports){
(function (process){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var _prodInvariant = require('./reactProdInvariant'),
_assign = require('object-assign');
var ReactCompositeComponent = require('./ReactCompositeComponent');
var ReactEmptyComponent = require('./ReactEmptyComponent');
var ReactHostComponent = require('./ReactHostComponent');
var getNextDebugID = require('react/lib/getNextDebugID');
var invariant = require('fbjs/lib/invariant');
var warning = require('fbjs/lib/warning');
// To avoid a cyclic dependency, we create the final class in this module
var ReactCompositeComponentWrapper = function (element) {
this.construct(element);
};
function getDeclarationErrorAddendum(owner) {
if (owner) {
var name = owner.getName();
if (name) {
return ' Check the render method of `' + name + '`.';
}
}
return '';
}
/**
* Check if the type reference is a known internal type. I.e. not a user
* provided composite type.
*
* @param {function} type
* @return {boolean} Returns true if this is a valid internal type.
*/
function isInternalComponentType(type) {
return typeof type === 'function' && typeof type.prototype !== 'undefined' && typeof type.prototype.mountComponent === 'function' && typeof type.prototype.receiveComponent === 'function';
}
/**
* Given a ReactNode, create an instance that will actually be mounted.
*
* @param {ReactNode} node
* @param {boolean} shouldHaveDebugID
* @return {object} A new instance of the element's constructor.
* @protected
*/
function instantiateReactComponent(node, shouldHaveDebugID) {
var instance;
if (node === null || node === false) {
instance = ReactEmptyComponent.create(instantiateReactComponent);
} else if (typeof node === 'object') {
var element = node;
var type = element.type;
if (typeof type !== 'function' && typeof type !== 'string') {
var info = '';
if (process.env.NODE_ENV !== 'production') {
if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {
info += ' You likely forgot to export your component from the file ' + 'it\'s defined in.';
}
}
info += getDeclarationErrorAddendum(element._owner);
!false ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s', type == null ? type : typeof type, info) : _prodInvariant('130', type == null ? type : typeof type, info) : void 0;
}
// Special case string values
if (typeof element.type === 'string') {
instance = ReactHostComponent.createInternalComponent(element);
} else if (isInternalComponentType(element.type)) {
// This is temporarily available for custom components that are not string
// representations. I.e. ART. Once those are updated to use the string
// representation, we can drop this code path.
instance = new element.type(element);
// We renamed this. Allow the old name for compat. :(
if (!instance.getHostNode) {
instance.getHostNode = instance.getNativeNode;
}
} else {
instance = new ReactCompositeComponentWrapper(element);
}
} else if (typeof node === 'string' || typeof node === 'number') {
instance = ReactHostComponent.createInstanceForText(node);
} else {
!false ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Encountered invalid React node of type %s', typeof node) : _prodInvariant('131', typeof node) : void 0;
}
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(typeof instance.mountComponent === 'function' && typeof instance.receiveComponent === 'function' && typeof instance.getHostNode === 'function' && typeof instance.unmountComponent === 'function', 'Only React Components can be mounted.') : void 0;
}
// These two fields are used by the DOM and ART diffing algorithms
// respectively. Instead of using expandos on components, we should be
// storing the state needed by the diffing algorithms elsewhere.
instance._mountIndex = 0;
instance._mountImage = null;
if (process.env.NODE_ENV !== 'production') {
instance._debugID = shouldHaveDebugID ? getNextDebugID() : 0;
}
// Internal instances should fully constructed at this point, so they should
// not get any new fields added to them at this point.
if (process.env.NODE_ENV !== 'production') {
if (Object.preventExtensions) {
Object.preventExtensions(instance);
}
}
return instance;
}
_assign(ReactCompositeComponentWrapper.prototype, ReactCompositeComponent, {
_instantiateReactComponent: instantiateReactComponent
});
module.exports = instantiateReactComponent;
}).call(this,require('_process'))
},{"./ReactCompositeComponent":63,"./ReactEmptyComponent":86,"./ReactHostComponent":91,"./reactProdInvariant":153,"_process":29,"fbjs/lib/invariant":19,"fbjs/lib/warning":26,"object-assign":28,"react/lib/getNextDebugID":183}],150:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var ExecutionEnvironment = require('fbjs/lib/ExecutionEnvironment');
var useHasFeature;
if (ExecutionEnvironment.canUseDOM) {
useHasFeature = document.implementation && document.implementation.hasFeature &&
// always returns true in newer browsers as per the standard.
// @see http://dom.spec.whatwg.org/#dom-domimplementation-hasfeature
document.implementation.hasFeature('', '') !== true;
}
/**
* Checks if an event is supported in the current execution environment.
*
* NOTE: This will not work correctly for non-generic events such as `change`,
* `reset`, `load`, `error`, and `select`.
*
* Borrows from Modernizr.
*
* @param {string} eventNameSuffix Event name, e.g. "click".
* @param {?boolean} capture Check if the capture phase is supported.
* @return {boolean} True if the event is supported.
* @internal
* @license Modernizr 3.0.0pre (Custom Build) | MIT
*/
function isEventSupported(eventNameSuffix, capture) {
if (!ExecutionEnvironment.canUseDOM || capture && !('addEventListener' in document)) {
return false;
}
var eventName = 'on' + eventNameSuffix;
var isSupported = eventName in document;
if (!isSupported) {
var element = document.createElement('div');
element.setAttribute(eventName, 'return;');
isSupported = typeof element[eventName] === 'function';
}
if (!isSupported && useHasFeature && eventNameSuffix === 'wheel') {
// This is the only way to test support for the `wheel` event in IE9+.
isSupported = document.implementation.hasFeature('Events.wheel', '3.0');
}
return isSupported;
}
module.exports = isEventSupported;
},{"fbjs/lib/ExecutionEnvironment":5}],151:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
'use strict';
/**
* @see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary
*/
var supportedInputTypes = {
'color': true,
'date': true,
'datetime': true,
'datetime-local': true,
'email': true,
'month': true,
'number': true,
'password': true,
'range': true,
'search': true,
'tel': true,
'text': true,
'time': true,
'url': true,
'week': true
};
function isTextInputElement(elem) {
var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();
if (nodeName === 'input') {
return !!supportedInputTypes[elem.type];
}
if (nodeName === 'textarea') {
return true;
}
return false;
}
module.exports = isTextInputElement;
},{}],152:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var escapeTextContentForBrowser = require('./escapeTextContentForBrowser');
/**
* Escapes attribute value to prevent scripting attacks.
*
* @param {*} value Value to escape.
* @return {string} An escaped string.
*/
function quoteAttributeValueForBrowser(value) {
return '"' + escapeTextContentForBrowser(value) + '"';
}
module.exports = quoteAttributeValueForBrowser;
},{"./escapeTextContentForBrowser":136}],153:[function(require,module,exports){
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
'use strict';
/**
* WARNING: DO NOT manually require this module.
* This is a replacement for `invariant(...)` used by the error code system
* and will _only_ be required by the corresponding babel pass.
* It always throws.
*/
function reactProdInvariant(code) {
var argCount = arguments.length - 1;
var message = 'Minified React error #' + code + '; visit ' + 'http://facebook.github.io/react/docs/error-decoder.html?invariant=' + code;
for (var argIdx = 0; argIdx < argCount; argIdx++) {
message += '&args[]=' + encodeURIComponent(arguments[argIdx + 1]);
}
message += ' for the full message or use the non-minified dev environment' + ' for full errors and additional helpful warnings.';
var error = new Error(message);
error.name = 'Invariant Violation';
error.framesToPop = 1; // we don't care about reactProdInvariant's own frame
throw error;
}
module.exports = reactProdInvariant;
},{}],154:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var ReactMount = require('./ReactMount');
module.exports = ReactMount.renderSubtreeIntoContainer;
},{"./ReactMount":99}],155:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var ExecutionEnvironment = require('fbjs/lib/ExecutionEnvironment');
var DOMNamespaces = require('./DOMNamespaces');
var WHITESPACE_TEST = /^[ \r\n\t\f]/;
var NONVISIBLE_TEST = /<(!--|link|noscript|meta|script|style)[ \r\n\t\f\/>]/;
var createMicrosoftUnsafeLocalFunction = require('./createMicrosoftUnsafeLocalFunction');
// SVG temp container for IE lacking innerHTML
var reusableSVGContainer;
/**
* Set the innerHTML property of a node, ensuring that whitespace is preserved
* even in IE8.
*
* @param {DOMElement} node
* @param {string} html
* @internal
*/
var setInnerHTML = createMicrosoftUnsafeLocalFunction(function (node, html) {
// IE does not have innerHTML for SVG nodes, so instead we inject the
// new markup in a temp node and then move the child nodes across into
// the target node
if (node.namespaceURI === DOMNamespaces.svg && !('innerHTML' in node)) {
reusableSVGContainer = reusableSVGContainer || document.createElement('div');
reusableSVGContainer.innerHTML = '<svg>' + html + '</svg>';
var svgNode = reusableSVGContainer.firstChild;
while (svgNode.firstChild) {
node.appendChild(svgNode.firstChild);
}
} else {
node.innerHTML = html;
}
});
if (ExecutionEnvironment.canUseDOM) {
// IE8: When updating a just created node with innerHTML only leading
// whitespace is removed. When updating an existing node with innerHTML
// whitespace in root TextNodes is also collapsed.
// @see quirksmode.org/bugreports/archives/2004/11/innerhtml_and_t.html
// Feature detection; only IE8 is known to behave improperly like this.
var testElement = document.createElement('div');
testElement.innerHTML = ' ';
if (testElement.innerHTML === '') {
setInnerHTML = function (node, html) {
// Magic theory: IE8 supposedly differentiates between added and updated
// nodes when processing innerHTML, innerHTML on updated nodes suffers
// from worse whitespace behavior. Re-adding a node like this triggers
// the initial and more favorable whitespace behavior.
// TODO: What to do on a detached node?
if (node.parentNode) {
node.parentNode.replaceChild(node, node);
}
// We also implement a workaround for non-visible tags disappearing into
// thin air on IE8, this only happens if there is no visible text
// in-front of the non-visible tags. Piggyback on the whitespace fix
// and simply check if any non-visible tags appear in the source.
if (WHITESPACE_TEST.test(html) || html[0] === '<' && NONVISIBLE_TEST.test(html)) {
// Recover leading whitespace by temporarily prepending any character.
// \uFEFF has the potential advantage of being zero-width/invisible.
// UglifyJS drops U+FEFF chars when parsing, so use String.fromCharCode
// in hopes that this is preserved even if "\uFEFF" is transformed to
// the actual Unicode character (by Babel, for example).
// https://github.com/mishoo/UglifyJS2/blob/v2.4.20/lib/parse.js#L216
node.innerHTML = String.fromCharCode(0xFEFF) + html;
// deleteData leaves an empty `TextNode` which offsets the index of all
// children. Definitely want to avoid this.
var textNode = node.firstChild;
if (textNode.data.length === 1) {
node.removeChild(textNode);
} else {
textNode.deleteData(0, 1);
}
} else {
node.innerHTML = html;
}
};
}
testElement = null;
}
module.exports = setInnerHTML;
},{"./DOMNamespaces":44,"./createMicrosoftUnsafeLocalFunction":134,"fbjs/lib/ExecutionEnvironment":5}],156:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var ExecutionEnvironment = require('fbjs/lib/ExecutionEnvironment');
var escapeTextContentForBrowser = require('./escapeTextContentForBrowser');
var setInnerHTML = require('./setInnerHTML');
/**
* Set the textContent property of a node, ensuring that whitespace is preserved
* even in IE8. innerText is a poor substitute for textContent and, among many
* issues, inserts <br> instead of the literal newline chars. innerHTML behaves
* as it should.
*
* @param {DOMElement} node
* @param {string} text
* @internal
*/
var setTextContent = function (node, text) {
if (text) {
var firstChild = node.firstChild;
if (firstChild && firstChild === node.lastChild && firstChild.nodeType === 3) {
firstChild.nodeValue = text;
return;
}
}
node.textContent = text;
};
if (ExecutionEnvironment.canUseDOM) {
if (!('textContent' in document.documentElement)) {
setTextContent = function (node, text) {
if (node.nodeType === 3) {
node.nodeValue = text;
return;
}
setInnerHTML(node, escapeTextContentForBrowser(text));
};
}
}
module.exports = setTextContent;
},{"./escapeTextContentForBrowser":136,"./setInnerHTML":155,"fbjs/lib/ExecutionEnvironment":5}],157:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
/**
* Given a `prevElement` and `nextElement`, determines if the existing
* instance should be updated as opposed to being destroyed or replaced by a new
* instance. Both arguments are elements. This ensures that this logic can
* operate on stateless trees without any backing instance.
*
* @param {?object} prevElement
* @param {?object} nextElement
* @return {boolean} True if the existing instance should be updated.
* @protected
*/
function shouldUpdateReactComponent(prevElement, nextElement) {
var prevEmpty = prevElement === null || prevElement === false;
var nextEmpty = nextElement === null || nextElement === false;
if (prevEmpty || nextEmpty) {
return prevEmpty === nextEmpty;
}
var prevType = typeof prevElement;
var nextType = typeof nextElement;
if (prevType === 'string' || prevType === 'number') {
return nextType === 'string' || nextType === 'number';
} else {
return nextType === 'object' && prevElement.type === nextElement.type && prevElement.key === nextElement.key;
}
}
module.exports = shouldUpdateReactComponent;
},{}],158:[function(require,module,exports){
(function (process){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var _prodInvariant = require('./reactProdInvariant');
var ReactCurrentOwner = require('react/lib/ReactCurrentOwner');
var REACT_ELEMENT_TYPE = require('./ReactElementSymbol');
var getIteratorFn = require('./getIteratorFn');
var invariant = require('fbjs/lib/invariant');
var KeyEscapeUtils = require('./KeyEscapeUtils');
var warning = require('fbjs/lib/warning');
var SEPARATOR = '.';
var SUBSEPARATOR = ':';
/**
* This is inlined from ReactElement since this file is shared between
* isomorphic and renderers. We could extract this to a
*
*/
/**
* TODO: Test that a single child and an array with one item have the same key
* pattern.
*/
var didWarnAboutMaps = false;
/**
* Generate a key string that identifies a component within a set.
*
* @param {*} component A component that could contain a manual key.
* @param {number} index Index that is used if a manual key is not provided.
* @return {string}
*/
function getComponentKey(component, index) {
// Do some typechecking here since we call this blindly. We want to ensure
// that we don't block potential future ES APIs.
if (component && typeof component === 'object' && component.key != null) {
// Explicit key
return KeyEscapeUtils.escape(component.key);
}
// Implicit key determined by the index in the set
return index.toString(36);
}
/**
* @param {?*} children Children tree container.
* @param {!string} nameSoFar Name of the key path so far.
* @param {!function} callback Callback to invoke with each child found.
* @param {?*} traverseContext Used to pass information throughout the traversal
* process.
* @return {!number} The number of children in this subtree.
*/
function traverseAllChildrenImpl(children, nameSoFar, callback, traverseContext) {
var type = typeof children;
if (type === 'undefined' || type === 'boolean') {
// All of the above are perceived as null.
children = null;
}
if (children === null || type === 'string' || type === 'number' ||
// The following is inlined from ReactElement. This means we can optimize
// some checks. React Fiber also inlines this logic for similar purposes.
type === 'object' && children.$$typeof === REACT_ELEMENT_TYPE) {
callback(traverseContext, children,
// If it's the only child, treat the name as if it was wrapped in an array
// so that it's consistent if the number of children grows.
nameSoFar === '' ? SEPARATOR + getComponentKey(children, 0) : nameSoFar);
return 1;
}
var child;
var nextName;
var subtreeCount = 0; // Count of children found in the current subtree.
var nextNamePrefix = nameSoFar === '' ? SEPARATOR : nameSoFar + SUBSEPARATOR;
if (Array.isArray(children)) {
for (var i = 0; i < children.length; i++) {
child = children[i];
nextName = nextNamePrefix + getComponentKey(child, i);
subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext);
}
} else {
var iteratorFn = getIteratorFn(children);
if (iteratorFn) {
var iterator = iteratorFn.call(children);
var step;
if (iteratorFn !== children.entries) {
var ii = 0;
while (!(step = iterator.next()).done) {
child = step.value;
nextName = nextNamePrefix + getComponentKey(child, ii++);
subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext);
}
} else {
if (process.env.NODE_ENV !== 'production') {
var mapsAsChildrenAddendum = '';
if (ReactCurrentOwner.current) {
var mapsAsChildrenOwnerName = ReactCurrentOwner.current.getName();
if (mapsAsChildrenOwnerName) {
mapsAsChildrenAddendum = ' Check the render method of `' + mapsAsChildrenOwnerName + '`.';
}
}
process.env.NODE_ENV !== 'production' ? warning(didWarnAboutMaps, 'Using Maps as children is not yet fully supported. It is an ' + 'experimental feature that might be removed. Convert it to a ' + 'sequence / iterable of keyed ReactElements instead.%s', mapsAsChildrenAddendum) : void 0;
didWarnAboutMaps = true;
}
// Iterator will provide entry [k,v] tuples rather than values.
while (!(step = iterator.next()).done) {
var entry = step.value;
if (entry) {
child = entry[1];
nextName = nextNamePrefix + KeyEscapeUtils.escape(entry[0]) + SUBSEPARATOR + getComponentKey(child, 0);
subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext);
}
}
}
} else if (type === 'object') {
var addendum = '';
if (process.env.NODE_ENV !== 'production') {
addendum = ' If you meant to render a collection of children, use an array ' + 'instead or wrap the object using createFragment(object) from the ' + 'React add-ons.';
if (children._isReactElement) {
addendum = ' It looks like you\'re using an element created by a different ' + 'version of React. Make sure to use only one copy of React.';
}
if (ReactCurrentOwner.current) {
var name = ReactCurrentOwner.current.getName();
if (name) {
addendum += ' Check the render method of `' + name + '`.';
}
}
}
var childrenString = String(children);
!false ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Objects are not valid as a React child (found: %s).%s', childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString, addendum) : _prodInvariant('31', childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString, addendum) : void 0;
}
}
return subtreeCount;
}
/**
* Traverses children that are typically specified as `props.children`, but
* might also be specified through attributes:
*
* - `traverseAllChildren(this.props.children, ...)`
* - `traverseAllChildren(this.props.leftPanelChildren, ...)`
*
* The `traverseContext` is an optional argument that is passed through the
* entire traversal. It can be used to store accumulations or anything else that
* the callback might find relevant.
*
* @param {?*} children Children tree object.
* @param {!function} callback To invoke upon traversing each child.
* @param {?*} traverseContext Context for traversal.
* @return {!number} The number of children in this subtree.
*/
function traverseAllChildren(children, callback, traverseContext) {
if (children == null) {
return 0;
}
return traverseAllChildrenImpl(children, '', callback, traverseContext);
}
module.exports = traverseAllChildren;
}).call(this,require('_process'))
},{"./KeyEscapeUtils":56,"./ReactElementSymbol":85,"./getIteratorFn":145,"./reactProdInvariant":153,"_process":29,"fbjs/lib/invariant":19,"fbjs/lib/warning":26,"react/lib/ReactCurrentOwner":169}],159:[function(require,module,exports){
(function (process){
/**
* Copyright 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var _assign = require('object-assign');
var emptyFunction = require('fbjs/lib/emptyFunction');
var warning = require('fbjs/lib/warning');
var validateDOMNesting = emptyFunction;
if (process.env.NODE_ENV !== 'production') {
// This validation code was written based on the HTML5 parsing spec:
// https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope
//
// Note: this does not catch all invalid nesting, nor does it try to (as it's
// not clear what practical benefit doing so provides); instead, we warn only
// for cases where the parser will give a parse tree differing from what React
// intended. For example, <b><div></div></b> is invalid but we don't warn
// because it still parses correctly; we do warn for other cases like nested
// <p> tags where the beginning of the second element implicitly closes the
// first, causing a confusing mess.
// https://html.spec.whatwg.org/multipage/syntax.html#special
var specialTags = ['address', 'applet', 'area', 'article', 'aside', 'base', 'basefont', 'bgsound', 'blockquote', 'body', 'br', 'button', 'caption', 'center', 'col', 'colgroup', 'dd', 'details', 'dir', 'div', 'dl', 'dt', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'frame', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'iframe', 'img', 'input', 'isindex', 'li', 'link', 'listing', 'main', 'marquee', 'menu', 'menuitem', 'meta', 'nav', 'noembed', 'noframes', 'noscript', 'object', 'ol', 'p', 'param', 'plaintext', 'pre', 'script', 'section', 'select', 'source', 'style', 'summary', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'title', 'tr', 'track', 'ul', 'wbr', 'xmp'];
// https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope
var inScopeTags = ['applet', 'caption', 'html', 'table', 'td', 'th', 'marquee', 'object', 'template',
// https://html.spec.whatwg.org/multipage/syntax.html#html-integration-point
// TODO: Distinguish by namespace here -- for <title>, including it here
// errs on the side of fewer warnings
'foreignObject', 'desc', 'title'];
// https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-button-scope
var buttonScopeTags = inScopeTags.concat(['button']);
// https://html.spec.whatwg.org/multipage/syntax.html#generate-implied-end-tags
var impliedEndTags = ['dd', 'dt', 'li', 'option', 'optgroup', 'p', 'rp', 'rt'];
var emptyAncestorInfo = {
current: null,
formTag: null,
aTagInScope: null,
buttonTagInScope: null,
nobrTagInScope: null,
pTagInButtonScope: null,
listItemTagAutoclosing: null,
dlItemTagAutoclosing: null
};
var updatedAncestorInfo = function (oldInfo, tag, instance) {
var ancestorInfo = _assign({}, oldInfo || emptyAncestorInfo);
var info = { tag: tag, instance: instance };
if (inScopeTags.indexOf(tag) !== -1) {
ancestorInfo.aTagInScope = null;
ancestorInfo.buttonTagInScope = null;
ancestorInfo.nobrTagInScope = null;
}
if (buttonScopeTags.indexOf(tag) !== -1) {
ancestorInfo.pTagInButtonScope = null;
}
// See rules for 'li', 'dd', 'dt' start tags in
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody
if (specialTags.indexOf(tag) !== -1 && tag !== 'address' && tag !== 'div' && tag !== 'p') {
ancestorInfo.listItemTagAutoclosing = null;
ancestorInfo.dlItemTagAutoclosing = null;
}
ancestorInfo.current = info;
if (tag === 'form') {
ancestorInfo.formTag = info;
}
if (tag === 'a') {
ancestorInfo.aTagInScope = info;
}
if (tag === 'button') {
ancestorInfo.buttonTagInScope = info;
}
if (tag === 'nobr') {
ancestorInfo.nobrTagInScope = info;
}
if (tag === 'p') {
ancestorInfo.pTagInButtonScope = info;
}
if (tag === 'li') {
ancestorInfo.listItemTagAutoclosing = info;
}
if (tag === 'dd' || tag === 'dt') {
ancestorInfo.dlItemTagAutoclosing = info;
}
return ancestorInfo;
};
/**
* Returns whether
*/
var isTagValidWithParent = function (tag, parentTag) {
// First, let's check if we're in an unusual parsing mode...
switch (parentTag) {
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inselect
case 'select':
return tag === 'option' || tag === 'optgroup' || tag === '#text';
case 'optgroup':
return tag === 'option' || tag === '#text';
// Strictly speaking, seeing an <option> doesn't mean we're in a <select>
// but
case 'option':
return tag === '#text';
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intd
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incaption
// No special behavior since these rules fall back to "in body" mode for
// all except special table nodes which cause bad parsing behavior anyway.
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intr
case 'tr':
return tag === 'th' || tag === 'td' || tag === 'style' || tag === 'script' || tag === 'template';
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intbody
case 'tbody':
case 'thead':
case 'tfoot':
return tag === 'tr' || tag === 'style' || tag === 'script' || tag === 'template';
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incolgroup
case 'colgroup':
return tag === 'col' || tag === 'template';
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intable
case 'table':
return tag === 'caption' || tag === 'colgroup' || tag === 'tbody' || tag === 'tfoot' || tag === 'thead' || tag === 'style' || tag === 'script' || tag === 'template';
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inhead
case 'head':
return tag === 'base' || tag === 'basefont' || tag === 'bgsound' || tag === 'link' || tag === 'meta' || tag === 'title' || tag === 'noscript' || tag === 'noframes' || tag === 'style' || tag === 'script' || tag === 'template';
// https://html.spec.whatwg.org/multipage/semantics.html#the-html-element
case 'html':
return tag === 'head' || tag === 'body';
case '#document':
return tag === 'html';
}
// Probably in the "in body" parsing mode, so we outlaw only tag combos
// where the parsing rules cause implicit opens or closes to be added.
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody
switch (tag) {
case 'h1':
case 'h2':
case 'h3':
case 'h4':
case 'h5':
case 'h6':
return parentTag !== 'h1' && parentTag !== 'h2' && parentTag !== 'h3' && parentTag !== 'h4' && parentTag !== 'h5' && parentTag !== 'h6';
case 'rp':
case 'rt':
return impliedEndTags.indexOf(parentTag) === -1;
case 'body':
case 'caption':
case 'col':
case 'colgroup':
case 'frame':
case 'head':
case 'html':
case 'tbody':
case 'td':
case 'tfoot':
case 'th':
case 'thead':
case 'tr':
// These tags are only valid with a few parents that have special child
// parsing rules -- if we're down here, then none of those matched and
// so we allow it only if we don't know what the parent is, as all other
// cases are invalid.
return parentTag == null;
}
return true;
};
/**
* Returns whether
*/
var findInvalidAncestorForTag = function (tag, ancestorInfo) {
switch (tag) {
case 'address':
case 'article':
case 'aside':
case 'blockquote':
case 'center':
case 'details':
case 'dialog':
case 'dir':
case 'div':
case 'dl':
case 'fieldset':
case 'figcaption':
case 'figure':
case 'footer':
case 'header':
case 'hgroup':
case 'main':
case 'menu':
case 'nav':
case 'ol':
case 'p':
case 'section':
case 'summary':
case 'ul':
case 'pre':
case 'listing':
case 'table':
case 'hr':
case 'xmp':
case 'h1':
case 'h2':
case 'h3':
case 'h4':
case 'h5':
case 'h6':
return ancestorInfo.pTagInButtonScope;
case 'form':
return ancestorInfo.formTag || ancestorInfo.pTagInButtonScope;
case 'li':
return ancestorInfo.listItemTagAutoclosing;
case 'dd':
case 'dt':
return ancestorInfo.dlItemTagAutoclosing;
case 'button':
return ancestorInfo.buttonTagInScope;
case 'a':
// Spec says something about storing a list of markers, but it sounds
// equivalent to this check.
return ancestorInfo.aTagInScope;
case 'nobr':
return ancestorInfo.nobrTagInScope;
}
return null;
};
/**
* Given a ReactCompositeComponent instance, return a list of its recursive
* owners, starting at the root and ending with the instance itself.
*/
var findOwnerStack = function (instance) {
if (!instance) {
return [];
}
var stack = [];
do {
stack.push(instance);
} while (instance = instance._currentElement._owner);
stack.reverse();
return stack;
};
var didWarn = {};
validateDOMNesting = function (childTag, childText, childInstance, ancestorInfo) {
ancestorInfo = ancestorInfo || emptyAncestorInfo;
var parentInfo = ancestorInfo.current;
var parentTag = parentInfo && parentInfo.tag;
if (childText != null) {
process.env.NODE_ENV !== 'production' ? warning(childTag == null, 'validateDOMNesting: when childText is passed, childTag should be null') : void 0;
childTag = '#text';
}
var invalidParent = isTagValidWithParent(childTag, parentTag) ? null : parentInfo;
var invalidAncestor = invalidParent ? null : findInvalidAncestorForTag(childTag, ancestorInfo);
var problematic = invalidParent || invalidAncestor;
if (problematic) {
var ancestorTag = problematic.tag;
var ancestorInstance = problematic.instance;
var childOwner = childInstance && childInstance._currentElement._owner;
var ancestorOwner = ancestorInstance && ancestorInstance._currentElement._owner;
var childOwners = findOwnerStack(childOwner);
var ancestorOwners = findOwnerStack(ancestorOwner);
var minStackLen = Math.min(childOwners.length, ancestorOwners.length);
var i;
var deepestCommon = -1;
for (i = 0; i < minStackLen; i++) {
if (childOwners[i] === ancestorOwners[i]) {
deepestCommon = i;
} else {
break;
}
}
var UNKNOWN = '(unknown)';
var childOwnerNames = childOwners.slice(deepestCommon + 1).map(function (inst) {
return inst.getName() || UNKNOWN;
});
var ancestorOwnerNames = ancestorOwners.slice(deepestCommon + 1).map(function (inst) {
return inst.getName() || UNKNOWN;
});
var ownerInfo = [].concat(
// If the parent and child instances have a common owner ancestor, start
// with that -- otherwise we just start with the parent's owners.
deepestCommon !== -1 ? childOwners[deepestCommon].getName() || UNKNOWN : [], ancestorOwnerNames, ancestorTag,
// If we're warning about an invalid (non-parent) ancestry, add '...'
invalidAncestor ? ['...'] : [], childOwnerNames, childTag).join(' > ');
var warnKey = !!invalidParent + '|' + childTag + '|' + ancestorTag + '|' + ownerInfo;
if (didWarn[warnKey]) {
return;
}
didWarn[warnKey] = true;
var tagDisplayName = childTag;
var whitespaceInfo = '';
if (childTag === '#text') {
if (/\S/.test(childText)) {
tagDisplayName = 'Text nodes';
} else {
tagDisplayName = 'Whitespace text nodes';
whitespaceInfo = ' Make sure you don\'t have any extra whitespace between tags on ' + 'each line of your source code.';
}
} else {
tagDisplayName = '<' + childTag + '>';
}
if (invalidParent) {
var info = '';
if (ancestorTag === 'table' && childTag === 'tr') {
info += ' Add a <tbody> to your code to match the DOM tree generated by ' + 'the browser.';
}
process.env.NODE_ENV !== 'production' ? warning(false, 'validateDOMNesting(...): %s cannot appear as a child of <%s>.%s ' + 'See %s.%s', tagDisplayName, ancestorTag, whitespaceInfo, ownerInfo, info) : void 0;
} else {
process.env.NODE_ENV !== 'production' ? warning(false, 'validateDOMNesting(...): %s cannot appear as a descendant of ' + '<%s>. See %s.', tagDisplayName, ancestorTag, ownerInfo) : void 0;
}
}
};
validateDOMNesting.updatedAncestorInfo = updatedAncestorInfo;
// For testing
validateDOMNesting.isTagValidInContext = function (tag, ancestorInfo) {
ancestorInfo = ancestorInfo || emptyAncestorInfo;
var parentInfo = ancestorInfo.current;
var parentTag = parentInfo && parentInfo.tag;
return isTagValidWithParent(tag, parentTag) && !findInvalidAncestorForTag(tag, ancestorInfo);
};
}
module.exports = validateDOMNesting;
}).call(this,require('_process'))
},{"_process":29,"fbjs/lib/emptyFunction":11,"fbjs/lib/warning":26,"object-assign":28}],160:[function(require,module,exports){
(function (process){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict';
var invariant = require('fbjs/lib/invariant');
var warning = require('fbjs/lib/warning');
var ReactPropTypesSecret = require('./lib/ReactPropTypesSecret');
var loggedTypeFailures = {};
/**
* Assert that the values match with the type specs.
* Error messages are memorized and will only be shown once.
*
* @param {object} typeSpecs Map of name to a ReactPropType
* @param {object} values Runtime values that need to be type-checked
* @param {string} location e.g. "prop", "context", "child context"
* @param {string} componentName Name of the component for error messages.
* @param {?Function} getStack Returns the component stack.
* @private
*/
function checkPropTypes(typeSpecs, values, location, componentName, getStack) {
if (process.env.NODE_ENV !== 'production') {
for (var typeSpecName in typeSpecs) {
if (typeSpecs.hasOwnProperty(typeSpecName)) {
var error;
// Prop type validation may throw. In case they do, we don't want to
// fail the render phase where it didn't fail before. So we log it.
// After these have been cleaned up, we'll let them throw.
try {
// This is intentionally an invariant that gets caught. It's the same
// behavior as without this statement except with a better message.
invariant(typeof typeSpecs[typeSpecName] === 'function', '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'React.PropTypes.', componentName || 'React class', location, typeSpecName);
error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret);
} catch (ex) {
error = ex;
}
process.env.NODE_ENV !== 'production' ? warning(!error || error instanceof Error, '%s: type specification of %s `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error) : void 0;
if (error instanceof Error && !(error.message in loggedTypeFailures)) {
// Only monitor this failure once because there tends to be a lot of the
// same error.
loggedTypeFailures[error.message] = true;
var stack = getStack ? getStack() : '';
process.env.NODE_ENV !== 'production' ? warning(false, 'Failed %s type: %s%s', location, error.message, stack != null ? stack : '') : void 0;
}
}
}
}
}
module.exports = checkPropTypes;
}).call(this,require('_process'))
},{"./lib/ReactPropTypesSecret":162,"_process":29,"fbjs/lib/invariant":19,"fbjs/lib/warning":26}],161:[function(require,module,exports){
(function (process){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict';
var emptyFunction = require('fbjs/lib/emptyFunction');
var invariant = require('fbjs/lib/invariant');
var warning = require('fbjs/lib/warning');
var ReactPropTypesSecret = require('./lib/ReactPropTypesSecret');
var checkPropTypes = require('./checkPropTypes');
module.exports = function (isValidElement) {
/* global Symbol */
var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec.
/**
* Returns the iterator method function contained on the iterable object.
*
* Be sure to invoke the function with the iterable as context:
*
* var iteratorFn = getIteratorFn(myIterable);
* if (iteratorFn) {
* var iterator = iteratorFn.call(myIterable);
* ...
* }
*
* @param {?object} maybeIterable
* @return {?function}
*/
function getIteratorFn(maybeIterable) {
var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]);
if (typeof iteratorFn === 'function') {
return iteratorFn;
}
}
/**
* Collection of methods that allow declaration and validation of props that are
* supplied to React components. Example usage:
*
* var Props = require('ReactPropTypes');
* var MyArticle = React.createClass({
* propTypes: {
* // An optional string prop named "description".
* description: Props.string,
*
* // A required enum prop named "category".
* category: Props.oneOf(['News','Photos']).isRequired,
*
* // A prop named "dialog" that requires an instance of Dialog.
* dialog: Props.instanceOf(Dialog).isRequired
* },
* render: function() { ... }
* });
*
* A more formal specification of how these methods are used:
*
* type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...)
* decl := ReactPropTypes.{type}(.isRequired)?
*
* Each and every declaration produces a function with the same signature. This
* allows the creation of custom validation functions. For example:
*
* var MyLink = React.createClass({
* propTypes: {
* // An optional string or URI prop named "href".
* href: function(props, propName, componentName) {
* var propValue = props[propName];
* if (propValue != null && typeof propValue !== 'string' &&
* !(propValue instanceof URI)) {
* return new Error(
* 'Expected a string or an URI for ' + propName + ' in ' +
* componentName
* );
* }
* }
* },
* render: function() {...}
* });
*
* @internal
*/
var ANONYMOUS = '<<anonymous>>';
var ReactPropTypes;
if (process.env.NODE_ENV !== 'production') {
// Keep in sync with production version below
ReactPropTypes = {
array: createPrimitiveTypeChecker('array'),
bool: createPrimitiveTypeChecker('boolean'),
func: createPrimitiveTypeChecker('function'),
number: createPrimitiveTypeChecker('number'),
object: createPrimitiveTypeChecker('object'),
string: createPrimitiveTypeChecker('string'),
symbol: createPrimitiveTypeChecker('symbol'),
any: createAnyTypeChecker(),
arrayOf: createArrayOfTypeChecker,
element: createElementTypeChecker(),
instanceOf: createInstanceTypeChecker,
node: createNodeChecker(),
objectOf: createObjectOfTypeChecker,
oneOf: createEnumTypeChecker,
oneOfType: createUnionTypeChecker,
shape: createShapeTypeChecker
};
} else {
var productionTypeChecker = function () {
invariant(false, 'React.PropTypes type checking code is stripped in production.');
};
productionTypeChecker.isRequired = productionTypeChecker;
var getProductionTypeChecker = function () {
return productionTypeChecker;
};
// Keep in sync with development version above
ReactPropTypes = {
array: productionTypeChecker,
bool: productionTypeChecker,
func: productionTypeChecker,
number: productionTypeChecker,
object: productionTypeChecker,
string: productionTypeChecker,
symbol: productionTypeChecker,
any: productionTypeChecker,
arrayOf: getProductionTypeChecker,
element: productionTypeChecker,
instanceOf: getProductionTypeChecker,
node: productionTypeChecker,
objectOf: getProductionTypeChecker,
oneOf: getProductionTypeChecker,
oneOfType: getProductionTypeChecker,
shape: getProductionTypeChecker
};
}
/**
* inlined Object.is polyfill to avoid requiring consumers ship their own
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
*/
/*eslint-disable no-self-compare*/
function is(x, y) {
// SameValue algorithm
if (x === y) {
// Steps 1-5, 7-10
// Steps 6.b-6.e: +0 != -0
return x !== 0 || 1 / x === 1 / y;
} else {
// Step 6.a: NaN == NaN
return x !== x && y !== y;
}
}
/*eslint-enable no-self-compare*/
/**
* We use an Error-like object for backward compatibility as people may call
* PropTypes directly and inspect their output. However, we don't use real
* Errors anymore. We don't inspect their stack anyway, and creating them
* is prohibitively expensive if they are created too often, such as what
* happens in oneOfType() for any type before the one that matched.
*/
function PropTypeError(message) {
this.message = message;
this.stack = '';
}
// Make `instanceof Error` still work for returned errors.
PropTypeError.prototype = Error.prototype;
function createChainableTypeChecker(validate) {
if (process.env.NODE_ENV !== 'production') {
var manualPropTypeCallCache = {};
}
function checkType(isRequired, props, propName, componentName, location, propFullName, secret) {
componentName = componentName || ANONYMOUS;
propFullName = propFullName || propName;
if (process.env.NODE_ENV !== 'production') {
if (secret !== ReactPropTypesSecret && typeof console !== 'undefined') {
var cacheKey = componentName + ':' + propName;
if (!manualPropTypeCallCache[cacheKey]) {
process.env.NODE_ENV !== 'production' ? warning(false, 'You are manually calling a React.PropTypes validation ' + 'function for the `%s` prop on `%s`. This is deprecated ' + 'and will not work in production with the next major version. ' + 'You may be seeing this warning due to a third-party PropTypes ' + 'library. See https://fb.me/react-warning-dont-call-proptypes ' + 'for details.', propFullName, componentName) : void 0;
manualPropTypeCallCache[cacheKey] = true;
}
}
}
if (props[propName] == null) {
if (isRequired) {
if (props[propName] === null) {
return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required ' + ('in `' + componentName + '`, but its value is `null`.'));
}
return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required in ' + ('`' + componentName + '`, but its value is `undefined`.'));
}
return null;
} else {
return validate(props, propName, componentName, location, propFullName);
}
}
var chainedCheckType = checkType.bind(null, false);
chainedCheckType.isRequired = checkType.bind(null, true);
return chainedCheckType;
}
function createPrimitiveTypeChecker(expectedType) {
function validate(props, propName, componentName, location, propFullName, secret) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== expectedType) {
// `propValue` being instance of, say, date/regexp, pass the 'object'
// check, but we can offer a more precise error message here rather than
// 'of type `object`'.
var preciseType = getPreciseType(propValue);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createAnyTypeChecker() {
return createChainableTypeChecker(emptyFunction.thatReturnsNull);
}
function createArrayOfTypeChecker(typeChecker) {
function validate(props, propName, componentName, location, propFullName) {
if (typeof typeChecker !== 'function') {
return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside arrayOf.');
}
var propValue = props[propName];
if (!Array.isArray(propValue)) {
var propType = getPropType(propValue);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an array.'));
}
for (var i = 0; i < propValue.length; i++) {
var error = typeChecker(propValue, i, componentName, location, propFullName + '[' + i + ']', ReactPropTypesSecret);
if (error instanceof Error) {
return error;
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function createElementTypeChecker() {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
if (!isValidElement(propValue)) {
var propType = getPropType(propValue);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createInstanceTypeChecker(expectedClass) {
function validate(props, propName, componentName, location, propFullName) {
if (!(props[propName] instanceof expectedClass)) {
var expectedClassName = expectedClass.name || ANONYMOUS;
var actualClassName = getClassName(props[propName]);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + actualClassName + '` supplied to `' + componentName + '`, expected ') + ('instance of `' + expectedClassName + '`.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createEnumTypeChecker(expectedValues) {
if (!Array.isArray(expectedValues)) {
process.env.NODE_ENV !== 'production' ? warning(false, 'Invalid argument supplied to oneOf, expected an instance of array.') : void 0;
return emptyFunction.thatReturnsNull;
}
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
for (var i = 0; i < expectedValues.length; i++) {
if (is(propValue, expectedValues[i])) {
return null;
}
}
var valuesString = JSON.stringify(expectedValues);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of value `' + propValue + '` ' + ('supplied to `' + componentName + '`, expected one of ' + valuesString + '.'));
}
return createChainableTypeChecker(validate);
}
function createObjectOfTypeChecker(typeChecker) {
function validate(props, propName, componentName, location, propFullName) {
if (typeof typeChecker !== 'function') {
return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside objectOf.');
}
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== 'object') {
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an object.'));
}
for (var key in propValue) {
if (propValue.hasOwnProperty(key)) {
var error = typeChecker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret);
if (error instanceof Error) {
return error;
}
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function createUnionTypeChecker(arrayOfTypeCheckers) {
if (!Array.isArray(arrayOfTypeCheckers)) {
process.env.NODE_ENV !== 'production' ? warning(false, 'Invalid argument supplied to oneOfType, expected an instance of array.') : void 0;
return emptyFunction.thatReturnsNull;
}
function validate(props, propName, componentName, location, propFullName) {
for (var i = 0; i < arrayOfTypeCheckers.length; i++) {
var checker = arrayOfTypeCheckers[i];
if (checker(props, propName, componentName, location, propFullName, ReactPropTypesSecret) == null) {
return null;
}
}
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`.'));
}
return createChainableTypeChecker(validate);
}
function createNodeChecker() {
function validate(props, propName, componentName, location, propFullName) {
if (!isNode(props[propName])) {
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a ReactNode.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createShapeTypeChecker(shapeTypes) {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== 'object') {
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.'));
}
for (var key in shapeTypes) {
var checker = shapeTypes[key];
if (!checker) {
continue;
}
var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret);
if (error) {
return error;
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function isNode(propValue) {
switch (typeof propValue) {
case 'number':
case 'string':
case 'undefined':
return true;
case 'boolean':
return !propValue;
case 'object':
if (Array.isArray(propValue)) {
return propValue.every(isNode);
}
if (propValue === null || isValidElement(propValue)) {
return true;
}
var iteratorFn = getIteratorFn(propValue);
if (iteratorFn) {
var iterator = iteratorFn.call(propValue);
var step;
if (iteratorFn !== propValue.entries) {
while (!(step = iterator.next()).done) {
if (!isNode(step.value)) {
return false;
}
}
} else {
// Iterator will provide entry [k,v] tuples rather than values.
while (!(step = iterator.next()).done) {
var entry = step.value;
if (entry) {
if (!isNode(entry[1])) {
return false;
}
}
}
}
} else {
return false;
}
return true;
default:
return false;
}
}
function isSymbol(propType, propValue) {
// Native Symbol.
if (propType === 'symbol') {
return true;
}
// 19.4.3.5 Symbol.prototype[@@toStringTag] === 'Symbol'
if (propValue['@@toStringTag'] === 'Symbol') {
return true;
}
// Fallback for non-spec compliant Symbols which are polyfilled.
if (typeof Symbol === 'function' && propValue instanceof Symbol) {
return true;
}
return false;
}
// Equivalent of `typeof` but with special handling for array and regexp.
function getPropType(propValue) {
var propType = typeof propValue;
if (Array.isArray(propValue)) {
return 'array';
}
if (propValue instanceof RegExp) {
// Old webkits (at least until Android 4.0) return 'function' rather than
// 'object' for typeof a RegExp. We'll normalize this here so that /bla/
// passes PropTypes.object.
return 'object';
}
if (isSymbol(propType, propValue)) {
return 'symbol';
}
return propType;
}
// This handles more types than `getPropType`. Only used for error messages.
// See `createPrimitiveTypeChecker`.
function getPreciseType(propValue) {
var propType = getPropType(propValue);
if (propType === 'object') {
if (propValue instanceof Date) {
return 'date';
} else if (propValue instanceof RegExp) {
return 'regexp';
}
}
return propType;
}
// Returns class name of the object, if any.
function getClassName(propValue) {
if (!propValue.constructor || !propValue.constructor.name) {
return ANONYMOUS;
}
return propValue.constructor.name;
}
ReactPropTypes.checkPropTypes = checkPropTypes;
ReactPropTypes.PropTypes = ReactPropTypes;
return ReactPropTypes;
};
}).call(this,require('_process'))
},{"./checkPropTypes":160,"./lib/ReactPropTypesSecret":162,"_process":29,"fbjs/lib/emptyFunction":11,"fbjs/lib/invariant":19,"fbjs/lib/warning":26}],162:[function(require,module,exports){
arguments[4][33][0].apply(exports,arguments)
},{"dup":33}],163:[function(require,module,exports){
arguments[4][56][0].apply(exports,arguments)
},{"dup":56}],164:[function(require,module,exports){
arguments[4][58][0].apply(exports,arguments)
},{"./reactProdInvariant":186,"_process":29,"dup":58,"fbjs/lib/invariant":19}],165:[function(require,module,exports){
(function (process){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var _assign = require('object-assign');
var ReactBaseClasses = require('./ReactBaseClasses');
var ReactChildren = require('./ReactChildren');
var ReactDOMFactories = require('./ReactDOMFactories');
var ReactElement = require('./ReactElement');
var ReactPropTypes = require('./ReactPropTypes');
var ReactVersion = require('./ReactVersion');
var createReactClass = require('./createClass');
var onlyChild = require('./onlyChild');
var createElement = ReactElement.createElement;
var createFactory = ReactElement.createFactory;
var cloneElement = ReactElement.cloneElement;
if (process.env.NODE_ENV !== 'production') {
var lowPriorityWarning = require('./lowPriorityWarning');
var canDefineProperty = require('./canDefineProperty');
var ReactElementValidator = require('./ReactElementValidator');
var didWarnPropTypesDeprecated = false;
createElement = ReactElementValidator.createElement;
createFactory = ReactElementValidator.createFactory;
cloneElement = ReactElementValidator.cloneElement;
}
var __spread = _assign;
var createMixin = function (mixin) {
return mixin;
};
if (process.env.NODE_ENV !== 'production') {
var warnedForSpread = false;
var warnedForCreateMixin = false;
__spread = function () {
lowPriorityWarning(warnedForSpread, 'React.__spread is deprecated and should not be used. Use ' + 'Object.assign directly or another helper function with similar ' + 'semantics. You may be seeing this warning due to your compiler. ' + 'See https://fb.me/react-spread-deprecation for more details.');
warnedForSpread = true;
return _assign.apply(null, arguments);
};
createMixin = function (mixin) {
lowPriorityWarning(warnedForCreateMixin, 'React.createMixin is deprecated and should not be used. ' + 'In React v16.0, it will be removed. ' + 'You can use this mixin directly instead. ' + 'See https://fb.me/createmixin-was-never-implemented for more info.');
warnedForCreateMixin = true;
return mixin;
};
}
var React = {
// Modern
Children: {
map: ReactChildren.map,
forEach: ReactChildren.forEach,
count: ReactChildren.count,
toArray: ReactChildren.toArray,
only: onlyChild
},
Component: ReactBaseClasses.Component,
PureComponent: ReactBaseClasses.PureComponent,
createElement: createElement,
cloneElement: cloneElement,
isValidElement: ReactElement.isValidElement,
// Classic
PropTypes: ReactPropTypes,
createClass: createReactClass,
createFactory: createFactory,
createMixin: createMixin,
// This looks DOM specific but these are actually isomorphic helpers
// since they are just generating DOM strings.
DOM: ReactDOMFactories,
version: ReactVersion,
// Deprecated hook for JSX spread, don't use this for anything.
__spread: __spread
};
if (process.env.NODE_ENV !== 'production') {
var warnedForCreateClass = false;
if (canDefineProperty) {
Object.defineProperty(React, 'PropTypes', {
get: function () {
lowPriorityWarning(didWarnPropTypesDeprecated, 'Accessing PropTypes via the main React package is deprecated,' + ' and will be removed in React v16.0.' + ' Use the latest available v15.* prop-types package from npm instead.' + ' For info on usage, compatibility, migration and more, see ' + 'https://fb.me/prop-types-docs');
didWarnPropTypesDeprecated = true;
return ReactPropTypes;
}
});
Object.defineProperty(React, 'createClass', {
get: function () {
lowPriorityWarning(warnedForCreateClass, 'Accessing createClass via the main React package is deprecated,' + ' and will be removed in React v16.0.' + " Use a plain JavaScript class instead. If you're not yet " + 'ready to migrate, create-react-class v15.* is available ' + 'on npm as a temporary, drop-in replacement. ' + 'For more info see https://fb.me/react-create-class');
warnedForCreateClass = true;
return createReactClass;
}
});
}
// React.DOM factories are deprecated. Wrap these methods so that
// invocations of the React.DOM namespace and alert users to switch
// to the `react-dom-factories` package.
React.DOM = {};
var warnedForFactories = false;
Object.keys(ReactDOMFactories).forEach(function (factory) {
React.DOM[factory] = function () {
if (!warnedForFactories) {
lowPriorityWarning(false, 'Accessing factories like React.DOM.%s has been deprecated ' + 'and will be removed in v16.0+. Use the ' + 'react-dom-factories package instead. ' + ' Version 1.0 provides a drop-in replacement.' + ' For more info, see https://fb.me/react-dom-factories', factory);
warnedForFactories = true;
}
return ReactDOMFactories[factory].apply(ReactDOMFactories, arguments);
};
});
}
module.exports = React;
}).call(this,require('_process'))
},{"./ReactBaseClasses":166,"./ReactChildren":167,"./ReactDOMFactories":170,"./ReactElement":171,"./ReactElementValidator":173,"./ReactPropTypes":176,"./ReactVersion":178,"./canDefineProperty":179,"./createClass":181,"./lowPriorityWarning":184,"./onlyChild":185,"_process":29,"object-assign":28}],166:[function(require,module,exports){
(function (process){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var _prodInvariant = require('./reactProdInvariant'),
_assign = require('object-assign');
var ReactNoopUpdateQueue = require('./ReactNoopUpdateQueue');
var canDefineProperty = require('./canDefineProperty');
var emptyObject = require('fbjs/lib/emptyObject');
var invariant = require('fbjs/lib/invariant');
var lowPriorityWarning = require('./lowPriorityWarning');
/**
* Base class helpers for the updating state of a component.
*/
function ReactComponent(props, context, updater) {
this.props = props;
this.context = context;
this.refs = emptyObject;
// We initialize the default updater but the real one gets injected by the
// renderer.
this.updater = updater || ReactNoopUpdateQueue;
}
ReactComponent.prototype.isReactComponent = {};
/**
* Sets a subset of the state. Always use this to mutate
* state. You should treat `this.state` as immutable.
*
* There is no guarantee that `this.state` will be immediately updated, so
* accessing `this.state` after calling this method may return the old value.
*
* There is no guarantee that calls to `setState` will run synchronously,
* as they may eventually be batched together. You can provide an optional
* callback that will be executed when the call to setState is actually
* completed.
*
* When a function is provided to setState, it will be called at some point in
* the future (not synchronously). It will be called with the up to date
* component arguments (state, props, context). These values can be different
* from this.* because your function may be called after receiveProps but before
* shouldComponentUpdate, and this new state, props, and context will not yet be
* assigned to this.
*
* @param {object|function} partialState Next partial state or function to
* produce next partial state to be merged with current state.
* @param {?function} callback Called after state is updated.
* @final
* @protected
*/
ReactComponent.prototype.setState = function (partialState, callback) {
!(typeof partialState === 'object' || typeof partialState === 'function' || partialState == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'setState(...): takes an object of state variables to update or a function which returns an object of state variables.') : _prodInvariant('85') : void 0;
this.updater.enqueueSetState(this, partialState);
if (callback) {
this.updater.enqueueCallback(this, callback, 'setState');
}
};
/**
* Forces an update. This should only be invoked when it is known with
* certainty that we are **not** in a DOM transaction.
*
* You may want to call this when you know that some deeper aspect of the
* component's state has changed but `setState` was not called.
*
* This will not invoke `shouldComponentUpdate`, but it will invoke
* `componentWillUpdate` and `componentDidUpdate`.
*
* @param {?function} callback Called after update is complete.
* @final
* @protected
*/
ReactComponent.prototype.forceUpdate = function (callback) {
this.updater.enqueueForceUpdate(this);
if (callback) {
this.updater.enqueueCallback(this, callback, 'forceUpdate');
}
};
/**
* Deprecated APIs. These APIs used to exist on classic React classes but since
* we would like to deprecate them, we're not going to move them over to this
* modern base class. Instead, we define a getter that warns if it's accessed.
*/
if (process.env.NODE_ENV !== 'production') {
var deprecatedAPIs = {
isMounted: ['isMounted', 'Instead, make sure to clean up subscriptions and pending requests in ' + 'componentWillUnmount to prevent memory leaks.'],
replaceState: ['replaceState', 'Refactor your code to use setState instead (see ' + 'https://github.com/facebook/react/issues/3236).']
};
var defineDeprecationWarning = function (methodName, info) {
if (canDefineProperty) {
Object.defineProperty(ReactComponent.prototype, methodName, {
get: function () {
lowPriorityWarning(false, '%s(...) is deprecated in plain JavaScript React classes. %s', info[0], info[1]);
return undefined;
}
});
}
};
for (var fnName in deprecatedAPIs) {
if (deprecatedAPIs.hasOwnProperty(fnName)) {
defineDeprecationWarning(fnName, deprecatedAPIs[fnName]);
}
}
}
/**
* Base class helpers for the updating state of a component.
*/
function ReactPureComponent(props, context, updater) {
// Duplicated from ReactComponent.
this.props = props;
this.context = context;
this.refs = emptyObject;
// We initialize the default updater but the real one gets injected by the
// renderer.
this.updater = updater || ReactNoopUpdateQueue;
}
function ComponentDummy() {}
ComponentDummy.prototype = ReactComponent.prototype;
ReactPureComponent.prototype = new ComponentDummy();
ReactPureComponent.prototype.constructor = ReactPureComponent;
// Avoid an extra prototype jump for these methods.
_assign(ReactPureComponent.prototype, ReactComponent.prototype);
ReactPureComponent.prototype.isPureReactComponent = true;
module.exports = {
Component: ReactComponent,
PureComponent: ReactPureComponent
};
}).call(this,require('_process'))
},{"./ReactNoopUpdateQueue":174,"./canDefineProperty":179,"./lowPriorityWarning":184,"./reactProdInvariant":186,"_process":29,"fbjs/lib/emptyObject":12,"fbjs/lib/invariant":19,"object-assign":28}],167:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var PooledClass = require('./PooledClass');
var ReactElement = require('./ReactElement');
var emptyFunction = require('fbjs/lib/emptyFunction');
var traverseAllChildren = require('./traverseAllChildren');
var twoArgumentPooler = PooledClass.twoArgumentPooler;
var fourArgumentPooler = PooledClass.fourArgumentPooler;
var userProvidedKeyEscapeRegex = /\/+/g;
function escapeUserProvidedKey(text) {
return ('' + text).replace(userProvidedKeyEscapeRegex, '$&/');
}
/**
* PooledClass representing the bookkeeping associated with performing a child
* traversal. Allows avoiding binding callbacks.
*
* @constructor ForEachBookKeeping
* @param {!function} forEachFunction Function to perform traversal with.
* @param {?*} forEachContext Context to perform context with.
*/
function ForEachBookKeeping(forEachFunction, forEachContext) {
this.func = forEachFunction;
this.context = forEachContext;
this.count = 0;
}
ForEachBookKeeping.prototype.destructor = function () {
this.func = null;
this.context = null;
this.count = 0;
};
PooledClass.addPoolingTo(ForEachBookKeeping, twoArgumentPooler);
function forEachSingleChild(bookKeeping, child, name) {
var func = bookKeeping.func,
context = bookKeeping.context;
func.call(context, child, bookKeeping.count++);
}
/**
* Iterates through children that are typically specified as `props.children`.
*
* See https://facebook.github.io/react/docs/top-level-api.html#react.children.foreach
*
* The provided forEachFunc(child, index) will be called for each
* leaf child.
*
* @param {?*} children Children tree container.
* @param {function(*, int)} forEachFunc
* @param {*} forEachContext Context for forEachContext.
*/
function forEachChildren(children, forEachFunc, forEachContext) {
if (children == null) {
return children;
}
var traverseContext = ForEachBookKeeping.getPooled(forEachFunc, forEachContext);
traverseAllChildren(children, forEachSingleChild, traverseContext);
ForEachBookKeeping.release(traverseContext);
}
/**
* PooledClass representing the bookkeeping associated with performing a child
* mapping. Allows avoiding binding callbacks.
*
* @constructor MapBookKeeping
* @param {!*} mapResult Object containing the ordered map of results.
* @param {!function} mapFunction Function to perform mapping with.
* @param {?*} mapContext Context to perform mapping with.
*/
function MapBookKeeping(mapResult, keyPrefix, mapFunction, mapContext) {
this.result = mapResult;
this.keyPrefix = keyPrefix;
this.func = mapFunction;
this.context = mapContext;
this.count = 0;
}
MapBookKeeping.prototype.destructor = function () {
this.result = null;
this.keyPrefix = null;
this.func = null;
this.context = null;
this.count = 0;
};
PooledClass.addPoolingTo(MapBookKeeping, fourArgumentPooler);
function mapSingleChildIntoContext(bookKeeping, child, childKey) {
var result = bookKeeping.result,
keyPrefix = bookKeeping.keyPrefix,
func = bookKeeping.func,
context = bookKeeping.context;
var mappedChild = func.call(context, child, bookKeeping.count++);
if (Array.isArray(mappedChild)) {
mapIntoWithKeyPrefixInternal(mappedChild, result, childKey, emptyFunction.thatReturnsArgument);
} else if (mappedChild != null) {
if (ReactElement.isValidElement(mappedChild)) {
mappedChild = ReactElement.cloneAndReplaceKey(mappedChild,
// Keep both the (mapped) and old keys if they differ, just as
// traverseAllChildren used to do for objects as children
keyPrefix + (mappedChild.key && (!child || child.key !== mappedChild.key) ? escapeUserProvidedKey(mappedChild.key) + '/' : '') + childKey);
}
result.push(mappedChild);
}
}
function mapIntoWithKeyPrefixInternal(children, array, prefix, func, context) {
var escapedPrefix = '';
if (prefix != null) {
escapedPrefix = escapeUserProvidedKey(prefix) + '/';
}
var traverseContext = MapBookKeeping.getPooled(array, escapedPrefix, func, context);
traverseAllChildren(children, mapSingleChildIntoContext, traverseContext);
MapBookKeeping.release(traverseContext);
}
/**
* Maps children that are typically specified as `props.children`.
*
* See https://facebook.github.io/react/docs/top-level-api.html#react.children.map
*
* The provided mapFunction(child, key, index) will be called for each
* leaf child.
*
* @param {?*} children Children tree container.
* @param {function(*, int)} func The map function.
* @param {*} context Context for mapFunction.
* @return {object} Object containing the ordered map of results.
*/
function mapChildren(children, func, context) {
if (children == null) {
return children;
}
var result = [];
mapIntoWithKeyPrefixInternal(children, result, null, func, context);
return result;
}
function forEachSingleChildDummy(traverseContext, child, name) {
return null;
}
/**
* Count the number of children that are typically specified as
* `props.children`.
*
* See https://facebook.github.io/react/docs/top-level-api.html#react.children.count
*
* @param {?*} children Children tree container.
* @return {number} The number of children.
*/
function countChildren(children, context) {
return traverseAllChildren(children, forEachSingleChildDummy, null);
}
/**
* Flatten a children object (typically specified as `props.children`) and
* return an array with appropriately re-keyed children.
*
* See https://facebook.github.io/react/docs/top-level-api.html#react.children.toarray
*/
function toArray(children) {
var result = [];
mapIntoWithKeyPrefixInternal(children, result, null, emptyFunction.thatReturnsArgument);
return result;
}
var ReactChildren = {
forEach: forEachChildren,
map: mapChildren,
mapIntoWithKeyPrefixInternal: mapIntoWithKeyPrefixInternal,
count: countChildren,
toArray: toArray
};
module.exports = ReactChildren;
},{"./PooledClass":164,"./ReactElement":171,"./traverseAllChildren":187,"fbjs/lib/emptyFunction":11}],168:[function(require,module,exports){
(function (process){
/**
* Copyright 2016-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
'use strict';
var _prodInvariant = require('./reactProdInvariant');
var ReactCurrentOwner = require('./ReactCurrentOwner');
var invariant = require('fbjs/lib/invariant');
var warning = require('fbjs/lib/warning');
function isNative(fn) {
// Based on isNative() from Lodash
var funcToString = Function.prototype.toString;
var hasOwnProperty = Object.prototype.hasOwnProperty;
var reIsNative = RegExp('^' + funcToString
// Take an example native function source for comparison
.call(hasOwnProperty
// Strip regex characters so we can use it for regex
).replace(/[\\^$.*+?()[\]{}|]/g, '\\$&'
// Remove hasOwnProperty from the template to make it generic
).replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$');
try {
var source = funcToString.call(fn);
return reIsNative.test(source);
} catch (err) {
return false;
}
}
var canUseCollections =
// Array.from
typeof Array.from === 'function' &&
// Map
typeof Map === 'function' && isNative(Map) &&
// Map.prototype.keys
Map.prototype != null && typeof Map.prototype.keys === 'function' && isNative(Map.prototype.keys) &&
// Set
typeof Set === 'function' && isNative(Set) &&
// Set.prototype.keys
Set.prototype != null && typeof Set.prototype.keys === 'function' && isNative(Set.prototype.keys);
var setItem;
var getItem;
var removeItem;
var getItemIDs;
var addRoot;
var removeRoot;
var getRootIDs;
if (canUseCollections) {
var itemMap = new Map();
var rootIDSet = new Set();
setItem = function (id, item) {
itemMap.set(id, item);
};
getItem = function (id) {
return itemMap.get(id);
};
removeItem = function (id) {
itemMap['delete'](id);
};
getItemIDs = function () {
return Array.from(itemMap.keys());
};
addRoot = function (id) {
rootIDSet.add(id);
};
removeRoot = function (id) {
rootIDSet['delete'](id);
};
getRootIDs = function () {
return Array.from(rootIDSet.keys());
};
} else {
var itemByKey = {};
var rootByKey = {};
// Use non-numeric keys to prevent V8 performance issues:
// https://github.com/facebook/react/pull/7232
var getKeyFromID = function (id) {
return '.' + id;
};
var getIDFromKey = function (key) {
return parseInt(key.substr(1), 10);
};
setItem = function (id, item) {
var key = getKeyFromID(id);
itemByKey[key] = item;
};
getItem = function (id) {
var key = getKeyFromID(id);
return itemByKey[key];
};
removeItem = function (id) {
var key = getKeyFromID(id);
delete itemByKey[key];
};
getItemIDs = function () {
return Object.keys(itemByKey).map(getIDFromKey);
};
addRoot = function (id) {
var key = getKeyFromID(id);
rootByKey[key] = true;
};
removeRoot = function (id) {
var key = getKeyFromID(id);
delete rootByKey[key];
};
getRootIDs = function () {
return Object.keys(rootByKey).map(getIDFromKey);
};
}
var unmountedIDs = [];
function purgeDeep(id) {
var item = getItem(id);
if (item) {
var childIDs = item.childIDs;
removeItem(id);
childIDs.forEach(purgeDeep);
}
}
function describeComponentFrame(name, source, ownerName) {
return '\n in ' + (name || 'Unknown') + (source ? ' (at ' + source.fileName.replace(/^.*[\\\/]/, '') + ':' + source.lineNumber + ')' : ownerName ? ' (created by ' + ownerName + ')' : '');
}
function getDisplayName(element) {
if (element == null) {
return '#empty';
} else if (typeof element === 'string' || typeof element === 'number') {
return '#text';
} else if (typeof element.type === 'string') {
return element.type;
} else {
return element.type.displayName || element.type.name || 'Unknown';
}
}
function describeID(id) {
var name = ReactComponentTreeHook.getDisplayName(id);
var element = ReactComponentTreeHook.getElement(id);
var ownerID = ReactComponentTreeHook.getOwnerID(id);
var ownerName;
if (ownerID) {
ownerName = ReactComponentTreeHook.getDisplayName(ownerID);
}
process.env.NODE_ENV !== 'production' ? warning(element, 'ReactComponentTreeHook: Missing React element for debugID %s when ' + 'building stack', id) : void 0;
return describeComponentFrame(name, element && element._source, ownerName);
}
var ReactComponentTreeHook = {
onSetChildren: function (id, nextChildIDs) {
var item = getItem(id);
!item ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Item must have been set') : _prodInvariant('144') : void 0;
item.childIDs = nextChildIDs;
for (var i = 0; i < nextChildIDs.length; i++) {
var nextChildID = nextChildIDs[i];
var nextChild = getItem(nextChildID);
!nextChild ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected hook events to fire for the child before its parent includes it in onSetChildren().') : _prodInvariant('140') : void 0;
!(nextChild.childIDs != null || typeof nextChild.element !== 'object' || nextChild.element == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected onSetChildren() to fire for a container child before its parent includes it in onSetChildren().') : _prodInvariant('141') : void 0;
!nextChild.isMounted ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected onMountComponent() to fire for the child before its parent includes it in onSetChildren().') : _prodInvariant('71') : void 0;
if (nextChild.parentID == null) {
nextChild.parentID = id;
// TODO: This shouldn't be necessary but mounting a new root during in
// componentWillMount currently causes not-yet-mounted components to
// be purged from our tree data so their parent id is missing.
}
!(nextChild.parentID === id) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected onBeforeMountComponent() parent and onSetChildren() to be consistent (%s has parents %s and %s).', nextChildID, nextChild.parentID, id) : _prodInvariant('142', nextChildID, nextChild.parentID, id) : void 0;
}
},
onBeforeMountComponent: function (id, element, parentID) {
var item = {
element: element,
parentID: parentID,
text: null,
childIDs: [],
isMounted: false,
updateCount: 0
};
setItem(id, item);
},
onBeforeUpdateComponent: function (id, element) {
var item = getItem(id);
if (!item || !item.isMounted) {
// We may end up here as a result of setState() in componentWillUnmount().
// In this case, ignore the element.
return;
}
item.element = element;
},
onMountComponent: function (id) {
var item = getItem(id);
!item ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Item must have been set') : _prodInvariant('144') : void 0;
item.isMounted = true;
var isRoot = item.parentID === 0;
if (isRoot) {
addRoot(id);
}
},
onUpdateComponent: function (id) {
var item = getItem(id);
if (!item || !item.isMounted) {
// We may end up here as a result of setState() in componentWillUnmount().
// In this case, ignore the element.
return;
}
item.updateCount++;
},
onUnmountComponent: function (id) {
var item = getItem(id);
if (item) {
// We need to check if it exists.
// `item` might not exist if it is inside an error boundary, and a sibling
// error boundary child threw while mounting. Then this instance never
// got a chance to mount, but it still gets an unmounting event during
// the error boundary cleanup.
item.isMounted = false;
var isRoot = item.parentID === 0;
if (isRoot) {
removeRoot(id);
}
}
unmountedIDs.push(id);
},
purgeUnmountedComponents: function () {
if (ReactComponentTreeHook._preventPurging) {
// Should only be used for testing.
return;
}
for (var i = 0; i < unmountedIDs.length; i++) {
var id = unmountedIDs[i];
purgeDeep(id);
}
unmountedIDs.length = 0;
},
isMounted: function (id) {
var item = getItem(id);
return item ? item.isMounted : false;
},
getCurrentStackAddendum: function (topElement) {
var info = '';
if (topElement) {
var name = getDisplayName(topElement);
var owner = topElement._owner;
info += describeComponentFrame(name, topElement._source, owner && owner.getName());
}
var currentOwner = ReactCurrentOwner.current;
var id = currentOwner && currentOwner._debugID;
info += ReactComponentTreeHook.getStackAddendumByID(id);
return info;
},
getStackAddendumByID: function (id) {
var info = '';
while (id) {
info += describeID(id);
id = ReactComponentTreeHook.getParentID(id);
}
return info;
},
getChildIDs: function (id) {
var item = getItem(id);
return item ? item.childIDs : [];
},
getDisplayName: function (id) {
var element = ReactComponentTreeHook.getElement(id);
if (!element) {
return null;
}
return getDisplayName(element);
},
getElement: function (id) {
var item = getItem(id);
return item ? item.element : null;
},
getOwnerID: function (id) {
var element = ReactComponentTreeHook.getElement(id);
if (!element || !element._owner) {
return null;
}
return element._owner._debugID;
},
getParentID: function (id) {
var item = getItem(id);
return item ? item.parentID : null;
},
getSource: function (id) {
var item = getItem(id);
var element = item ? item.element : null;
var source = element != null ? element._source : null;
return source;
},
getText: function (id) {
var element = ReactComponentTreeHook.getElement(id);
if (typeof element === 'string') {
return element;
} else if (typeof element === 'number') {
return '' + element;
} else {
return null;
}
},
getUpdateCount: function (id) {
var item = getItem(id);
return item ? item.updateCount : 0;
},
getRootIDs: getRootIDs,
getRegisteredIDs: getItemIDs,
pushNonStandardWarningStack: function (isCreatingElement, currentSource) {
if (typeof console.reactStack !== 'function') {
return;
}
var stack = [];
var currentOwner = ReactCurrentOwner.current;
var id = currentOwner && currentOwner._debugID;
try {
if (isCreatingElement) {
stack.push({
name: id ? ReactComponentTreeHook.getDisplayName(id) : null,
fileName: currentSource ? currentSource.fileName : null,
lineNumber: currentSource ? currentSource.lineNumber : null
});
}
while (id) {
var element = ReactComponentTreeHook.getElement(id);
var parentID = ReactComponentTreeHook.getParentID(id);
var ownerID = ReactComponentTreeHook.getOwnerID(id);
var ownerName = ownerID ? ReactComponentTreeHook.getDisplayName(ownerID) : null;
var source = element && element._source;
stack.push({
name: ownerName,
fileName: source ? source.fileName : null,
lineNumber: source ? source.lineNumber : null
});
id = parentID;
}
} catch (err) {
// Internal state is messed up.
// Stop building the stack (it's just a nice to have).
}
console.reactStack(stack);
},
popNonStandardWarningStack: function () {
if (typeof console.reactStackEnd !== 'function') {
return;
}
console.reactStackEnd();
}
};
module.exports = ReactComponentTreeHook;
}).call(this,require('_process'))
},{"./ReactCurrentOwner":169,"./reactProdInvariant":186,"_process":29,"fbjs/lib/invariant":19,"fbjs/lib/warning":26}],169:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
'use strict';
/**
* Keeps track of the current owner.
*
* The current owner is the component who should own any components that are
* currently being constructed.
*/
var ReactCurrentOwner = {
/**
* @internal
* @type {ReactComponent}
*/
current: null
};
module.exports = ReactCurrentOwner;
},{}],170:[function(require,module,exports){
(function (process){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var ReactElement = require('./ReactElement');
/**
* Create a factory that creates HTML tag elements.
*
* @private
*/
var createDOMFactory = ReactElement.createFactory;
if (process.env.NODE_ENV !== 'production') {
var ReactElementValidator = require('./ReactElementValidator');
createDOMFactory = ReactElementValidator.createFactory;
}
/**
* Creates a mapping from supported HTML tags to `ReactDOMComponent` classes.
*
* @public
*/
var ReactDOMFactories = {
a: createDOMFactory('a'),
abbr: createDOMFactory('abbr'),
address: createDOMFactory('address'),
area: createDOMFactory('area'),
article: createDOMFactory('article'),
aside: createDOMFactory('aside'),
audio: createDOMFactory('audio'),
b: createDOMFactory('b'),
base: createDOMFactory('base'),
bdi: createDOMFactory('bdi'),
bdo: createDOMFactory('bdo'),
big: createDOMFactory('big'),
blockquote: createDOMFactory('blockquote'),
body: createDOMFactory('body'),
br: createDOMFactory('br'),
button: createDOMFactory('button'),
canvas: createDOMFactory('canvas'),
caption: createDOMFactory('caption'),
cite: createDOMFactory('cite'),
code: createDOMFactory('code'),
col: createDOMFactory('col'),
colgroup: createDOMFactory('colgroup'),
data: createDOMFactory('data'),
datalist: createDOMFactory('datalist'),
dd: createDOMFactory('dd'),
del: createDOMFactory('del'),
details: createDOMFactory('details'),
dfn: createDOMFactory('dfn'),
dialog: createDOMFactory('dialog'),
div: createDOMFactory('div'),
dl: createDOMFactory('dl'),
dt: createDOMFactory('dt'),
em: createDOMFactory('em'),
embed: createDOMFactory('embed'),
fieldset: createDOMFactory('fieldset'),
figcaption: createDOMFactory('figcaption'),
figure: createDOMFactory('figure'),
footer: createDOMFactory('footer'),
form: createDOMFactory('form'),
h1: createDOMFactory('h1'),
h2: createDOMFactory('h2'),
h3: createDOMFactory('h3'),
h4: createDOMFactory('h4'),
h5: createDOMFactory('h5'),
h6: createDOMFactory('h6'),
head: createDOMFactory('head'),
header: createDOMFactory('header'),
hgroup: createDOMFactory('hgroup'),
hr: createDOMFactory('hr'),
html: createDOMFactory('html'),
i: createDOMFactory('i'),
iframe: createDOMFactory('iframe'),
img: createDOMFactory('img'),
input: createDOMFactory('input'),
ins: createDOMFactory('ins'),
kbd: createDOMFactory('kbd'),
keygen: createDOMFactory('keygen'),
label: createDOMFactory('label'),
legend: createDOMFactory('legend'),
li: createDOMFactory('li'),
link: createDOMFactory('link'),
main: createDOMFactory('main'),
map: createDOMFactory('map'),
mark: createDOMFactory('mark'),
menu: createDOMFactory('menu'),
menuitem: createDOMFactory('menuitem'),
meta: createDOMFactory('meta'),
meter: createDOMFactory('meter'),
nav: createDOMFactory('nav'),
noscript: createDOMFactory('noscript'),
object: createDOMFactory('object'),
ol: createDOMFactory('ol'),
optgroup: createDOMFactory('optgroup'),
option: createDOMFactory('option'),
output: createDOMFactory('output'),
p: createDOMFactory('p'),
param: createDOMFactory('param'),
picture: createDOMFactory('picture'),
pre: createDOMFactory('pre'),
progress: createDOMFactory('progress'),
q: createDOMFactory('q'),
rp: createDOMFactory('rp'),
rt: createDOMFactory('rt'),
ruby: createDOMFactory('ruby'),
s: createDOMFactory('s'),
samp: createDOMFactory('samp'),
script: createDOMFactory('script'),
section: createDOMFactory('section'),
select: createDOMFactory('select'),
small: createDOMFactory('small'),
source: createDOMFactory('source'),
span: createDOMFactory('span'),
strong: createDOMFactory('strong'),
style: createDOMFactory('style'),
sub: createDOMFactory('sub'),
summary: createDOMFactory('summary'),
sup: createDOMFactory('sup'),
table: createDOMFactory('table'),
tbody: createDOMFactory('tbody'),
td: createDOMFactory('td'),
textarea: createDOMFactory('textarea'),
tfoot: createDOMFactory('tfoot'),
th: createDOMFactory('th'),
thead: createDOMFactory('thead'),
time: createDOMFactory('time'),
title: createDOMFactory('title'),
tr: createDOMFactory('tr'),
track: createDOMFactory('track'),
u: createDOMFactory('u'),
ul: createDOMFactory('ul'),
'var': createDOMFactory('var'),
video: createDOMFactory('video'),
wbr: createDOMFactory('wbr'),
// SVG
circle: createDOMFactory('circle'),
clipPath: createDOMFactory('clipPath'),
defs: createDOMFactory('defs'),
ellipse: createDOMFactory('ellipse'),
g: createDOMFactory('g'),
image: createDOMFactory('image'),
line: createDOMFactory('line'),
linearGradient: createDOMFactory('linearGradient'),
mask: createDOMFactory('mask'),
path: createDOMFactory('path'),
pattern: createDOMFactory('pattern'),
polygon: createDOMFactory('polygon'),
polyline: createDOMFactory('polyline'),
radialGradient: createDOMFactory('radialGradient'),
rect: createDOMFactory('rect'),
stop: createDOMFactory('stop'),
svg: createDOMFactory('svg'),
text: createDOMFactory('text'),
tspan: createDOMFactory('tspan')
};
module.exports = ReactDOMFactories;
}).call(this,require('_process'))
},{"./ReactElement":171,"./ReactElementValidator":173,"_process":29}],171:[function(require,module,exports){
(function (process){
/**
* Copyright 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var _assign = require('object-assign');
var ReactCurrentOwner = require('./ReactCurrentOwner');
var warning = require('fbjs/lib/warning');
var canDefineProperty = require('./canDefineProperty');
var hasOwnProperty = Object.prototype.hasOwnProperty;
var REACT_ELEMENT_TYPE = require('./ReactElementSymbol');
var RESERVED_PROPS = {
key: true,
ref: true,
__self: true,
__source: true
};
var specialPropKeyWarningShown, specialPropRefWarningShown;
function hasValidRef(config) {
if (process.env.NODE_ENV !== 'production') {
if (hasOwnProperty.call(config, 'ref')) {
var getter = Object.getOwnPropertyDescriptor(config, 'ref').get;
if (getter && getter.isReactWarning) {
return false;
}
}
}
return config.ref !== undefined;
}
function hasValidKey(config) {
if (process.env.NODE_ENV !== 'production') {
if (hasOwnProperty.call(config, 'key')) {
var getter = Object.getOwnPropertyDescriptor(config, 'key').get;
if (getter && getter.isReactWarning) {
return false;
}
}
}
return config.key !== undefined;
}
function defineKeyPropWarningGetter(props, displayName) {
var warnAboutAccessingKey = function () {
if (!specialPropKeyWarningShown) {
specialPropKeyWarningShown = true;
process.env.NODE_ENV !== 'production' ? warning(false, '%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://fb.me/react-special-props)', displayName) : void 0;
}
};
warnAboutAccessingKey.isReactWarning = true;
Object.defineProperty(props, 'key', {
get: warnAboutAccessingKey,
configurable: true
});
}
function defineRefPropWarningGetter(props, displayName) {
var warnAboutAccessingRef = function () {
if (!specialPropRefWarningShown) {
specialPropRefWarningShown = true;
process.env.NODE_ENV !== 'production' ? warning(false, '%s: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://fb.me/react-special-props)', displayName) : void 0;
}
};
warnAboutAccessingRef.isReactWarning = true;
Object.defineProperty(props, 'ref', {
get: warnAboutAccessingRef,
configurable: true
});
}
/**
* Factory method to create a new React element. This no longer adheres to
* the class pattern, so do not use new to call it. Also, no instanceof check
* will work. Instead test $$typeof field against Symbol.for('react.element') to check
* if something is a React Element.
*
* @param {*} type
* @param {*} key
* @param {string|object} ref
* @param {*} self A *temporary* helper to detect places where `this` is
* different from the `owner` when React.createElement is called, so that we
* can warn. We want to get rid of owner and replace string `ref`s with arrow
* functions, and as long as `this` and owner are the same, there will be no
* change in behavior.
* @param {*} source An annotation object (added by a transpiler or otherwise)
* indicating filename, line number, and/or other information.
* @param {*} owner
* @param {*} props
* @internal
*/
var ReactElement = function (type, key, ref, self, source, owner, props) {
var element = {
// This tag allow us to uniquely identify this as a React Element
$$typeof: REACT_ELEMENT_TYPE,
// Built-in properties that belong on the element
type: type,
key: key,
ref: ref,
props: props,
// Record the component responsible for creating this element.
_owner: owner
};
if (process.env.NODE_ENV !== 'production') {
// The validation flag is currently mutative. We put it on
// an external backing store so that we can freeze the whole object.
// This can be replaced with a WeakMap once they are implemented in
// commonly used development environments.
element._store = {};
// To make comparing ReactElements easier for testing purposes, we make
// the validation flag non-enumerable (where possible, which should
// include every environment we run tests in), so the test framework
// ignores it.
if (canDefineProperty) {
Object.defineProperty(element._store, 'validated', {
configurable: false,
enumerable: false,
writable: true,
value: false
});
// self and source are DEV only properties.
Object.defineProperty(element, '_self', {
configurable: false,
enumerable: false,
writable: false,
value: self
});
// Two elements created in two different places should be considered
// equal for testing purposes and therefore we hide it from enumeration.
Object.defineProperty(element, '_source', {
configurable: false,
enumerable: false,
writable: false,
value: source
});
} else {
element._store.validated = false;
element._self = self;
element._source = source;
}
if (Object.freeze) {
Object.freeze(element.props);
Object.freeze(element);
}
}
return element;
};
/**
* Create and return a new ReactElement of the given type.
* See https://facebook.github.io/react/docs/top-level-api.html#react.createelement
*/
ReactElement.createElement = function (type, config, children) {
var propName;
// Reserved names are extracted
var props = {};
var key = null;
var ref = null;
var self = null;
var source = null;
if (config != null) {
if (hasValidRef(config)) {
ref = config.ref;
}
if (hasValidKey(config)) {
key = '' + config.key;
}
self = config.__self === undefined ? null : config.__self;
source = config.__source === undefined ? null : config.__source;
// Remaining properties are added to a new props object
for (propName in config) {
if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
props[propName] = config[propName];
}
}
}
// Children can be more than one argument, and those are transferred onto
// the newly allocated props object.
var childrenLength = arguments.length - 2;
if (childrenLength === 1) {
props.children = children;
} else if (childrenLength > 1) {
var childArray = Array(childrenLength);
for (var i = 0; i < childrenLength; i++) {
childArray[i] = arguments[i + 2];
}
if (process.env.NODE_ENV !== 'production') {
if (Object.freeze) {
Object.freeze(childArray);
}
}
props.children = childArray;
}
// Resolve default props
if (type && type.defaultProps) {
var defaultProps = type.defaultProps;
for (propName in defaultProps) {
if (props[propName] === undefined) {
props[propName] = defaultProps[propName];
}
}
}
if (process.env.NODE_ENV !== 'production') {
if (key || ref) {
if (typeof props.$$typeof === 'undefined' || props.$$typeof !== REACT_ELEMENT_TYPE) {
var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type;
if (key) {
defineKeyPropWarningGetter(props, displayName);
}
if (ref) {
defineRefPropWarningGetter(props, displayName);
}
}
}
}
return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props);
};
/**
* Return a function that produces ReactElements of a given type.
* See https://facebook.github.io/react/docs/top-level-api.html#react.createfactory
*/
ReactElement.createFactory = function (type) {
var factory = ReactElement.createElement.bind(null, type);
// Expose the type on the factory and the prototype so that it can be
// easily accessed on elements. E.g. `<Foo />.type === Foo`.
// This should not be named `constructor` since this may not be the function
// that created the element, and it may not even be a constructor.
// Legacy hook TODO: Warn if this is accessed
factory.type = type;
return factory;
};
ReactElement.cloneAndReplaceKey = function (oldElement, newKey) {
var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props);
return newElement;
};
/**
* Clone and return a new ReactElement using element as the starting point.
* See https://facebook.github.io/react/docs/top-level-api.html#react.cloneelement
*/
ReactElement.cloneElement = function (element, config, children) {
var propName;
// Original props are copied
var props = _assign({}, element.props);
// Reserved names are extracted
var key = element.key;
var ref = element.ref;
// Self is preserved since the owner is preserved.
var self = element._self;
// Source is preserved since cloneElement is unlikely to be targeted by a
// transpiler, and the original source is probably a better indicator of the
// true owner.
var source = element._source;
// Owner will be preserved, unless ref is overridden
var owner = element._owner;
if (config != null) {
if (hasValidRef(config)) {
// Silently steal the ref from the parent.
ref = config.ref;
owner = ReactCurrentOwner.current;
}
if (hasValidKey(config)) {
key = '' + config.key;
}
// Remaining properties override existing props
var defaultProps;
if (element.type && element.type.defaultProps) {
defaultProps = element.type.defaultProps;
}
for (propName in config) {
if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
if (config[propName] === undefined && defaultProps !== undefined) {
// Resolve default props
props[propName] = defaultProps[propName];
} else {
props[propName] = config[propName];
}
}
}
}
// Children can be more than one argument, and those are transferred onto
// the newly allocated props object.
var childrenLength = arguments.length - 2;
if (childrenLength === 1) {
props.children = children;
} else if (childrenLength > 1) {
var childArray = Array(childrenLength);
for (var i = 0; i < childrenLength; i++) {
childArray[i] = arguments[i + 2];
}
props.children = childArray;
}
return ReactElement(element.type, key, ref, self, source, owner, props);
};
/**
* Verifies the object is a ReactElement.
* See https://facebook.github.io/react/docs/top-level-api.html#react.isvalidelement
* @param {?object} object
* @return {boolean} True if `object` is a valid component.
* @final
*/
ReactElement.isValidElement = function (object) {
return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
};
module.exports = ReactElement;
}).call(this,require('_process'))
},{"./ReactCurrentOwner":169,"./ReactElementSymbol":172,"./canDefineProperty":179,"_process":29,"fbjs/lib/warning":26,"object-assign":28}],172:[function(require,module,exports){
arguments[4][85][0].apply(exports,arguments)
},{"dup":85}],173:[function(require,module,exports){
(function (process){
/**
* Copyright 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
/**
* ReactElementValidator provides a wrapper around a element factory
* which validates the props passed to the element. This is intended to be
* used only in DEV and could be replaced by a static type checker for languages
* that support it.
*/
'use strict';
var ReactCurrentOwner = require('./ReactCurrentOwner');
var ReactComponentTreeHook = require('./ReactComponentTreeHook');
var ReactElement = require('./ReactElement');
var checkReactTypeSpec = require('./checkReactTypeSpec');
var canDefineProperty = require('./canDefineProperty');
var getIteratorFn = require('./getIteratorFn');
var warning = require('fbjs/lib/warning');
var lowPriorityWarning = require('./lowPriorityWarning');
function getDeclarationErrorAddendum() {
if (ReactCurrentOwner.current) {
var name = ReactCurrentOwner.current.getName();
if (name) {
return ' Check the render method of `' + name + '`.';
}
}
return '';
}
function getSourceInfoErrorAddendum(elementProps) {
if (elementProps !== null && elementProps !== undefined && elementProps.__source !== undefined) {
var source = elementProps.__source;
var fileName = source.fileName.replace(/^.*[\\\/]/, '');
var lineNumber = source.lineNumber;
return ' Check your code at ' + fileName + ':' + lineNumber + '.';
}
return '';
}
/**
* Warn if there's no key explicitly set on dynamic arrays of children or
* object keys are not valid. This allows us to keep track of children between
* updates.
*/
var ownerHasKeyUseWarning = {};
function getCurrentComponentErrorInfo(parentType) {
var info = getDeclarationErrorAddendum();
if (!info) {
var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name;
if (parentName) {
info = ' Check the top-level render call using <' + parentName + '>.';
}
}
return info;
}
/**
* Warn if the element doesn't have an explicit key assigned to it.
* This element is in an array. The array could grow and shrink or be
* reordered. All children that haven't already been validated are required to
* have a "key" property assigned to it. Error statuses are cached so a warning
* will only be shown once.
*
* @internal
* @param {ReactElement} element Element that requires a key.
* @param {*} parentType element's parent's type.
*/
function validateExplicitKey(element, parentType) {
if (!element._store || element._store.validated || element.key != null) {
return;
}
element._store.validated = true;
var memoizer = ownerHasKeyUseWarning.uniqueKey || (ownerHasKeyUseWarning.uniqueKey = {});
var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType);
if (memoizer[currentComponentErrorInfo]) {
return;
}
memoizer[currentComponentErrorInfo] = true;
// Usually the current owner is the offender, but if it accepts children as a
// property, it may be the creator of the child that's responsible for
// assigning it a key.
var childOwner = '';
if (element && element._owner && element._owner !== ReactCurrentOwner.current) {
// Give the component that originally created this child.
childOwner = ' It was passed a child from ' + element._owner.getName() + '.';
}
process.env.NODE_ENV !== 'production' ? warning(false, 'Each child in an array or iterator should have a unique "key" prop.' + '%s%s See https://fb.me/react-warning-keys for more information.%s', currentComponentErrorInfo, childOwner, ReactComponentTreeHook.getCurrentStackAddendum(element)) : void 0;
}
/**
* Ensure that every element either is passed in a static location, in an
* array with an explicit keys property defined, or in an object literal
* with valid key property.
*
* @internal
* @param {ReactNode} node Statically passed child of any type.
* @param {*} parentType node's parent's type.
*/
function validateChildKeys(node, parentType) {
if (typeof node !== 'object') {
return;
}
if (Array.isArray(node)) {
for (var i = 0; i < node.length; i++) {
var child = node[i];
if (ReactElement.isValidElement(child)) {
validateExplicitKey(child, parentType);
}
}
} else if (ReactElement.isValidElement(node)) {
// This element was passed in a valid location.
if (node._store) {
node._store.validated = true;
}
} else if (node) {
var iteratorFn = getIteratorFn(node);
// Entry iterators provide implicit keys.
if (iteratorFn) {
if (iteratorFn !== node.entries) {
var iterator = iteratorFn.call(node);
var step;
while (!(step = iterator.next()).done) {
if (ReactElement.isValidElement(step.value)) {
validateExplicitKey(step.value, parentType);
}
}
}
}
}
}
/**
* Given an element, validate that its props follow the propTypes definition,
* provided by the type.
*
* @param {ReactElement} element
*/
function validatePropTypes(element) {
var componentClass = element.type;
if (typeof componentClass !== 'function') {
return;
}
var name = componentClass.displayName || componentClass.name;
if (componentClass.propTypes) {
checkReactTypeSpec(componentClass.propTypes, element.props, 'prop', name, element, null);
}
if (typeof componentClass.getDefaultProps === 'function') {
process.env.NODE_ENV !== 'production' ? warning(componentClass.getDefaultProps.isReactClassApproved, 'getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.') : void 0;
}
}
var ReactElementValidator = {
createElement: function (type, props, children) {
var validType = typeof type === 'string' || typeof type === 'function';
// We warn in this case but don't throw. We expect the element creation to
// succeed and there will likely be errors in render.
if (!validType) {
if (typeof type !== 'function' && typeof type !== 'string') {
var info = '';
if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {
info += ' You likely forgot to export your component from the file ' + "it's defined in.";
}
var sourceInfo = getSourceInfoErrorAddendum(props);
if (sourceInfo) {
info += sourceInfo;
} else {
info += getDeclarationErrorAddendum();
}
info += ReactComponentTreeHook.getCurrentStackAddendum();
var currentSource = props !== null && props !== undefined && props.__source !== undefined ? props.__source : null;
ReactComponentTreeHook.pushNonStandardWarningStack(true, currentSource);
process.env.NODE_ENV !== 'production' ? warning(false, 'React.createElement: type is invalid -- expected a string (for ' + 'built-in components) or a class/function (for composite ' + 'components) but got: %s.%s', type == null ? type : typeof type, info) : void 0;
ReactComponentTreeHook.popNonStandardWarningStack();
}
}
var element = ReactElement.createElement.apply(this, arguments);
// The result can be nullish if a mock or a custom function is used.
// TODO: Drop this when these are no longer allowed as the type argument.
if (element == null) {
return element;
}
// Skip key warning if the type isn't valid since our key validation logic
// doesn't expect a non-string/function type and can throw confusing errors.
// We don't want exception behavior to differ between dev and prod.
// (Rendering will throw with a helpful message and as soon as the type is
// fixed, the key warnings will appear.)
if (validType) {
for (var i = 2; i < arguments.length; i++) {
validateChildKeys(arguments[i], type);
}
}
validatePropTypes(element);
return element;
},
createFactory: function (type) {
var validatedFactory = ReactElementValidator.createElement.bind(null, type);
// Legacy hook TODO: Warn if this is accessed
validatedFactory.type = type;
if (process.env.NODE_ENV !== 'production') {
if (canDefineProperty) {
Object.defineProperty(validatedFactory, 'type', {
enumerable: false,
get: function () {
lowPriorityWarning(false, 'Factory.type is deprecated. Access the class directly ' + 'before passing it to createFactory.');
Object.defineProperty(this, 'type', {
value: type
});
return type;
}
});
}
}
return validatedFactory;
},
cloneElement: function (element, props, children) {
var newElement = ReactElement.cloneElement.apply(this, arguments);
for (var i = 2; i < arguments.length; i++) {
validateChildKeys(arguments[i], newElement.type);
}
validatePropTypes(newElement);
return newElement;
}
};
module.exports = ReactElementValidator;
}).call(this,require('_process'))
},{"./ReactComponentTreeHook":168,"./ReactCurrentOwner":169,"./ReactElement":171,"./canDefineProperty":179,"./checkReactTypeSpec":180,"./getIteratorFn":182,"./lowPriorityWarning":184,"_process":29,"fbjs/lib/warning":26}],174:[function(require,module,exports){
(function (process){
/**
* Copyright 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var warning = require('fbjs/lib/warning');
function warnNoop(publicInstance, callerName) {
if (process.env.NODE_ENV !== 'production') {
var constructor = publicInstance.constructor;
process.env.NODE_ENV !== 'production' ? warning(false, '%s(...): Can only update a mounted or mounting component. ' + 'This usually means you called %s() on an unmounted component. ' + 'This is a no-op. Please check the code for the %s component.', callerName, callerName, constructor && (constructor.displayName || constructor.name) || 'ReactClass') : void 0;
}
}
/**
* This is the abstract API for an update queue.
*/
var ReactNoopUpdateQueue = {
/**
* Checks whether or not this composite component is mounted.
* @param {ReactClass} publicInstance The instance we want to test.
* @return {boolean} True if mounted, false otherwise.
* @protected
* @final
*/
isMounted: function (publicInstance) {
return false;
},
/**
* Enqueue a callback that will be executed after all the pending updates
* have processed.
*
* @param {ReactClass} publicInstance The instance to use as `this` context.
* @param {?function} callback Called after state is updated.
* @internal
*/
enqueueCallback: function (publicInstance, callback) {},
/**
* Forces an update. This should only be invoked when it is known with
* certainty that we are **not** in a DOM transaction.
*
* You may want to call this when you know that some deeper aspect of the
* component's state has changed but `setState` was not called.
*
* This will not invoke `shouldComponentUpdate`, but it will invoke
* `componentWillUpdate` and `componentDidUpdate`.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @internal
*/
enqueueForceUpdate: function (publicInstance) {
warnNoop(publicInstance, 'forceUpdate');
},
/**
* Replaces all of the state. Always use this or `setState` to mutate state.
* You should treat `this.state` as immutable.
*
* There is no guarantee that `this.state` will be immediately updated, so
* accessing `this.state` after calling this method may return the old value.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @param {object} completeState Next state.
* @internal
*/
enqueueReplaceState: function (publicInstance, completeState) {
warnNoop(publicInstance, 'replaceState');
},
/**
* Sets a subset of the state. This only exists because _pendingState is
* internal. This provides a merging strategy that is not available to deep
* properties which is confusing. TODO: Expose pendingState or don't use it
* during the merge.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @param {object} partialState Next partial state to be merged with state.
* @internal
*/
enqueueSetState: function (publicInstance, partialState) {
warnNoop(publicInstance, 'setState');
}
};
module.exports = ReactNoopUpdateQueue;
}).call(this,require('_process'))
},{"_process":29,"fbjs/lib/warning":26}],175:[function(require,module,exports){
arguments[4][103][0].apply(exports,arguments)
},{"_process":29,"dup":103}],176:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var _require = require('./ReactElement'),
isValidElement = _require.isValidElement;
var factory = require('prop-types/factory');
module.exports = factory(isValidElement);
},{"./ReactElement":171,"prop-types/factory":31}],177:[function(require,module,exports){
arguments[4][104][0].apply(exports,arguments)
},{"dup":104}],178:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
module.exports = '15.6.1';
},{}],179:[function(require,module,exports){
(function (process){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
'use strict';
var canDefineProperty = false;
if (process.env.NODE_ENV !== 'production') {
try {
// $FlowFixMe https://github.com/facebook/flow/issues/285
Object.defineProperty({}, 'x', { get: function () {} });
canDefineProperty = true;
} catch (x) {
// IE will fail on defineProperty
}
}
module.exports = canDefineProperty;
}).call(this,require('_process'))
},{"_process":29}],180:[function(require,module,exports){
(function (process){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var _prodInvariant = require('./reactProdInvariant');
var ReactPropTypeLocationNames = require('./ReactPropTypeLocationNames');
var ReactPropTypesSecret = require('./ReactPropTypesSecret');
var invariant = require('fbjs/lib/invariant');
var warning = require('fbjs/lib/warning');
var ReactComponentTreeHook;
if (typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'test') {
// Temporary hack.
// Inline requires don't work well with Jest:
// https://github.com/facebook/react/issues/7240
// Remove the inline requires when we don't need them anymore:
// https://github.com/facebook/react/pull/7178
ReactComponentTreeHook = require('./ReactComponentTreeHook');
}
var loggedTypeFailures = {};
/**
* Assert that the values match with the type specs.
* Error messages are memorized and will only be shown once.
*
* @param {object} typeSpecs Map of name to a ReactPropType
* @param {object} values Runtime values that need to be type-checked
* @param {string} location e.g. "prop", "context", "child context"
* @param {string} componentName Name of the component for error messages.
* @param {?object} element The React element that is being type-checked
* @param {?number} debugID The React component instance that is being type-checked
* @private
*/
function checkReactTypeSpec(typeSpecs, values, location, componentName, element, debugID) {
for (var typeSpecName in typeSpecs) {
if (typeSpecs.hasOwnProperty(typeSpecName)) {
var error;
// Prop type validation may throw. In case they do, we don't want to
// fail the render phase where it didn't fail before. So we log it.
// After these have been cleaned up, we'll let them throw.
try {
// This is intentionally an invariant that gets caught. It's the same
// behavior as without this statement except with a better message.
!(typeof typeSpecs[typeSpecName] === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s: %s type `%s` is invalid; it must be a function, usually from React.PropTypes.', componentName || 'React class', ReactPropTypeLocationNames[location], typeSpecName) : _prodInvariant('84', componentName || 'React class', ReactPropTypeLocationNames[location], typeSpecName) : void 0;
error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret);
} catch (ex) {
error = ex;
}
process.env.NODE_ENV !== 'production' ? warning(!error || error instanceof Error, '%s: type specification of %s `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', ReactPropTypeLocationNames[location], typeSpecName, typeof error) : void 0;
if (error instanceof Error && !(error.message in loggedTypeFailures)) {
// Only monitor this failure once because there tends to be a lot of the
// same error.
loggedTypeFailures[error.message] = true;
var componentStackInfo = '';
if (process.env.NODE_ENV !== 'production') {
if (!ReactComponentTreeHook) {
ReactComponentTreeHook = require('./ReactComponentTreeHook');
}
if (debugID !== null) {
componentStackInfo = ReactComponentTreeHook.getStackAddendumByID(debugID);
} else if (element !== null) {
componentStackInfo = ReactComponentTreeHook.getCurrentStackAddendum(element);
}
}
process.env.NODE_ENV !== 'production' ? warning(false, 'Failed %s type: %s%s', location, error.message, componentStackInfo) : void 0;
}
}
}
}
module.exports = checkReactTypeSpec;
}).call(this,require('_process'))
},{"./ReactComponentTreeHook":168,"./ReactPropTypeLocationNames":175,"./ReactPropTypesSecret":177,"./reactProdInvariant":186,"_process":29,"fbjs/lib/invariant":19,"fbjs/lib/warning":26}],181:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var _require = require('./ReactBaseClasses'),
Component = _require.Component;
var _require2 = require('./ReactElement'),
isValidElement = _require2.isValidElement;
var ReactNoopUpdateQueue = require('./ReactNoopUpdateQueue');
var factory = require('create-react-class/factory');
module.exports = factory(Component, isValidElement, ReactNoopUpdateQueue);
},{"./ReactBaseClasses":166,"./ReactElement":171,"./ReactNoopUpdateQueue":174,"create-react-class/factory":3}],182:[function(require,module,exports){
arguments[4][145][0].apply(exports,arguments)
},{"dup":145}],183:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
'use strict';
var nextDebugID = 1;
function getNextDebugID() {
return nextDebugID++;
}
module.exports = getNextDebugID;
},{}],184:[function(require,module,exports){
(function (process){
/**
* Copyright 2014-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
/**
* Forked from fbjs/warning:
* https://github.com/facebook/fbjs/blob/e66ba20ad5be433eb54423f2b097d829324d9de6/packages/fbjs/src/__forks__/warning.js
*
* Only change is we use console.warn instead of console.error,
* and do nothing when 'console' is not supported.
* This really simplifies the code.
* ---
* Similar to invariant but only logs a warning if the condition is not met.
* This can be used to log issues in development environments in critical
* paths. Removing the logging code for production environments will keep the
* same logic and follow the same code paths.
*/
var lowPriorityWarning = function () {};
if (process.env.NODE_ENV !== 'production') {
var printWarning = function (format) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
var argIndex = 0;
var message = 'Warning: ' + format.replace(/%s/g, function () {
return args[argIndex++];
});
if (typeof console !== 'undefined') {
console.warn(message);
}
try {
// --- Welcome to debugging React ---
// This error was thrown as a convenience so that you can use this stack
// to find the callsite that caused this warning to fire.
throw new Error(message);
} catch (x) {}
};
lowPriorityWarning = function (condition, format) {
if (format === undefined) {
throw new Error('`warning(condition, format, ...args)` requires a warning ' + 'message argument');
}
if (!condition) {
for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
args[_key2 - 2] = arguments[_key2];
}
printWarning.apply(undefined, [format].concat(args));
}
};
}
module.exports = lowPriorityWarning;
}).call(this,require('_process'))
},{"_process":29}],185:[function(require,module,exports){
(function (process){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var _prodInvariant = require('./reactProdInvariant');
var ReactElement = require('./ReactElement');
var invariant = require('fbjs/lib/invariant');
/**
* Returns the first child in a collection of children and verifies that there
* is only one child in the collection.
*
* See https://facebook.github.io/react/docs/top-level-api.html#react.children.only
*
* The current implementation of this function assumes that a single child gets
* passed without a wrapper, but the purpose of this helper function is to
* abstract away the particular structure of children.
*
* @param {?object} children Child collection structure.
* @return {ReactElement} The first and only `ReactElement` contained in the
* structure.
*/
function onlyChild(children) {
!ReactElement.isValidElement(children) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'React.Children.only expected to receive a single React element child.') : _prodInvariant('143') : void 0;
return children;
}
module.exports = onlyChild;
}).call(this,require('_process'))
},{"./ReactElement":171,"./reactProdInvariant":186,"_process":29,"fbjs/lib/invariant":19}],186:[function(require,module,exports){
arguments[4][153][0].apply(exports,arguments)
},{"dup":153}],187:[function(require,module,exports){
(function (process){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var _prodInvariant = require('./reactProdInvariant');
var ReactCurrentOwner = require('./ReactCurrentOwner');
var REACT_ELEMENT_TYPE = require('./ReactElementSymbol');
var getIteratorFn = require('./getIteratorFn');
var invariant = require('fbjs/lib/invariant');
var KeyEscapeUtils = require('./KeyEscapeUtils');
var warning = require('fbjs/lib/warning');
var SEPARATOR = '.';
var SUBSEPARATOR = ':';
/**
* This is inlined from ReactElement since this file is shared between
* isomorphic and renderers. We could extract this to a
*
*/
/**
* TODO: Test that a single child and an array with one item have the same key
* pattern.
*/
var didWarnAboutMaps = false;
/**
* Generate a key string that identifies a component within a set.
*
* @param {*} component A component that could contain a manual key.
* @param {number} index Index that is used if a manual key is not provided.
* @return {string}
*/
function getComponentKey(component, index) {
// Do some typechecking here since we call this blindly. We want to ensure
// that we don't block potential future ES APIs.
if (component && typeof component === 'object' && component.key != null) {
// Explicit key
return KeyEscapeUtils.escape(component.key);
}
// Implicit key determined by the index in the set
return index.toString(36);
}
/**
* @param {?*} children Children tree container.
* @param {!string} nameSoFar Name of the key path so far.
* @param {!function} callback Callback to invoke with each child found.
* @param {?*} traverseContext Used to pass information throughout the traversal
* process.
* @return {!number} The number of children in this subtree.
*/
function traverseAllChildrenImpl(children, nameSoFar, callback, traverseContext) {
var type = typeof children;
if (type === 'undefined' || type === 'boolean') {
// All of the above are perceived as null.
children = null;
}
if (children === null || type === 'string' || type === 'number' ||
// The following is inlined from ReactElement. This means we can optimize
// some checks. React Fiber also inlines this logic for similar purposes.
type === 'object' && children.$$typeof === REACT_ELEMENT_TYPE) {
callback(traverseContext, children,
// If it's the only child, treat the name as if it was wrapped in an array
// so that it's consistent if the number of children grows.
nameSoFar === '' ? SEPARATOR + getComponentKey(children, 0) : nameSoFar);
return 1;
}
var child;
var nextName;
var subtreeCount = 0; // Count of children found in the current subtree.
var nextNamePrefix = nameSoFar === '' ? SEPARATOR : nameSoFar + SUBSEPARATOR;
if (Array.isArray(children)) {
for (var i = 0; i < children.length; i++) {
child = children[i];
nextName = nextNamePrefix + getComponentKey(child, i);
subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext);
}
} else {
var iteratorFn = getIteratorFn(children);
if (iteratorFn) {
var iterator = iteratorFn.call(children);
var step;
if (iteratorFn !== children.entries) {
var ii = 0;
while (!(step = iterator.next()).done) {
child = step.value;
nextName = nextNamePrefix + getComponentKey(child, ii++);
subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext);
}
} else {
if (process.env.NODE_ENV !== 'production') {
var mapsAsChildrenAddendum = '';
if (ReactCurrentOwner.current) {
var mapsAsChildrenOwnerName = ReactCurrentOwner.current.getName();
if (mapsAsChildrenOwnerName) {
mapsAsChildrenAddendum = ' Check the render method of `' + mapsAsChildrenOwnerName + '`.';
}
}
process.env.NODE_ENV !== 'production' ? warning(didWarnAboutMaps, 'Using Maps as children is not yet fully supported. It is an ' + 'experimental feature that might be removed. Convert it to a ' + 'sequence / iterable of keyed ReactElements instead.%s', mapsAsChildrenAddendum) : void 0;
didWarnAboutMaps = true;
}
// Iterator will provide entry [k,v] tuples rather than values.
while (!(step = iterator.next()).done) {
var entry = step.value;
if (entry) {
child = entry[1];
nextName = nextNamePrefix + KeyEscapeUtils.escape(entry[0]) + SUBSEPARATOR + getComponentKey(child, 0);
subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext);
}
}
}
} else if (type === 'object') {
var addendum = '';
if (process.env.NODE_ENV !== 'production') {
addendum = ' If you meant to render a collection of children, use an array ' + 'instead or wrap the object using createFragment(object) from the ' + 'React add-ons.';
if (children._isReactElement) {
addendum = " It looks like you're using an element created by a different " + 'version of React. Make sure to use only one copy of React.';
}
if (ReactCurrentOwner.current) {
var name = ReactCurrentOwner.current.getName();
if (name) {
addendum += ' Check the render method of `' + name + '`.';
}
}
}
var childrenString = String(children);
!false ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Objects are not valid as a React child (found: %s).%s', childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString, addendum) : _prodInvariant('31', childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString, addendum) : void 0;
}
}
return subtreeCount;
}
/**
* Traverses children that are typically specified as `props.children`, but
* might also be specified through attributes:
*
* - `traverseAllChildren(this.props.children, ...)`
* - `traverseAllChildren(this.props.leftPanelChildren, ...)`
*
* The `traverseContext` is an optional argument that is passed through the
* entire traversal. It can be used to store accumulations or anything else that
* the callback might find relevant.
*
* @param {?*} children Children tree object.
* @param {!function} callback To invoke upon traversing each child.
* @param {?*} traverseContext Context for traversal.
* @return {!number} The number of children in this subtree.
*/
function traverseAllChildren(children, callback, traverseContext) {
if (children == null) {
return 0;
}
return traverseAllChildrenImpl(children, '', callback, traverseContext);
}
module.exports = traverseAllChildren;
}).call(this,require('_process'))
},{"./KeyEscapeUtils":163,"./ReactCurrentOwner":169,"./ReactElementSymbol":172,"./getIteratorFn":182,"./reactProdInvariant":186,"_process":29,"fbjs/lib/invariant":19,"fbjs/lib/warning":26}],188:[function(require,module,exports){
'use strict';
module.exports = require('./lib/React');
},{"./lib/React":165}],189:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _lodash = require('lodash.isequal');
var _lodash2 = _interopRequireDefault(_lodash);
var _resizer = require('./resizer');
var _resizer2 = _interopRequireDefault(_resizer);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
/* eslint-disable import/no-extraneous-dependencies */
/* eslint-disable react/no-unused-prop-types */
/* eslint-disable react/require-default-props */
/* eslint-disable react/jsx-filename-extension */
/* eslint-disable react/sort-comp */
/* eslint-disable jsx-a11y/no-static-element-interactions */
/* eslint-disable max-len */
/* eslint-disable no-bitwise */
/* eslint-disable react/no-did-mount-set-state */
var userSelectNone = {
userSelect: 'none',
MozUserSelect: 'none',
WebkitUserSelect: 'none',
MsUserSelect: 'none'
};
var userSelectAuto = {
userSelect: 'auto',
MozUserSelect: 'auto',
WebkitUserSelect: 'auto',
MsUserSelect: 'auto'
};
var clamp = function clamp(n, min, max) {
return Math.max(Math.min(n, max), min);
};
var snap = function snap(n, size) {
return Math.round(n / size) * size;
};
var Resizable = function (_Component) {
_inherits(Resizable, _Component);
function Resizable(props) {
_classCallCheck(this, Resizable);
var _this = _possibleConstructorReturn(this, (Resizable.__proto__ || Object.getPrototypeOf(Resizable)).call(this, props));
var width = props.width,
height = props.height;
_this.state = {
isResizing: false,
width: typeof width === 'undefined' ? 'auto' : width,
height: typeof height === 'undefined' ? 'auto' : height,
direction: 'right',
original: {
x: 0,
y: 0,
width: 0,
height: 0
}
};
_this.onResizeStart = _this.onResizeStart.bind(_this);
_this.onMouseMove = _this.onMouseMove.bind(_this);
_this.onMouseUp = _this.onMouseUp.bind(_this);
if (typeof window !== 'undefined') {
window.addEventListener('mouseup', _this.onMouseUp);
window.addEventListener('mousemove', _this.onMouseMove);
window.addEventListener('touchmove', _this.onMouseMove);
window.addEventListener('touchend', _this.onMouseUp);
}
return _this;
}
_createClass(Resizable, [{
key: 'componentDidMount',
value: function componentDidMount() {
var size = this.size;
// If props.width or height is not defined, set default size when mounted.
this.setState({
width: this.state.width || size.width,
height: this.state.height || size.height
});
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(_ref) {
var width = _ref.width,
height = _ref.height;
if (width !== this.props.width) {
this.setState({ width: width });
}
if (height !== this.props.height) {
this.setState({ height: height });
}
}
}, {
key: 'shouldComponentUpdate',
value: function shouldComponentUpdate(nextProps, nextState) {
return !(0, _lodash2.default)(this.props, nextProps) || !(0, _lodash2.default)(this.state, nextState);
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
if (typeof window !== 'undefined') {
window.removeEventListener('mouseup', this.onMouseUp);
window.removeEventListener('mousemove', this.onMouseMove);
window.removeEventListener('touchmove', this.onMouseMove);
window.removeEventListener('touchend', this.onMouseUp);
}
}
}, {
key: 'onResizeStart',
value: function onResizeStart(event, direction) {
var clientX = 0;
var clientY = 0;
if (event.nativeEvent instanceof MouseEvent) {
clientX = event.nativeEvent.clientX;
clientY = event.nativeEvent.clientY;
} else if (event.nativeEvent instanceof TouchEvent) {
clientX = event.nativeEvent.touches[0].clientX;
clientY = event.nativeEvent.touches[0].clientY;
}
if (this.props.onResizeStart) {
this.props.onResizeStart(event, direction, this.resizable);
}
var size = this.size;
this.setState({
original: {
x: clientX,
y: clientY,
width: size.width,
height: size.height
},
isResizing: true,
direction: direction
});
}
}, {
key: 'onMouseMove',
value: function onMouseMove(event) {
if (!this.state.isResizing) return;
var clientX = event instanceof MouseEvent ? event.clientX : event.touches[0].clientX;
var clientY = event instanceof MouseEvent ? event.clientY : event.touches[0].clientY;
var _state = this.state,
direction = _state.direction,
original = _state.original,
width = _state.width,
height = _state.height;
var _props = this.props,
lockAspectRatio = _props.lockAspectRatio,
minWidth = _props.minWidth,
minHeight = _props.minHeight;
var _props2 = this.props,
maxWidth = _props2.maxWidth,
maxHeight = _props2.maxHeight;
var ratio = original.height / original.width;
var newWidth = original.width;
var newHeight = original.height;
if (/right/i.test(direction)) {
newWidth = original.width + (clientX - original.x);
if (lockAspectRatio) newHeight = newWidth * ratio;
}
if (/left/i.test(direction)) {
newWidth = original.width - (clientX - original.x);
if (lockAspectRatio) newHeight = newWidth * ratio;
}
if (/bottom/i.test(direction)) {
newHeight = original.height + (clientY - original.y);
if (lockAspectRatio) newWidth = newHeight / ratio;
}
if (/top/i.test(direction)) {
newHeight = original.height - (clientY - original.y);
if (lockAspectRatio) newWidth = newHeight / ratio;
}
if (this.props.bounds === 'parent') {
var parent = this.resizable.parentNode;
if (parent instanceof HTMLElement) {
var parentRect = parent.getBoundingClientRect();
var parentLeft = parentRect.left;
var parentTop = parentRect.top;
var _resizable$getBoundin = this.resizable.getBoundingClientRect(),
_left = _resizable$getBoundin.left,
_top = _resizable$getBoundin.top;
var boundWidth = parent.offsetWidth + (parentLeft - _left);
var boundHeight = parent.offsetHeight + (parentTop - _top);
maxWidth = maxWidth && maxWidth < boundWidth ? maxWidth : boundWidth;
maxHeight = maxHeight && maxHeight < boundHeight ? maxHeight : boundHeight;
}
} else if (this.props.bounds === 'window') {
if (typeof window !== 'undefined') {
var _resizable$getBoundin2 = this.resizable.getBoundingClientRect(),
_left2 = _resizable$getBoundin2.left,
_top2 = _resizable$getBoundin2.top;
var _boundWidth = window.innerWidth - _left2;
var _boundHeight = window.innerHeight - _top2;
maxWidth = maxWidth && maxWidth < _boundWidth ? maxWidth : _boundWidth;
maxHeight = maxHeight && maxHeight < _boundHeight ? maxHeight : _boundHeight;
}
} else if (this.props.bounds instanceof HTMLElement) {
var targetRect = this.props.bounds.getBoundingClientRect();
var targetLeft = targetRect.left;
var targetTop = targetRect.top;
var _resizable$getBoundin3 = this.resizable.getBoundingClientRect(),
_left3 = _resizable$getBoundin3.left,
_top3 = _resizable$getBoundin3.top;
if (!(this.props.bounds instanceof HTMLElement)) return;
var _boundWidth2 = this.props.bounds.offsetWidth + (targetLeft - _left3);
var _boundHeight2 = this.props.bounds.offsetHeight + (targetTop - _top3);
maxWidth = maxWidth && maxWidth < _boundWidth2 ? maxWidth : _boundWidth2;
maxHeight = maxHeight && maxHeight < _boundHeight2 ? maxHeight : _boundHeight2;
}
var computedMinWidth = typeof minWidth === 'undefined' || minWidth < 0 ? 0 : minWidth;
var computedMaxWidth = typeof maxWidth === 'undefined' || maxWidth < 0 ? newWidth : maxWidth;
var computedMinHeight = typeof minHeight === 'undefined' || minHeight < 0 ? 0 : minHeight;
var computedMaxHeight = typeof maxHeight === 'undefined' || maxHeight < 0 ? newHeight : maxHeight;
if (lockAspectRatio) {
var lockedMinWidth = computedMinWidth > computedMinHeight / ratio ? computedMinWidth : computedMinHeight / ratio;
var lockedMaxWidth = computedMaxWidth < computedMaxHeight / ratio ? computedMaxWidth : computedMaxHeight / ratio;
var lockedMinHeight = computedMinHeight > computedMinWidth * ratio ? computedMinHeight : computedMinWidth * ratio;
var lockedMaxHeight = computedMaxHeight < computedMaxWidth * ratio ? computedMaxHeight : computedMaxWidth * ratio;
newWidth = clamp(newWidth, lockedMinWidth, lockedMaxWidth);
newHeight = clamp(newHeight, lockedMinHeight, lockedMaxHeight);
} else {
newWidth = clamp(newWidth, computedMinWidth, computedMaxWidth);
newHeight = clamp(newHeight, computedMinHeight, computedMaxHeight);
}
if (this.props.grid) {
newWidth = snap(newWidth, this.props.grid[0]);
}
if (this.props.grid) {
newHeight = snap(newHeight, this.props.grid[1]);
}
this.setState({
width: width !== 'auto' ? newWidth : 'auto',
height: height !== 'auto' ? newHeight : 'auto'
});
var delta = {
width: newWidth - original.width,
height: newHeight - original.height
};
if (this.props.onResize) {
this.props.onResize(event, direction, this.resizable, delta);
}
}
}, {
key: 'onMouseUp',
value: function onMouseUp(event) {
var _state2 = this.state,
isResizing = _state2.isResizing,
direction = _state2.direction,
original = _state2.original;
if (!isResizing) return;
var delta = {
width: this.size.width - original.width,
height: this.size.height - original.height
};
if (this.props.onResizeStop) {
this.props.onResizeStop(event, direction, this.resizable, delta);
}
this.setState({ isResizing: false });
}
}, {
key: 'setSize',
value: function setSize(size) {
this.setState({
width: this.state.width || size.width,
height: this.state.height || size.height
});
}
}, {
key: 'updateSize',
value: function updateSize(size) {
this.setState({ width: size.width, height: size.height });
}
}, {
key: 'renderResizer',
value: function renderResizer() {
var _this2 = this;
var _props3 = this.props,
enable = _props3.enable,
handlerStyles = _props3.handlerStyles,
handlerClasses = _props3.handlerClasses;
if (!enable) return null;
var content = Object.keys(enable).map(function (dir) {
if (enable[dir] !== false) {
return _react2.default.createElement(_resizer2.default, {
key: dir,
direction: dir,
onResizeStart: _this2.onResizeStart,
replaceStyles: handlerStyles && handlerStyles[dir],
className: handlerClasses && handlerClasses[dir]
});
}
return null;
});
// #93 Wrap the resize box in span (will not break 100% width/height)
if (handlerClasses && handlerClasses['wrapper']) {
return _react2.default.createElement(
'span',
{ className: handlerClasses && handlerClasses['wrapper'] },
content
);
}
return content;
}
}, {
key: 'render',
value: function render() {
var _this3 = this;
var userSelect = this.state.isResizing ? userSelectNone : userSelectAuto;
var _props4 = this.props,
style = _props4.style,
className = _props4.className;
return _react2.default.createElement(
'div',
_extends({
ref: function ref(c) {
_this3.resizable = c;
},
style: _extends({
position: 'relative'
}, userSelect, style, this.style, {
boxSizing: 'border-box'
}),
className: className
}, this.props.extendsProps),
this.props.children,
this.renderResizer()
);
}
}, {
key: 'size',
get: function get() {
var width = 0;
var height = 0;
if (typeof window !== 'undefined') {
var _style = window.getComputedStyle(this.resizable, null);
width = ~~_style.getPropertyValue('width').replace('px', '');
height = ~~_style.getPropertyValue('height').replace('px', '');
}
return { width: width, height: height };
}
}, {
key: 'style',
get: function get() {
var _this4 = this;
var size = function size(key) {
if (typeof _this4.state[key] === 'undefined' || _this4.state[key] === 'auto') return 'auto';else if (/px$/.test(_this4.state[key].toString())) return _this4.state[key].toString();else if (/%$/.test(_this4.state[key].toString())) return _this4.state[key].toString();
return _this4.state[key] + 'px';
};
return {
width: size('width'),
height: size('height')
};
}
}]);
return Resizable;
}(_react.Component);
Resizable.defaultProps = {
onResizeStart: function onResizeStart() {},
onResize: function onResize() {},
onResizeStop: function onResizeStop() {},
enable: {
top: true,
right: true,
bottom: true,
left: true,
topRight: true,
bottomRight: true,
bottomLeft: true,
topLeft: true
},
style: {},
grid: [1, 1],
lockAspectRatio: false
};
exports.default = Resizable;
},{"./resizer":190,"lodash.isequal":27,"react":188}],190:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
/* eslint-disable import/no-extraneous-dependencies */
/* eslint-disable react/no-unused-prop-types */
/* eslint-disable react/require-default-props */
/* eslint-disable react/jsx-filename-extension */
exports.default = ResizeHandler;
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var styles = {
base: {
position: 'absolute'
},
top: {
width: '100%',
height: '10px',
top: '-5px',
left: '0px',
cursor: 'row-resize'
},
right: {
width: '10px',
height: '100%',
top: '0px',
right: '-5px',
cursor: 'col-resize'
},
bottom: {
width: '100%',
height: '10px',
bottom: '-5px',
left: '0px',
cursor: 'row-resize'
},
left: {
width: '10px',
height: '100%',
top: '0px',
left: '-5px',
cursor: 'col-resize'
},
topRight: {
width: '20px',
height: '20px',
position: 'absolute',
right: '-10px',
top: '-10px',
cursor: 'ne-resize'
},
bottomRight: {
width: '20px',
height: '20px',
position: 'absolute',
right: '-10px',
bottom: '-10px',
cursor: 'se-resize'
},
bottomLeft: {
width: '20px',
height: '20px',
position: 'absolute',
left: '-10px',
bottom: '-10px',
cursor: 'sw-resize'
},
topLeft: {
width: '20px',
height: '20px',
position: 'absolute',
left: '-10px',
top: '-10px',
cursor: 'nw-resize'
}
};
function ResizeHandler(props) {
return _react2.default.createElement('div', {
className: props.className,
style: _extends({}, styles.base, styles[props.direction], props.replaceStyles || {}),
onMouseDown: function onMouseDown(e) {
return props.onResizeStart(e, props.direction);
},
onTouchStart: function onTouchStart(e) {
return props.onResizeStart(e, props.direction);
}
});
}
},{"react":188}]},{},[2]);
|
define(["dojo/_base/lang",
"dojo/_base/array",
"dojo/_base/Deferred",
"dojo/DeferredList",
"dojo/on",
"dojo/_base/sniff"],
function(lang, array, Deferred, DeferredList, on, has){
// module:
// dojox/css3/transition
//create cross platform animation/transition effects
//TODO enable opera mobile when it is hardware accelerated
//TODO enable IE when CSS3 transition is supported in IE 10
var transitionEndEventName = "transitionend";
var transitionPrefix = "t"; //by default use "t" prefix and "ransition" to make word "transition"
var translateMethodStart = "translate3d(";//Android 2.x does not support translateX in CSS Transition, we need to use translate3d in webkit browsers
var translateMethodEnd = ",0,0)";
if(has("webkit")){
transitionPrefix = "WebkitT";
transitionEndEventName = "webkitTransitionEnd";
}else if(has("mozilla")){
transitionPrefix = "MozT";
translateMethodStart = "translateX(";
translateMethodEnd = ")";
}
//TODO find a way to lock the animation and prevent animation conflict
//Use the simple object inheritance
var transition = function(/*Object?*/args){
// summary:
// This module defines the transition utilities which can be used
// to perform transition effects based on the CSS Transition standard.
// args:
// The arguments which will be mixed into this transition object.
//default config should be in animation object itself instead of its prototype
//otherwise, it might be easy for making mistake of modifying prototype
var defaultConfig = {
startState: {},
endState: {},
node: null,
duration: 250,
"in": true,
direction: 1,
autoClear: true
};
lang.mixin(this, defaultConfig);
lang.mixin(this, args);
//create the deferred object which will resolve after the animation is finished.
//We can rely on "onAfterEnd" function to notify the end of a single animation,
//but using a deferred object is easier to wait for multiple animations end.
if(!this.deferred){
this.deferred = new Deferred();
}
};
lang.extend(transition, {
play: function(){
// summary:
// Plays the transition effect defined by this transition object.
transition.groupedPlay([this]);
},
//method to apply the state of the transition
_applyState: function(state){
var style = this.node.style;
for(var property in state){
if(state.hasOwnProperty(property)){
style[property] = state[property];
}
}
},
initState: function(){
// summary:
// Method to initialize the state for a transition.
//apply the immediate style change for initial state.
this.node.style[transitionPrefix + "ransitionProperty"] = "none";
this.node.style[transitionPrefix + "ransitionDuration"] = "0ms";
this._applyState(this.startState);
},
_beforeStart: function(){
if (this.node.style.display === "none"){
this.node.style.display = "";
}
this.beforeStart();
},
_beforeClear: function(){
this.node.style[transitionPrefix + "ransitionProperty"] = null;
this.node.style[transitionPrefix + "ransitionDuration"] = null;
if(this["in"] !== true){
this.node.style.display = "none";
}
this.beforeClear();
},
_onAfterEnd: function(){
this.deferred.resolve(this.node);
if(this.node.id && transition.playing[this.node.id]===this.deferred){
delete transition.playing[this.node.id];
}
this.onAfterEnd();
},
beforeStart: function(){
// summary:
// The callback which will be called right before the start
// of the transition effect.
},
beforeClear: function(){
// summary:
// The callback which will be called right after the end
// of the transition effect and before the final state is
// cleared.
},
onAfterEnd: function(){
// summary:
// The callback which will be called right after the end
// of the transition effect and after the final state is
// cleared.
},
start: function(){
// summary:
// Method to start the transition.
this._beforeStart();
this._startTime = new Date().getTime(); // set transition start timestamp
this._cleared = false; // set clear flag to false
var self = this;
//change the transition duration
self.node.style[transitionPrefix + "ransitionProperty"] = "all";
self.node.style[transitionPrefix + "ransitionDuration"] = self.duration + "ms";
//connect to clear the transition state after the transition end.
//Since the transition is conducted asynchronously, we need to
//connect to transition end event to clear the state
on.once(self.node, transitionEndEventName, function(){
self.clear();
});
this._applyState(this.endState);
},
clear: function(){
// summary:
// Method to clear the state after a transition.
if(this._cleared) {
return;
}
this._cleared = true; // set clear flag to true
this._beforeClear();
this._removeState(this.endState);
// console.log(this.node.id + " clear.");
this._onAfterEnd();
},
//create removeState method
_removeState: function(state){
var style = this.node.style;
for(var property in state){
if(state.hasOwnProperty(property)){
style[property] = null;
}
}
}
});
//TODO add the lock mechanism for all of the transition effects
// consider using only one object for one type of transition.
transition.slide = function(node, config){
// summary:
// Method which is used to create the transition object of a slide effect.
// node:
// The node that the slide transition effect will be applied on.
// config:
// The cofig arguments which will be mixed into this transition object.
//create the return object and set the startState, endState of the return
var ret = new transition(config);
ret.node = node;
var startX = "0";
var endX = "0";
if(ret["in"]){
if(ret.direction === 1){
startX = "100%";
}else{
startX = "-100%";
}
}else{
if(ret.direction === 1){
endX = "-100%";
}else{
endX = "100%";
}
}
ret.startState[transitionPrefix + "ransform"]=translateMethodStart+startX+translateMethodEnd;
ret.endState[transitionPrefix + "ransform"]=translateMethodStart+endX+translateMethodEnd;
return ret;
};
transition.fade = function(node, config){
// summary:
// Method which is used to create the transition object of fade effect.
// node:
// The node that the fade transition effect will be applied on.
// config:
// The cofig arguments which will be mixed into this transition object.
var ret = new transition(config);
ret.node = node;
var startOpacity = "0";
var endOpacity = "0";
if(ret["in"]){
endOpacity = "1";
}else{
startOpacity = "1";
}
lang.mixin(ret, {
startState:{
"opacity": startOpacity
},
endState:{
"opacity": endOpacity
}
});
return ret;
};
transition.flip = function(node, config){
// summary:
// Method which is used to create the transition object of flip effect.
// node:
// The node that the flip transition effect will be applied on.
// config:
// The cofig arguments which will be mixed into this transition object.
var ret = new transition(config);
ret.node = node;
if(ret["in"]){
//Need to set opacity here because Android 2.2 has bug that
//scale(...) in transform does not persist status
lang.mixin(ret,{
startState:{
"opacity": "0"
},
endState:{
"opacity": "1"
}
});
ret.startState[transitionPrefix + "ransform"]="scale(0,0.8) skew(0,-30deg)";
ret.endState[transitionPrefix + "ransform"]="scale(1,1) skew(0,0)";
}else{
lang.mixin(ret,{
startState:{
"opacity": "1"
},
endState:{
"opacity": "0"
}
});
ret.startState[transitionPrefix + "ransform"]="scale(1,1) skew(0,0)";
ret.endState[transitionPrefix + "ransform"]="scale(0,0.8) skew(0,30deg)";
}
return ret;
};
var getWaitingList = function(/*Array*/ nodes){
var defs = [];
array.forEach(nodes, function(node){
//check whether the node is under other animation
if(node.id && transition.playing[node.id]){
//hook on deferred object in transition.playing
defs.push(transition.playing[node.id]);
}
});
return new DeferredList(defs);
};
transition.getWaitingList = getWaitingList;
transition.groupedPlay = function(/*Array*/args){
// summary:
// The method which groups multiple transitions and plays
// them together.
// args:
// The array of transition objects which will be played together.
var animNodes = array.filter(args, function(item){
return item.node;
});
var waitingList = getWaitingList(animNodes);
//update registry with deferred objects in animations of args.
array.forEach(args, function(item){
if(item.node.id){
transition.playing[item.node.id] = item.deferred;
}
});
//wait for all deferred object in deferred list to resolve
Deferred.when(waitingList, function(){
array.forEach(args, function(item){
//set the start state
item.initState();
});
//Assume the fps of the animation should be higher than 30 fps and
//allow the browser to use one frame's time to redraw so that
//the transition can be started
setTimeout(function(){
array.forEach(args, function(item){
item.start();
});
// check and clear node if the node not cleared.
// 1. on Android2.2/2.3, the "fade out" transitionEnd event will be lost if the soft keyboard popup, so we need to check nodes' clear status.
// 2. The "fade in" transitionEnd event will before or after "fade out" transitionEnd event and it always occurs.
// We can check fade out node status in the last "fade in" node transitionEnd event callback, if node transition timeout, we clear it.
// NOTE: the last "fade in" transitionEnd event will always fired, so we bind on this event and check other nodes.
on.once(args[args.length-1].node, transitionEndEventName, function(){
var timeout;
for(var i=0; i<args.length-1; i++){
if(args[i].deferred.fired !== 0){
timeout = new Date().getTime() - args[i]._startTime;
if(timeout >= args[i].duration){
args[i].clear();
}
}
}
});
}, 33);
});
};
transition.chainedPlay = function(/*Array*/args){
// summary:
// The method which plays multiple transitions one by one.
// args:
// The array of transition objects which will be played in a chain.
var animNodes = array.filter(args, function(item){
return item.node;
});
var waitingList = getWaitingList(animNodes);
//update registry with deferred objects in animations of args.
array.forEach(args, function(item){
if(item.node.id){
transition.playing[item.node.id] = item.deferred;
}
});
Deferred.when(waitingList, function(){
array.forEach(args, function(item){
//set the start state
item.initState();
});
//chain animations together
for (var i=1, len=args.length; i < len; i++){
args[i-1].deferred.then(lang.hitch(args[i], function(){
this.start();
}));
}
//Assume the fps of the animation should be higher than 30 fps and
//allow the browser to use one frame's time to redraw so that
//the transition can be started
setTimeout(function(){
args[0].start();
}, 33);
});
};
//TODO complete the registry mechanism for animation handling and prevent animation conflicts
transition.playing = {};
return transition;
});
|
define(['./kindOf'], function (kindOf) {
var _win = this;
/**
* Convert array-like object into array
*/
/**
* Description
* @method toArray
* @param {} val
* @return ret
*/
function toArray(val){
var ret = [],
kind = kindOf(val),
n;
if (val != null) {
if ( val.length == null || kind === 'String' || kind === 'Function' || kind === 'RegExp' || val === _win ) {
//string, regexp, function have .length but user probably just want
//to wrap value into an array..
ret[ret.length] = val;
} else {
//window returns true on isObject in IE7 and may have length
//property. `typeof NodeList` returns `function` on Safari so
//we can't use it (#58)
n = val.length;
while (n--) {
ret[n] = val[n];
}
}
}
return ret;
}
return toArray;
});
|
var dir_5a37fa460d8d8ed46083971603ae2788 =
[
[ "modules", "dir_418f0b3bebd041d70149628f27b94e66.html", "dir_418f0b3bebd041d70149628f27b94e66" ]
]; |
import request from '../functions/request';
/* istanbul ignore next */
export default async (bot, uri) => {
const { get, post, put, del } = request(bot, uri);
bot.listen(/^teamline manage add (\w+) (.*)/i, async message => {
const [type, name] = message.match;
const t = type.toLowerCase();
const item = await post(`${t}`, { name });
message.reply(`Created ${t} #${item.id} - ${item.name}`);
}, {
permissions: ['admin', 'human-resource'],
});
bot.listen(/^teamline manage done (\w+) (?:#)?(\d+)/i, async message => {
const [type, id] = message.match;
const t = type.toLowerCase();
const item = await put(`${t}/${id}`, {
done: true,
});
message.reply(`Marked ${type} #${item.id} as done.`);
}, {
permissions: ['admin', 'human-resource'],
});
bot.listen(/^teamline manage undone (\w+) (?:#)?(\d+)/i, async message => {
const [type, id] = message.match;
const t = type.toLowerCase();
const item = await put(`${t}/${id}`, {
done: false,
});
message.reply(`Marked ${type} #${item.id} as undone.`);
}, {
permissions: ['admin', 'human-resource'],
});
bot.listen(/^teamline manage delete (\w+) (?:#)?(\d+)/i, async message => {
const [type, id] = message.match;
const t = type.toLowerCase();
const item = await del(`${t}/${id}`);
message.reply(`Deleted ${type} #${item.id}.`);
}, {
permissions: ['admin', 'human-resource'],
});
bot.listen(/^teamline manage connect (\w+) (?:#)?(\d+) (?:with|to|->)?\s?(\w+) (?:#)?(\d+)/i, async message => { // eslint-disable-line
const [st, sourceId, tt, targetId] = message.match;
const sourceType = st.toLowerCase();
const targetType = tt.toLowerCase();
await get(`associate/${sourceType}/${sourceId}/${targetType}/${targetId}`);
message.reply(`Connected ${sourceType} #${sourceId} with ${targetType} #${targetId}`);
}, {
permissions: ['admin', 'human-resource'],
});
bot.command('^teamline refresh', async message => {
get('?refresh');
message.reply(bot.t('teamline.actions.refresh'));
});
};
|
var express = require('express');
var router = express.Router();
router.post('/', function(req, res, next) {
var dm = req.app.locals.dataManager;
var newRecord = req.body;
if (dm.checkDataSheme(newRecord)) {
dm.addRecord(newRecord, function(success) {
if (success) {
res.render("added", {title: "Record added"});
} else {
next(new Error("Record failed to be added and saved"));
}
});
} else {
next(new Error("Record data did not match the database schema"));
}
});
router.get("/records", function(req, res) {
var records = req.app.locals.dataManager.getRecords();
res.json(records);
});
module.exports = router;
|
'use strict';
describe('Service: UserMedia', function () {
// load the service's module
beforeEach(module('pulsarClientApp'));
// instantiate service
var UserMedia;
beforeEach(inject(function (_UserMedia_) {
UserMedia = _UserMedia_;
}));
it('should do something', function () {
expect(!!UserMedia).toBe(true);
});
});
|
var UU5 = UU5 || {};
UU5.DocKit = UU5.DocKit || {};
UU5.DocKit.data = UU5.DocKit.data || {};
UU5.DocKit.data.uu5_bricks_date_time = {
tagName: "UU5.Bricks.DateTime",
sourceFile: "../../data/source/uu5-bricks-date-time.js",
cssFile: "../../data/source/uu5-bricks-date-time.less",
descLSI: {
en: '',
cs: `<UU5.Bricks.Blockquote.bgSuccess>Komponenta <UU5.Bricks.Code content='UU5.Bricks.DateTime'/> zobrazuje datum a
čas podle formátování prohlížeče nebo formátu zadaného uživatelem. Formát lze zadávat:
<UU5.Bricks.Ul>
<UU5.Bricks.Li>do objektu <UU5.Bricks.Code content='UU5.Environment.dateTimeFormat'/>, kde klíč je
<UU5.Bricks.Link content="kód jazyka" target="_blank" href="https://msdn.microsoft.com/en-us/library/ee825488(v=cs.20).aspx" />
(malými písmeny) a hodnota je string s formátem.</UU5.Bricks.Li>
<UU5.Bricks.Li>do vlastnosti <UU5.Bricks.Code content='format'/></UU5.Bricks.Li>
</UU5.Bricks.Ul>
Komponentě se dá nastavit časová zóna pomocí vlastnosti <UU5.Bricks.Code content='timeZone'/>.
Metody <UU5.Bricks.Code content='setGlobalDateTimeCountry'/> a <UU5.Bricks.Code content='setGlobalDateTimeFormat'/>
v <UU5.DocKit.Bricks.Link tagName='UU5.Common.BaseMixin'/> změní formát všem komponentám <UU5.Bricks.Code content='UU5.Bricks.DateTime'/>
ve vizuálním případu užití. Metoda <UU5.Bricks.Code content='setGlobalDateTimeZone'/> změní časovou zónu všem
<UU5.Bricks.Code content='UU5.Bricks.DateTime'/>. Pokud je potřeba změnit jak časovou zónu, tak formát, použije se metoda
<UU5.Bricks.Code content='setGlobalDateTimeOptions'/>.
</UU5.Bricks.Blockquote.bgSuccess>`
},
demoExample: {
src: "../../data/examples/exampleUU5BricksDateTime02.html",
descLSI: {
cs: `Příklad ukazuje aktuální datum a čas ve třech městech za použití vlastnosti <UU5.Bricks.Code content='timeZone'/>.
Při výběru země (reprezentované tlačítky s vlajkami) se změní formát datumů podle nastavení prohlížeče v dané
jazykové lokaci.`
}
},
mixins: [
'<UU5.DocKit.Bricks.Link tagName="UU5.Common.BaseMixin" />',
'<UU5.DocKit.Bricks.Link tagName="UU5.Common.ElementaryMixin" />'
],
mixinsDescLSI: null,
staticsDescLSI: null,
props: [
{
"name": "value",
"descLSI": {
en: "",
cs: `<UU5.Bricks.Code content='(object)'/> - datum vytvořené pomocí <UU5.Bricks.Code content='new Date()'/><br/>
Výchozí hodnota je <UU5.Bricks.Code content="new Date()" />.<br/><br/>
Např. <UU5.Bricks.Code content='value={new Date(2017, 1, 19, 23, 10, 19, 987)}'/>`
}
},
{
"name": "format",
"descLSI": {
en: "",
cs: `<UU5.Bricks.Code content='(string)'/> - formát, ve kterém se má datum a čas zobrazit, lze zadat pomocí
následujících značek:<br />
<UU5.Bricks.Ul>
<UU5.Bricks.Li><UU5.Bricks.Code content='d'/> - pořadí dne v měsíci 1-31</UU5.Bricks.Li>
<UU5.Bricks.Li><UU5.Bricks.Code content='dd'/> - pořadí dne v měsíci 01-31</UU5.Bricks.Li>
<UU5.Bricks.Li><UU5.Bricks.Code content='m'/> - číslo měsíce 1-12</UU5.Bricks.Li>
<UU5.Bricks.Li><UU5.Bricks.Code content='mm'/> - číslo měsíce 01-12</UU5.Bricks.Li>
<UU5.Bricks.Li><UU5.Bricks.Code content='y'/> - poslední dvě číslice roku (např. 17)</UU5.Bricks.Li>
<UU5.Bricks.Li><UU5.Bricks.Code content='Y'/> - rok</UU5.Bricks.Li>
<UU5.Bricks.Li><UU5.Bricks.Code content='h'/> - hodiny 1-12</UU5.Bricks.Li>
<UU5.Bricks.Li><UU5.Bricks.Code content='hh'/> - hodiny 01-12</UU5.Bricks.Li>
<UU5.Bricks.Li><UU5.Bricks.Code content='H'/> - hodiny 0-23</UU5.Bricks.Li>
<UU5.Bricks.Li><UU5.Bricks.Code content='HH'/> - hodiny 00-23</UU5.Bricks.Li>
<UU5.Bricks.Li><UU5.Bricks.Code content='M'/> - minuty 0-59</UU5.Bricks.Li>
<UU5.Bricks.Li><UU5.Bricks.Code content='MM'/> - minuty 00-59</UU5.Bricks.Li>
<UU5.Bricks.Li><UU5.Bricks.Code content='S'/> - sekundy 0-59</UU5.Bricks.Li>
<UU5.Bricks.Li><UU5.Bricks.Code content='SS'/> - sekundy 00-59</UU5.Bricks.Li>
<UU5.Bricks.Li><UU5.Bricks.Code content='s'/> - milisekundy 0-999</UU5.Bricks.Li>
<UU5.Bricks.Li><UU5.Bricks.Code content='ss'/> - milisekundy 000-999</UU5.Bricks.Li>
<UU5.Bricks.Li><UU5.Bricks.Code content='t'/> - a.m. pro čas před polednem, p.m. pro čas po poledni</UU5.Bricks.Li>
<UU5.Bricks.Li><UU5.Bricks.Code content='T'/> - AM pro čas před polednem, PM pro čas po poledni</UU5.Bricks.Li>
<UU5.Bricks.Li><UU5.Bricks.Code content='w'/> - pořadí týdne v roce 0-52</UU5.Bricks.Li>
<UU5.Bricks.Li><UU5.Bricks.Code content='ww'/> - pořadí týdne v roce 00-52</UU5.Bricks.Li>
<UU5.Bricks.Li><UU5.Bricks.Code content='q'/> - čtvrtletí 1-4</UU5.Bricks.Li>
<UU5.Bricks.Li><UU5.Bricks.Code content='Z'/> - časová zóna -12:00 - +12:00</UU5.Bricks.Li>
</UU5.Bricks.Ul>
Výchozí hodnota je <UU5.Bricks.Code content="null" /> a formát se bere podle nastavení prohlížeče.<br/><br/>
Např. <UU5.Bricks.Code content="format='d. m. Y HH:MM:SS Z (w/52) q/4'"/>`
}
},
{
"name": "country",
"descLSI": {
en: "",
cs: `<UU5.Bricks.Code content='(string)'/> - <UU5.Bricks.Link content="kód jazyka země" target="_blank" href="https://msdn.microsoft.com/en-us/library/ee825488(v=cs.20).aspx" /> je potřeba zadávat malými písmeny.<br/>
Do objektu <UU5.Bricks.Code content='UU5.Environment.dateTimeFormat'/> lze přidávat vlastní formátování, kdy se za klíč
s <UU5.Bricks.Link content="kódem jazyka země" target="_blank" href="https://msdn.microsoft.com/en-us/library/ee825488(v=cs.20).aspx" />
vloží string s formátem. Např. <UU5.Bricks.Code content="UU5.Environment.dateTimeFormat['en-gb'] = 'd/m/Y HH:MM:SS:ss'"/>.
Výchozí hodnota je <UU5.Bricks.Code content="null" /> a formát se bere podle nastavení prohlížeče.<br/><br/>
Např. <UU5.Bricks.Code content="country='en-us'"/>`
}
},
{
"name": "timeZone",
"descLSI": {
en: "",
cs: `<UU5.Bricks.Code content='(number)'/> - časová zóna, do které se má čas převést<br />
Výchozí hodnota je <UU5.Bricks.Code content='null'/> a časová zóna se bere z proměnné
<UU5.Bricks.Code content='UU5.Environment.dateTimeZone'/>, kde je jako výchozí nastavená časová zóna prohlížeče. Tuto
globální defaultní hodnotu si může aplikace přenastavit.<br/>
Jsou povolené hodnoty od -12.0 do 12.0.<br/><br/>
Např. <UU5.Bricks.Code content='timeZone={-3.5}'/>`
}
},
{
"name": "onChange",
"descLSI": {
en: "",
cs: `<UU5.Bricks.Code content='(func)'/> - metoda se zavolá při globální změně formátu, country nebo timeZone.
Tato metoda může být vyvolána pouze při zavolání metod <UU5.Bricks.Code content='setGlobalDateTimeCountry'/>,
<UU5.Bricks.Code content='setGlobalDateTimeFormat'/>, <UU5.Bricks.Code content='setGlobalDateTimeZone'/> a
<UU5.Bricks.Code content='setGlobalDateTimeOptions'/> z <UU5.DocKit.Bricks.Link tagName='UU5.Common.BaseMixin'/>.<br/>
Výchozí hodnota je <UU5.Bricks.Code content='null'/>.<br/>
Do metody jsou předány následující parametry:
<UU5.Bricks.Ul>
<UU5.Bricks.Li><UU5.Bricks.Code content='component'/> - instance komponenty <UU5.Bricks.Code content='UU5.Bricks.DateTime'/></UU5.Bricks.Li>
<UU5.Bricks.Li>
<UU5.Bricks.Code content='opt'/> - objekt s aktualizovanými hodnotami
<UU5.Bricks.Ul>
<UU5.Bricks.Li><UU5.Bricks.Code content='format'/> - string s formátem</UU5.Bricks.Li>
<UU5.Bricks.Li><UU5.Bricks.Code content='country'/> - <UU5.Bricks.Link content="kód jazyka země" target="_blank" href="https://msdn.microsoft.com/en-us/library/ee825488(v=cs.20).aspx" /></UU5.Bricks.Li>
<UU5.Bricks.Li><UU5.Bricks.Code content='timeZone'/> - číslo časové zóny</UU5.Bricks.Li>
</UU5.Bricks.Ul>
</UU5.Bricks.Li>
<UU5.Bricks.Li><UU5.Bricks.Code content='event'/> - standardní JavaScript událost</UU5.Bricks.Li>
</UU5.Bricks.Ul>
<br/><br/>
Např. <UU5.Bricks.Code content='onChange={(component, opt, event) => {...; component.setOptions(opt)}}'/>`
}
}
],
propsDescLSI: null,
interface: [
{
"name": "getFormat",
"descLSI": {
en: "",
cs: `<UU5.Bricks.Code>[string] component.getFormat()</UU5.Bricks.Code><br/>
Metoda vrátí aktuální formát komponenty.`
}
},
{
"name": "setFormat",
"descLSI": {
en: "",
cs: `<UU5.Bricks.Code>[component] component.setFormat(format, setStateCallback)</UU5.Bricks.Code><br/>
Metoda nastaví nový formát, který má stejné parametry jako má vlastnost <UU5.Bricks.Code content="format" />.`
}
},
{
"name": "getCountry",
"descLSI": {
en: "",
cs: `<UU5.Bricks.Code>[string] component.getCountry()</UU5.Bricks.Code><br/>
Metoda vrátí aktuální <UU5.Bricks.Link content="kód jazyka země" target="_blank" href="https://msdn.microsoft.com/en-us/library/ee825488(v=cs.20).aspx" />.`
}
},
{
"name": "setCountry",
"descLSI": {
en: "",
cs: `<UU5.Bricks.Code>[component] component.setFormat(country, setStateCallback)</UU5.Bricks.Code><br/>
Metoda nastaví <UU5.Bricks.Link content="kód jazyka země" target="_blank" href="https://msdn.microsoft.com/en-us/library/ee825488(v=cs.20).aspx" />.`
}
},
{
"name": "getTimeZone",
"descLSI": {
en: "",
cs: `<UU5.Bricks.Code>[number] component.getTimeZone()</UU5.Bricks.Code><br/>
Metoda vrátí časovou zónu.`
}
},
{
"name": "setTimeZone",
"descLSI": {
en: "",
cs: `<UU5.Bricks.Code>[component] component.setTimeZone(timeZone, setStateCallback)</UU5.Bricks.Code><br/>
Metoda nastaví novou časovou zónu. Povolené hodnoty jsou od -12.0 do 12.0.`
}
},
{
"name": "setOptions",
"descLSI": {
en: "",
cs: `<UU5.Bricks.Code>[component] component.setOptions(opt, setStateCallback)</UU5.Bricks.Code><br/>
Metoda může nastavit <UU5.Bricks.Code content="format" />, <UU5.Bricks.Code content="country" /> a
<UU5.Bricks.Code content="timeZone" /> naráz pomocí objektu <UU5.Bricks.Code content="opt" />. Pro jednotlivé
hodnoty platí stejná pravidla jako pro vlasntosti <UU5.Bricks.Code content="format" />, <UU5.Bricks.Code content="country" /> a
<UU5.Bricks.Code content="timeZone" />.`
}
},
],
interfaceDescLSI: null,
examplesIntroLSI: null,
examples: [
{
src: '../../data/examples/exampleUU5BricksDateTime01.html',
descLSI: {
en: `ToDo!!!`,
cs: `Příklad představuje výchozí zobrazení komponenty <UU5.Bricks.Code content='UU5.Bricks.DateTime'/>,
která zobrazuje aktuální datum a čas podle nastavení prohlížeče.`
}
},
{
src: '../../data/examples/exampleUU5BricksDateTime02.html',
descLSI: {
en: `ToDo!!!`,
cs: `Příklad ukazuje aktuální datum a čas ve třech městech za použití vlastnosti <UU5.Bricks.Code content='timeZone'/>.
Při výběru země (reprezentované tlačítky s vlajkami) se změní formát datumů podle nastavení prohlížeče v dané
jazykové lokaci.`
}
},
{
src: '../../data/examples/exampleUU5BricksDateTime03.html',
descLSI: {
en: `ToDo!!!`,
cs: `Příklad ukazuje použití jednotlivých vlastností a většinu značek pro formátování.`
}
},
{
src: '../../data/examples/exampleUU5BricksDateTime04.html',
descLSI: {
en: `ToDo!!!`,
cs: `Příklad ukazuje globální změnu formátu a časové zóny. Metody pro globální nastavení <UU5.Bricks.Code content='UU5.Bricks.DateTime'/>
jsou v <UU5.DocKit.Bricks.Link tagName='UU5.Common.BaseMixin'/>.`
}
}
],
exampleConclusionLSI: null
}; |
describe('hotttlist section', function () {
beforeEach(module('myApp.hotttlist'));
describe('Hottt Controller', function () {
var $controller;
beforeEach(inject(function (_$controller_) {
// The injector unwraps the underscores (_) from around the parameter names when matching
$controller = _$controller_;
}));
it('should provide simple access to its data', function () {
var scope = {};
var hotttCtrl = $controller('HotttCtrl', {$scope: scope});
expect(hotttCtrl).toBeDefined();
expect(hotttCtrl.listTitle).toBeDefined();
expect(hotttCtrl.artists).toBeDefined();
expect(hotttCtrl.listTitle).toBe('Echonest\'s hotttest artists');
});
});
});
|
$.RaCalendar = {
version: '0.0.1',
elements: {
root: null,
header: null,
resources: null,
content: null
},
config: {
date: {
begin_time: "09:00:00",
duration: 3600,
round: '15m'
},
events: {
id: "id",
resource_id: "resource_id",
title: "name",
begin: "begin",
end: "end",
duration: "",
url: "url"
},
resources: {
id: "",
title: "name"
}
},
events: [],
resorces: [],
default_color: {
color: '#000000',
background: '#eeeeee'
}
};
|
/* global console */
var _ = require('lodash');
var tape = require('tape');
var test = tape;
//qunit has equal/strictEqual, we just have equal
tape.Test.prototype.strictEqual = function () {
this.equal.apply(this, arguments);
};
tape.skip = function (name) {
console.log('SKIPPING', name);
};
//stub qunit module
function module(moduleName, opts) {
test = function (testName, cb) {
if (opts.setup) opts.setup();
tape.call(tape, moduleName + ' - ' + testName, cb);
};
test.only = function (testName, cb) {
if (opts.setup) opts.setup();
tape.only.call(tape, moduleName + ' - ' + testName, cb);
};
test.skip = tape.skip;
}
var AmpersandModel = require('../ampersand-model');
//Let's fake some backbone things to minimize test changes
var env = {};
var Backbone = {
Model: AmpersandModel.extend({
extraProperties: 'allow',
sync: function (method, model, options) {
env.syncArgs = {
method: method,
model: model,
options: options
};
}
}),
Collection: {
extend: function (o) {
var Coll = function () {
var k;
for (k in o) {
this[k] = o[k];
}
};
Coll.prototype.add = function (m) {
m.collection = this;
};
return Coll;
}
}
};
(function () {
var proxy = Backbone.Model.extend();
var klass = Backbone.Collection.extend({
url : function () { return '/collection'; }
});
var doc, collection;
module("Backbone.Model", {
setup: function () {
doc = new proxy({
id : '1-the-tempest',
title : "The Tempest",
author : "Bill Shakespeare",
textLength : 123
});
collection = new klass();
collection.add(doc);
}
});
test("initialize", function (t) {
t.plan(3);
var Model = Backbone.Model.extend({
initialize: function () {
this.one = 1;
t.equal(this.collection, collection);
}
});
var model = new Model({}, {collection: collection});
t.equal(model.one, 1);
t.equal(model.collection, collection);
});
test("initialize with attributes and options", function (t) {
t.plan(1);
var Model = Backbone.Model.extend({
initialize: function (attributes, options) {
this.one = options.one;
}
});
var model = new Model({}, {one: 1});
t.equal(model.one, 1);
});
test("initialize with parsed attributes", function (t) {
t.plan(1);
var Model = Backbone.Model.extend({
parse: function (attrs) {
attrs.value += 1;
return attrs;
}
});
var model = new Model({value: 1}, {parse: true});
t.equal(model.get('value'), 2);
});
test("initialize with defaults", function (t) {
t.plan(2);
var Model = Backbone.Model.extend({
props: {
first_name: ['string', true, 'Unknown'],
last_name: ['string', true, 'Unknown']
}
});
var model = new Model({'first_name': 'John'});
t.equal(model.get('first_name'), 'John');
t.equal(model.get('last_name'), 'Unknown');
});
test("parse can return null", function (t) {
t.plan(1);
var Model = Backbone.Model.extend({
parse: function (attrs) {
attrs.value += 1;
return null;
}
});
var model = new Model({value: 1}, {parse: true});
t.equal(JSON.stringify(model.toJSON()), "{}");
});
test("url", function (t) {
t.plan(3);
doc.urlRoot = null;
t.equal(doc.url(), '/collection/1-the-tempest');
doc.collection.url = '/collection/';
t.equal(doc.url(), '/collection/1-the-tempest');
doc.collection = null;
t.throws(function () { doc.url(); });
doc.collection = collection;
});
test("url when using urlRoot, and uri encoding", function (t) {
t.plan(2);
var Model = Backbone.Model.extend({
urlRoot: '/collection'
});
var model = new Model();
t.equal(model.url(), '/collection');
model.set({id: '+1+'});
t.equal(model.url(), '/collection/%2B1%2B');
});
test("url when using urlRoot as a function to determine urlRoot at runtime", function (t) {
t.plan(2);
var Model = Backbone.Model.extend({
urlRoot: function () {
return '/nested/' + this.get('parent_id') + '/collection';
}
});
var model = new Model({parent_id: 1});
t.equal(model.url(), '/nested/1/collection');
model.set({id: 2});
t.equal(model.url(), '/nested/1/collection/2');
});
test.skip("underscore methods", function (t) {
t.plan(5);
var model = new Backbone.Model({ 'foo': 'a', 'bar': 'b', 'baz': 'c' });
var model2 = model.clone();
t.deepEqual(model.keys(), ['foo', 'bar', 'baz']);
t.deepEqual(model.values(), ['a', 'b', 'c']);
t.deepEqual(model.invert(), { 'a': 'foo', 'b': 'bar', 'c': 'baz' });
t.deepEqual(model.pick('foo', 'baz'), {'foo': 'a', 'baz': 'c'});
t.deepEqual(model.omit('foo', 'bar'), {'baz': 'c'});
});
test.skip("chain", function (t) {
t.plan(1);
var model = new Backbone.Model({ a: 0, b: 1, c: 2 });
t.deepEqual(model.chain().pick("a", "b", "c").values().compact().value(), [1, 2]);
});
test.skip("clone", function (t) {
t.plan(10);
var a = new Backbone.Model({ 'foo': 1, 'bar': 2, 'baz': 3});
var b = a.clone();
t.equal(a.get('foo'), 1);
t.equal(a.get('bar'), 2);
t.equal(a.get('baz'), 3);
t.equal(b.get('foo'), a.get('foo'), "Foo should be the same on the clone.");
t.equal(b.get('bar'), a.get('bar'), "Bar should be the same on the clone.");
t.equal(b.get('baz'), a.get('baz'), "Baz should be the same on the clone.");
a.set({foo : 100});
t.equal(a.get('foo'), 100);
t.equal(b.get('foo'), 1, "Changing a parent attribute does not change the clone.");
var foo = new Backbone.Model({p: 1});
var bar = new Backbone.Model({p: 2});
bar.set(foo.clone().attributes, {unset: true});
t.equal(foo.get('p'), 1);
t.equal(bar.get('p'), undefined);
});
test("isNew", function (t) {
t.plan(6);
var a = new Backbone.Model({ 'foo': 1, 'bar': 2, 'baz': 3});
t.ok(a.isNew(), "it should be new");
a = new Backbone.Model({ 'foo': 1, 'bar': 2, 'baz': 3, 'id': -5 });
t.ok(!a.isNew(), "any defined ID is legal, negative or positive");
a = new Backbone.Model({ 'foo': 1, 'bar': 2, 'baz': 3, 'id': 0 });
t.ok(!a.isNew(), "any defined ID is legal, including zero");
t.ok(new Backbone.Model({ }).isNew(), "is true when there is no id");
t.ok(!new Backbone.Model({ 'id': 2 }).isNew(), "is false for a positive integer");
t.ok(!new Backbone.Model({ 'id': -5 }).isNew(), "is false for a negative integer");
});
test("get", function (t) {
t.plan(2);
t.equal(doc.get('title'), 'The Tempest');
t.equal(doc.get('author'), 'Bill Shakespeare');
});
test("escape", function (t) {
t.plan(5);
t.equal(doc.escape('title'), 'The Tempest');
doc.set({audience: 'Bill & Bob'});
t.equal(doc.escape('audience'), 'Bill & Bob');
doc.set({audience: 'Tim > Joan'});
t.equal(doc.escape('audience'), 'Tim > Joan');
doc.set({audience: 10101});
t.equal(doc.escape('audience'), '10101');
doc.unset('audience');
t.equal(doc.escape('audience'), '');
});
test.skip("has", function (t) {
t.plan(10);
var model = new Backbone.Model();
t.strictEqual(model.has('name'), false);
model.set({
'0': 0,
'1': 1,
'true': true,
'false': false,
'empty': '',
'name': 'name',
'null': null,
'undefined': undefined
});
t.strictEqual(model.has('0'), true);
t.strictEqual(model.has('1'), true);
t.strictEqual(model.has('true'), true);
t.strictEqual(model.has('false'), true);
t.strictEqual(model.has('empty'), true);
t.strictEqual(model.has('name'), true);
model.unset('name');
t.strictEqual(model.has('name'), false);
t.strictEqual(model.has('null'), false);
t.strictEqual(model.has('undefined'), false);
});
test("set and unset", function (t) {
t.plan(8);
var a = new Backbone.Model({id: 'id', foo: 1, bar: 2, baz: 3});
var changeCount = 0;
a.on("change:foo", function () { changeCount += 1; });
a.set({'foo': 2});
t.ok(a.get('foo') == 2, "Foo should have changed.");
t.ok(changeCount == 1, "Change count should have incremented.");
a.set({'foo': 2}); // set with value that is not new shouldn't fire change event
t.ok(a.get('foo') == 2, "Foo should NOT have changed, still 2");
t.ok(changeCount == 1, "Change count should NOT have incremented.");
a.validate = function (attrs) {
t.equal(attrs.foo, void 0, "validate:true passed while unsetting");
};
a.unset('foo', {validate: true});
t.equal(a.get('foo'), void 0, "Foo should have changed");
delete a.validate;
t.ok(changeCount == 2, "Change count should have incremented for unset.");
a.unset('id');
t.equal(a.id, undefined, "Unsetting the id should remove the id property.");
});
test("#2030 - set with failed validate, followed by another set triggers change", function (t) {
t.plan(1);
var attr = 0, main = 0, error = 0;
var Model = Backbone.Model.extend({
validate: function (attr) {
if (attr.x > 1) {
error++;
return "this is an error";
}
}
});
var model = new Model({x: 0});
model.on('change:x', function () { attr++; });
model.on('change', function () { main++; });
model.set({x: 2}, {validate: true});
model.set({x: 1}, {validate: true});
t.deepEqual([attr, main, error], [1, 1, 1]);
});
test("set triggers changes in the correct order", function (t) {
t.plan(1);
var value = null;
var model = new Backbone.Model();
model.on('last', function () { value = 'last'; });
model.on('first', function () { value = 'first'; });
model.trigger('first');
model.trigger('last');
t.equal(value, 'last');
});
test("set falsy values in the correct order", function (t) {
t.plan(2);
var model = new Backbone.Model({result: 'result'});
model.on('change', function () {
t.equal(model._changed.result, void 0);
t.equal(model.previous('result'), false);
});
model.set({result: void 0}, {silent: true});
model.set({result: null}, {silent: true});
model.set({result: false}, {silent: true});
model.set({result: void 0});
});
test.skip("nested set triggers with the correct options", function (t) {
t.plan(3);
var model = new Backbone.Model();
var o1 = {};
var o2 = {};
var o3 = {};
model.on('change', function (__, options) {
switch (model.get('a')) {
case 1:
t.equal(options, o1);
return model.set('a', 2, o2);
case 2:
t.equal(options, o2);
return model.set('a', 3, o3);
case 3:
t.equal(options, o3);
}
});
model.set('a', 1, o1);
});
test("multiple unsets", function (t) {
t.plan(1);
var i = 0;
var counter = function () { i++; };
var model = new Backbone.Model({a: 1});
model.on("change:a", counter);
model.set({a: 2});
model.unset('a');
model.unset('a');
t.equal(i, 2, 'Unset does not fire an event for missing attributes.');
});
test("unset and changedAttributes", function (t) {
t.plan(1);
var model = new Backbone.Model({a: 1});
model.on('change', function () {
t.ok('a' in model.changedAttributes(), 'changedAttributes should contain unset properties');
});
model.unset('a');
});
test.skip("using a non-default id attribute.", function (t) {
t.plan(5);
var MongoModel = Backbone.Model.extend({idAttribute : '_id'});
var model = new MongoModel({id: 'eye-dee', _id: 25, title: 'Model'});
t.equal(model.get('id'), 'eye-dee');
t.equal(model.id, 25);
t.equal(model.isNew(), false);
model.unset('_id');
t.equal(model.id, undefined);
t.equal(model.isNew(), true);
});
test("set an empty string", function (t) {
t.plan(1);
var model = new Backbone.Model({name : "Model"});
model.set({name : ''});
t.equal(model.get('name'), '');
});
test("setting an object", function (t) {
t.plan(1);
var model = new Backbone.Model({
custom: { foo: 1 }
});
model.on('change', function () {
t.ok(1);
});
model.set({
custom: { foo: 1 } // no change should be fired
});
model.set({
custom: { foo: 2 } // change event should be fired
});
});
test.skip("clear", function (t) {
t.plan(3);
var changed;
var model = new Backbone.Model({id: 1, name : "Model"});
model.on("change:name", function () { changed = true; });
model.on("change", function () {
var changedAttrs = model.changedAttributes();
t.ok('name' in changedAttrs);
});
model.clear();
t.equal(changed, true);
t.equal(model.get('name'), undefined);
});
test.skip("defaults", function (t) {
t.plan(4);
var Defaulted = Backbone.Model.extend({
props: {
"one": ['number', true, 1],
"two": ['number', true, 2]
}
});
var model = new Defaulted({two: undefined});
t.equal(model.get('one'), 1);
t.equal(model.get('two'), 2);
Defaulted = Backbone.Model.extend({
props: {
"one": ['number', true, 3],
"two": ['number', true, 4]
}
});
model = new Defaulted({two: undefined});
t.equal(model.get('one'), 3);
t.equal(model.get('two'), 4);
});
test("change, hasChanged, changedAttributes, previous, previousAttributes", function (t) {
t.plan(9);
var model = new Backbone.Model({name: "Tim", age: 10});
t.deepEqual(model.changedAttributes(), false);
model.on('change', function () {
t.ok(model.hasChanged('name'), 'name changed');
t.ok(!model.hasChanged('age'), 'age did not');
t.ok(_.isEqual(model.changedAttributes(), {name : 'Rob'}), 'changedAttributes returns the changed attrs');
t.equal(model.previous('name'), 'Tim');
t.ok(_.isEqual(model.previousAttributes(), {name : "Tim", age : 10}), 'previousAttributes is correct');
});
t.equal(model.hasChanged(), false);
t.equal(model.hasChanged(undefined), false);
model.set({name : 'Rob'});
t.equal(model.get('name'), 'Rob');
});
test("changedAttributes", function (t) {
t.plan(3);
var model = new Backbone.Model({a: 'a', b: 'b'});
t.deepEqual(model.changedAttributes(), false);
t.equal(model.changedAttributes({a: 'a'}), false);
t.equal(model.changedAttributes({a: 'b'}).a, 'b');
});
test("change with options", function (t) {
t.plan(2);
var value;
var model = new Backbone.Model({name: 'Rob'});
model.on('change', function (model, options) {
value = options.prefix + model.get('name');
});
model.set({name: 'Bob'}, {prefix: 'Mr. '});
t.equal(value, 'Mr. Bob');
model.set({name: 'Sue'}, {prefix: 'Ms. '});
t.equal(value, 'Ms. Sue');
});
test("change after initialize", function (t) {
t.plan(1);
var changed = 0;
var attrs = {id: 1, label: 'c'};
var obj = new Backbone.Model(attrs);
obj.on('change', function () { changed += 1; });
obj.set(attrs);
t.equal(changed, 0);
});
test("save within change event", function (t) {
t.plan(1);
//var env = this;
var model = new Backbone.Model({firstName : "Taylor", lastName: "Swift"});
model.url = '/test';
model.on('change', function () {
model.save();
t.ok(_.isEqual(env.syncArgs.model, model));
});
model.set({lastName: 'Hicks'});
});
test("validate after save", function (t) {
t.plan(2);
var lastError, model = new Backbone.Model();
model.validate = function (attrs) {
if (attrs.admin) return "Can't change admin status.";
};
model.sync = function (method, model, options) {
options.success.call(this, {admin: true});
};
model.on('invalid', function (model, error) {
lastError = error;
});
model.save(null);
t.equal(lastError, "Can't change admin status.");
t.equal(model.validationError, "Can't change admin status.");
});
test("save", function (t) {
t.plan(2);
doc.save({title : "Henry V"});
t.equal(env.syncArgs.method, 'update');
t.ok(_.isEqual(env.syncArgs.model, doc));
});
test("save, fetch, destroy triggers error event, calls error handler, both with proper args, when an error occurs", function (t) {
t.plan(6);
var model = new Backbone.Model();
model.on('error', function (model, resp) {
t.equal(resp, 'xhrError');
});
model.sync = function (method, model, options) {
options.error('xhrError');
};
model.save( {data: 2, id: 1}, {error: function (model, resp) { t.equal(resp, 'xhrError'); } });
model.fetch( {error: function (model, resp) { t.equal(resp, 'xhrError'); } });
model.destroy( {error: function (model, resp) { t.equal(resp, 'xhrError'); } });
});
test("save with PATCH", function (t) {
t.plan(6);
var Model = Backbone.Model.extend();
var model = new Model({parent_id: 1});
model.clear().set({id: 1, a: 1, b: 2, c: 3, d: 4});
model.save();
t.equal(env.syncArgs.method, 'update');
t.equal(env.syncArgs.options.attrs, undefined);
model.save({b: 2, d: 4}, {patch: true});
t.equal(env.syncArgs.method, 'patch');
t.equal(_.size(env.syncArgs.options.attrs), 2);
t.equal(env.syncArgs.options.attrs.d, 4);
t.equal(env.syncArgs.options.attrs.a, undefined);
});
test.skip("save in positional style", function (t) {
t.plan(1);
var model = new Backbone.Model();
model.sync = function (method, model, options) {
options.success();
};
model.save('title', 'Twelfth Night');
t.equal(model.get('title'), 'Twelfth Night');
});
test.skip("save with non-object success response", function (t) {
t.plan(2);
var model = new Backbone.Model();
model.sync = function (method, model, options) {
options.success('', options);
options.success(null, options);
};
model.save({testing: 'empty'}, {
success: function (model) {
t.deepEqual(model.attributes, {testing: 'empty'});
}
});
});
test.skip("fetch", function (t) {
t.plan(2);
doc.fetch();
t.equal(this.syncArgs.method, 'read');
t.ok(_.isEqual(this.syncArgs.model, doc));
});
test.skip("destroy", function (t) {
t.plan(3);
doc.destroy();
t.equal(this.syncArgs.method, 'delete');
t.ok(_.isEqual(this.syncArgs.model, doc));
var newModel = new Backbone.Model();
t.equal(newModel.destroy(), false);
});
test("non-persisted destroy", function (t) {
t.plan(1);
var a = new Backbone.Model({ 'foo': 1, 'bar': 2, 'baz': 3});
a.sync = function () { throw "should not be called"; };
a.destroy();
t.ok(true, "non-persisted model should not call sync");
});
test("validate", function (t) {
t.plan(7);
var lastError;
var model = new Backbone.Model();
model.validate = function (attrs) {
if (attrs.admin != this.get('admin')) return "Can't change admin status.";
};
model.on('invalid', function (model, error) {
lastError = error;
});
var result = model.set({a: 100});
t.equal(result, model);
t.equal(model.get('a'), 100);
t.equal(lastError, undefined);
result = model.set({admin: true});
t.equal(model.get('admin'), true);
result = model.set({a: 200, admin: false}, {validate: true});
t.equal(lastError, "Can't change admin status.");
t.equal(result, false);
t.equal(model.get('a'), 100);
});
test("validate on unset and clear", function (t) {
t.plan(6);
var error;
var model = new Backbone.Model({name: "One"});
model.validate = function (attrs) {
if (!attrs.name) {
error = true;
return "No thanks.";
}
};
model.set({name: "Two"});
t.equal(model.get('name'), 'Two');
t.equal(error, undefined);
model.unset('name', {validate: true});
t.equal(error, true);
t.equal(model.get('name'), 'Two');
model.clear({validate: true});
t.equal(model.get('name'), 'Two');
delete model.validate;
model.clear();
t.equal(model.get('name'), undefined);
});
test("validate with error callback", function (t) {
t.plan(8);
var lastError, boundError;
var model = new Backbone.Model();
model.validate = function (attrs) {
if (attrs.admin) return "Can't change admin status.";
};
model.on('invalid', function (model, error) {
boundError = true;
});
var result = model.set({a: 100}, {validate: true});
t.equal(result, model);
t.equal(model.get('a'), 100);
t.equal(model.validationError, null);
t.equal(boundError, undefined);
result = model.set({a: 200, admin: true}, {validate: true});
t.equal(result, false);
t.equal(model.get('a'), 100);
t.equal(model.validationError, "Can't change admin status.");
t.equal(boundError, true);
});
test("defaults always extend attrs (#459)", function (t) {
t.plan(2);
var Defaulted = Backbone.Model.extend({
props: {
one: ['number', true, 1]
},
initialize : function (attrs, opts) {
t.equal(this.attributes.one, 1);
}
});
var providedattrs = new Defaulted({});
var emptyattrs = new Defaulted();
});
test.skip("Inherit class properties", function (t) {
t.plan(6);
var Parent = Backbone.Model.extend({
instancePropSame: function () {},
instancePropDiff: function () {}
}, {
classProp: function () {}
});
var Child = Parent.extend({
instancePropDiff: function () {}
});
var adult = new Parent();
var kid = new Child();
t.equal(Child.classProp, Parent.classProp);
t.notEqual(Child.classProp, undefined);
t.equal(kid.instancePropSame, adult.instancePropSame);
t.notEqual(kid.instancePropSame, undefined);
t.notEqual(Child.prototype.instancePropDiff, Parent.prototype.instancePropDiff);
t.notEqual(Child.prototype.instancePropDiff, undefined);
});
test("Nested change events don't clobber previous attributes", function (t) {
t.plan(4);
new Backbone.Model()
.on('change:state', function (model, newState) {
t.equal(model.previous('state'), undefined);
t.equal(newState, 'hello');
// Fire a nested change event.
model.set({other: 'whatever'});
})
.on('change:state', function (model, newState) {
t.equal(model.previous('state'), undefined);
t.equal(newState, 'hello');
})
.set({state: 'hello'});
});
test("hasChanged/set should use same comparison", function (t) {
t.plan(2);
var changed = 0, model = new Backbone.Model({a: null});
model.on('change', function () {
t.ok(this.hasChanged('a'));
})
.on('change:a', function () {
changed++;
})
.set({a: undefined});
t.equal(changed, 1);
});
test("#582, #425, change:attribute callbacks should fire after all changes have occurred", function (t) {
t.plan(9);
var model = new Backbone.Model();
var assertion = function () {
t.equal(model.get('a'), 'a');
t.equal(model.get('b'), 'b');
t.equal(model.get('c'), 'c');
};
model.on('change:a', assertion);
model.on('change:b', assertion);
model.on('change:c', assertion);
model.set({a: 'a', b: 'b', c: 'c'});
});
test.skip("#871, set with attributes property", function (t) {
t.plan(1);
var model = new Backbone.Model();
model.set({attributes: true});
t.ok(model.has('attributes'));
});
test.skip("set value regardless of equality/change", function (t) {
t.plan(1);
var model = new Backbone.Model({x: []});
var a = [];
model.set({x: a});
t.ok(model.get('x') === a);
});
test("set same value does not trigger change", function (t) {
var model = new Backbone.Model({x: 1});
model.on('change change:x', function () {
t.ok(false);
});
model.set({x: 1});
model.set({x: 1});
t.end();
});
test("unset does not fire a change for undefined attributes", function (t) {
var model = new Backbone.Model({x: undefined});
model.on('change:x', function () { t.ok(false); });
model.unset('x');
t.end();
});
test.skip("set: undefined values", function (t) {
t.plan(1);
var model = new Backbone.Model({x: undefined});
t.ok('x' in model.attributes);
});
test("hasChanged works outside of change events, and true within", function (t) {
t.plan(6);
var model = new Backbone.Model({x: 1});
model.on('change:x', function () {
t.ok(model.hasChanged('x'));
t.equal(model.get('x'), 1);
});
model.set({x: 2}, {silent: true});
t.ok(model.hasChanged());
t.equal(model.hasChanged('x'), true);
model.set({x: 1});
t.ok(model.hasChanged());
t.equal(model.hasChanged('x'), true);
});
test("hasChanged gets cleared on the following set", function (t) {
t.plan(4);
var model = new Backbone.Model();
model.set({x: 1});
t.ok(model.hasChanged());
model.set({x: 1});
t.ok(!model.hasChanged());
model.set({x: 2});
t.ok(model.hasChanged());
model.set({});
t.ok(!model.hasChanged());
});
test.skip("save with `wait` succeeds without `validate`", function (t) {
t.plan(1);
var model = new Backbone.Model();
model.url = '/test';
model.save({x: 1}, {wait: true});
t.ok(this.syncArgs.model === model);
});
test.skip("save without `wait` doesn't set invalid attributes", function (t) {
t.plan(1);
var model = new Backbone.Model();
model.validate = function () { return 1; };
model.save({a: 1});
t.equal(model.get('a'), void 0);
});
test("save with PATCH and `wait` only sends specified attributes", function (t) {
t.plan(4);
var Model = Backbone.Model.extend({id: 1});
var model = new Model({parent_id: 1});
model.set({a: 1, b: 2, d: 4, e: 5});
model.save({b: 2, d: 4}, {patch: true, wait: true });
t.equal(env.syncArgs.method, 'patch');
t.equal(_.size(env.syncArgs.options.attrs), 2);
t.equal(env.syncArgs.options.attrs.d, 4);
t.equal(env.syncArgs.options.attrs.a, undefined);
});
test.skip("save doesn't validate twice", function (t) {
t.plan(1);
var model = new Backbone.Model();
var times = 0;
model.sync = function () {};
model.validate = function () { ++times; };
model.save({});
t.equal(times, 1);
});
test("`hasChanged` for falsey keys", function (t) {
t.plan(2);
var model = new Backbone.Model();
model.set({x: true}, {silent: true});
t.ok(!model.hasChanged(0));
t.ok(!model.hasChanged(''));
});
test("`previous` for falsey keys", function (t) {
t.plan(2);
var model = new Backbone.Model({0: true, '': true});
model.set({0: false, '': false}, {silent: true});
t.equal(model.previous(0), true);
t.equal(model.previous(''), true);
});
test.skip("`save` with `wait` sends correct attributes", function (t) {
t.plan(5);
var changed = 0;
var model = new Backbone.Model({x: 1, y: 2});
model.url = '/test';
model.on('change:x', function () { changed++; });
model.save({x: 3}, {wait: true});
t.deepEqual(JSON.parse(this.ajaxSettings.data), {x: 3, y: 2});
t.equal(model.get('x'), 1);
t.equal(changed, 0);
this.syncArgs.options.success({});
t.equal(model.get('x'), 3);
t.equal(changed, 1);
});
test("a failed `save` with `wait` doesn't leave attributes behind", function (t) {
t.plan(1);
var model = new Backbone.Model();
model.url = '/test';
model.save({x: 1}, {wait: true});
t.equal(model.get('x'), void 0);
});
test("#1030 - `save` with `wait` results in correct attributes if success is called during sync", function (t) {
t.plan(2);
var model = new Backbone.Model({x: 1, y: 2});
model.sync = function (method, model, options) {
options.success();
};
model.on("change:x", function () { t.ok(true); });
model.save({x: 3}, {wait: true});
t.equal(model.get('x'), 3);
});
test("save with wait validates attributes", function (t) {
t.plan(1);
var model = new Backbone.Model();
model.url = '/test';
model.validate = function () { t.ok(true); };
model.save({x: 1}, {wait: true});
});
test.skip("save turns on parse flag", function (t) {
t.plan(1);
var Model = Backbone.Model.extend({
sync: function (method, model, options) { t.ok(options.parse); }
});
new Model().save();
});
test("nested `set` during `'change:attr'`", function (t) {
t.plan(2);
var events = [];
var model = new Backbone.Model();
model.on('all', function (event) { events.push(event); });
model.on('change', function () {
model.set({z: true}, {silent: true});
});
model.on('change:x', function () {
model.set({y: true});
});
model.set({x: true});
t.deepEqual(events, ['change:y', 'change:x', 'change']);
events = [];
model.set({z: true});
t.deepEqual(events, []);
});
test("nested `change` only fires once", function (t) {
t.plan(1);
var model = new Backbone.Model();
model.on('change', function () {
t.ok(true);
model.set({x: true});
});
model.set({x: true});
});
test("nested `set` during `'change'`", function (t) {
t.plan(6);
var count = 0;
var model = new Backbone.Model();
model.on('change', function () {
switch (count++) {
case 0:
t.deepEqual(this.changedAttributes(), {x: true});
t.equal(model.previous('x'), undefined);
model.set({y: true});
break;
case 1:
t.deepEqual(this.changedAttributes(), {x: true, y: true});
t.equal(model.previous('x'), undefined);
model.set({z: true});
break;
case 2:
t.deepEqual(this.changedAttributes(), {x: true, y: true, z: true});
t.equal(model.previous('y'), undefined);
break;
default:
t.ok(false);
}
});
model.set({x: true});
});
test("nested `change` with silent", function (t) {
t.plan(3);
var count = 0;
var model = new Backbone.Model();
model.on('change:y', function () { t.ok(false); });
model.on('change', function () {
switch (count++) {
case 0:
t.deepEqual(this.changedAttributes(), {x: true});
model.set({y: true}, {silent: true});
model.set({z: true});
break;
case 1:
t.deepEqual(this.changedAttributes(), {x: true, y: true, z: true});
break;
case 2:
t.deepEqual(this.changedAttributes(), {z: false});
break;
default:
t.ok(false);
}
});
model.set({x: true});
model.set({z: false});
});
test("nested `change:attr` with silent", function (t) {
var model = new Backbone.Model();
model.on('change:y', function () { t.ok(false); });
model.on('change', function () {
model.set({y: true}, {silent: true});
model.set({z: true});
});
model.set({x: true});
t.end();
});
test("multiple nested changes with silent", function (t) {
t.plan(1);
var model = new Backbone.Model();
model.on('change:x', function () {
model.set({y: 1}, {silent: true});
model.set({y: 2});
});
model.on('change:y', function (model, val) {
t.equal(val, 2);
});
model.set({x: true});
});
test("multiple nested changes with silent", function (t) {
t.plan(1);
var changes = [];
var model = new Backbone.Model();
model.on('change:b', function (model, val) { changes.push(val); });
model.on('change', function () {
model.set({b: 1});
});
model.set({b: 0});
t.deepEqual(changes, [0, 1]);
});
test("basic silent change semantics", function (t) {
t.plan(1);
var model = new Backbone.Model();
model.set({x: 1});
model.on('change', function () { t.ok(true); });
model.set({x: 2}, {silent: true});
model.set({x: 1});
});
test("nested set multiple times", function (t) {
t.plan(1);
var model = new Backbone.Model();
model.on('change:b', function () {
t.ok(true);
});
model.on('change:a', function () {
model.set({b: true});
model.set({b: true});
});
model.set({a: true});
});
test("#1122 - clear does not alter options.", function (t) {
t.plan(1);
var model = new Backbone.Model();
var options = {};
model.clear(options);
t.ok(!options.unset);
});
test("#1122 - unset does not alter options.", function (t) {
t.plan(1);
var model = new Backbone.Model({x: 1});
var options = {};
model.unset('x', options);
t.ok(!options.unset);
});
test("#1355 - `options` is passed to success callbacks", function (t) {
t.plan(3);
var model = new Backbone.Model();
var opts = {
success: function (model, resp, options) {
t.ok(options);
}
};
model.sync = function (method, model, options) {
options.success();
};
model.save({id: 1}, opts);
model.fetch(opts);
model.destroy(opts);
});
test("#1412 - Trigger 'sync' event.", function (t) {
t.plan(3);
var model = new Backbone.Model({id: 1});
model.sync = function (method, model, options) { options.success(); };
model.on('sync', function () { t.ok(true); });
model.fetch();
model.save();
model.destroy();
});
test("#1365 - Destroy: New models execute success callback.", function (t) {
t.plan(2);
new Backbone.Model()
.on('sync', function () { t.ok(false); })
.on('destroy', function () { t.ok(true); })
.destroy({ success: function () { t.ok(true); }});
});
test("#1433 - Save: An invalid model cannot be persisted.", function (t) {
t.plan(1);
var model = new Backbone.Model();
model.validate = function () { return 'invalid'; };
model.sync = function () { t.ok(false); };
t.strictEqual(model.save(), false);
});
test("#1377 - Save without attrs triggers 'error'.", function (t) {
t.plan(1);
var Model = Backbone.Model.extend({
url: '/test/',
sync: function (method, model, options) { options.success(); },
validate: function () { return 'invalid'; }
});
var model = new Model({id: 1});
model.on('invalid', function () { t.ok(true); });
model.save();
});
test("#1545 - `undefined` can be passed to a model constructor without coersion", function (t) {
var Model = Backbone.Model.extend({
defaults: { one: 1 },
initialize : function (attrs, opts) {
t.equal(attrs, undefined);
}
});
var emptyattrs = new Model();
var undefinedattrs = new Model(undefined);
t.end();
});
test("#1478 - Model `save` does not trigger change on unchanged attributes", function (t) {
var Model = Backbone.Model.extend({
sync: function (method, model, options) {
setTimeout(function () {
options.success();
t.end();
}, 0);
}
});
new Model({x: true})
.on('change:x', function () { t.ok(false); })
.save(null, {wait: true});
});
test("#1664 - Changing from one value, silently to another, back to original triggers a change.", function (t) {
t.plan(1);
var model = new Backbone.Model({x: 1});
model.on('change:x', function () { t.ok(true); });
model.set({x: 2}, {silent: true});
model.set({x: 3}, {silent: true});
model.set({x: 1});
});
test("#1664 - multiple silent changes nested inside a change event", function (t) {
t.plan(2);
var changes = [];
var model = new Backbone.Model();
model.on('change', function () {
model.set({a: 'c'}, {silent: true});
model.set({b: 2}, {silent: true});
model.unset('c', {silent: true});
});
model.on('change:a change:b change:c', function (model, val) { changes.push(val); });
model.set({a: 'a', b: 1, c: 'item'});
t.deepEqual(changes, ['a', 1, 'item']);
t.deepEqual(model.attributes, {a: 'c', b: 2});
});
test("#1791 - `attributes` is available for `parse`", function (t) {
var Model = Backbone.Model.extend({
parse: function () { this.attributes; } // shouldn't throw an error
});
var model = new Model(null, {parse: true});
t.end();
});
test("silent changes in last `change` event back to original triggers change", function (t) {
t.plan(2);
var changes = [];
var model = new Backbone.Model();
model.on('change:a change:b change:c', function (model, val) { changes.push(val); });
model.on('change', function () {
model.set({a: 'c'}, {silent: true});
});
model.set({a: 'a'});
t.deepEqual(changes, ['a']);
model.set({a: 'a'});
t.deepEqual(changes, ['a', 'a']);
});
test("#1943 change calculations should use _.isEqual", function (t) {
t.plan(1);
var model = new Backbone.Model({a: {key: 'value'}});
model.set('a', {key: 'value'}, {silent: true});
t.equal(model.changedAttributes(), false);
});
test("#1964 - final `change` event is always fired, regardless of interim changes", function (t) {
t.plan(1);
var model = new Backbone.Model();
model.on('change:property', function () {
model.set('property', 'bar');
});
model.on('change', function () {
t.ok(true);
});
model.set('property', 'foo');
});
test("isValid", function (t) {
t.plan(5);
var model = new Backbone.Model({valid: true});
model.validate = function (attrs) {
if (!attrs.valid) return "invalid";
};
t.equal(model.isValid(), true);
t.equal(model.set({valid: false}, {validate: true}), false);
t.equal(model.isValid(), true);
model.set({valid: false});
t.equal(model.isValid(), false);
t.ok(!model.set('valid', false, {validate: true}));
});
test("#1179 - isValid returns true in the absence of validate.", function (t) {
t.plan(1);
var model = new Backbone.Model();
model.validate = null;
t.ok(model.isValid());
});
test("#1961 - Creating a model with {validate:true} will call validate and use the error callback", function (t) {
t.plan(1);
var Model = Backbone.Model.extend({
validate: function (attrs) {
if (attrs.id === 1) return "This shouldn't happen";
}
});
var model = new Model({id: 1}, {validate: true});
t.equal(model.validationError, "This shouldn't happen");
});
test.skip("toJSON receives attrs during save(..., {wait: true})", function (t) {
t.plan(1);
var Model = Backbone.Model.extend({
url: '/test',
toJSON: function () {
t.strictEqual(this.attributes.x, 1);
return _.clone(this.attributes);
}
});
var model = new Model();
model.save({x: 1}, {wait: true});
});
test("#2034 - nested set with silent only triggers one change", function (t) {
t.plan(1);
var model = new Backbone.Model();
model.on('change', function () {
model.set({b: true}, {silent: true});
t.ok(true);
});
model.set({a: true});
});
})();
|
import React from 'react';
import { storiesOf } from '@kadira/storybook';
import Root from '../src/components/Root/Root';
import Dashboard from '../src/components/Dashboard/Dashboard';
storiesOf('Spinner', module)
.add('Active Spinner', () => (
<div>
<Root
IsSpinnerActive
location={{
pathname: 'testPath',
}}
notifications={[]}
>
<Dashboard />
</Root>
</div>
));
|
// ==ClosureCompiler==
// @compilation_level ADVANCED_OPTIMIZATIONS
// @output_file_name SelecTable.js
// ==/ClosureCompiler==
/**
* @license The MIT License (MIT)
* Copyright (c) 2014 c0ff3m4r <l34k@bk.ru>
*/
/* 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.
*/
/**
* @constructor
* @param {HTMLElement|string} table The table element or its Id.
* @param {Object} options Options
* @export
*/
var SelecTable = function(table, options)
{
/** @type{!NodeList} */
var inputs;
/** @type{number} */
var row_i;
/** @type{number} */
var cb_i;
/** @type{!Object} */
var sTable = this;
/** @dict */
this.defaults = {
'cssSelected': 'selected',
'cssFocused': 'focused',
'focusCheckbox': true,
'allCheckbox': false
}
// parse options to this.config
/** @dict */
this.config = {}
for (variable in this.defaults)
{
if (options && options.hasOwnProperty(variable))
this.config[variable] = options[variable];
else
this.config[variable] = this.defaults[variable];
}
function clear_selection(){
if (window.getSelection) {
if (window.getSelection().empty) { // Chrome
window.getSelection().empty();
} else if (window.getSelection().removeAllRanges) { // Firefox
window.getSelection().removeAllRanges();
}
} else if (document.selection) { // IE?
document.selection.empty();
}
}
/** @this{!HTMLElement} */
function checkboxOnclick(e)
{
// prevent row from beiing clicked
e.stopPropagation();
var row = this['row'];
if(this.checked)
{
sTable.select(row, true);
} else {
sTable.unselect(row);
}
}
/**
* @type{RegExp|null}
* @private
*/
this.reFocused = null;
/**
* @type{RegExp|null}
* @private
*/
this.reSelected = null;
if(this.config['cssFocused'])
{
this.reFocused = new RegExp("(?:^|\\s)"+ this.config['cssFocused'] +"(?!\\S)","g");
}
if(this.config['cssSelected'])
this.reSelected = new RegExp("(?:^|\\s)"+ this.config['cssSelected'] +"(?!\\S)","g");
if (typeof table == "string")
{
table = document.getElementById(table);
if(table === null) return;
}
/** @type {HTMLElement} */
this.table = table;
/** @type {Array.<HTMLElement>} */
var rows = table.tBodies[0].rows;
/** @type {?HTMLElement}
* @private
*/
this.selected = null;
/**
* @type {number}
* @private
*/
this.selectedCount = 0;
/** @type {HTMLElement} */
var all_checkbox = this.config['allCheckbox'];
// configure checkboxes
if(all_checkbox)
{
if (typeof all_checkbox == "string")
all_checkbox = document.getElementById(this.config['allCheckbox']);
all_checkbox.onchange = function()
{
if(this.checked)
{
sTable.selectAll()
}else{
sTable.unselectAll()
}
};
}
for(row_i=0; row_i<rows.length; row_i++)
{
inputs = rows[row_i].getElementsByTagName('input');
rows[row_i]['checkbox'] = null;
for(cb_i=0; cb_i < inputs.length; cb_i++){
if(inputs[cb_i].type == "checkbox"){
inputs[cb_i].onclick = checkboxOnclick;
if(inputs[cb_i].checked)
{
this.select(row_i, true);
}
inputs[cb_i]['row'] = rows[row_i]
rows[row_i]['checkbox'] = inputs[cb_i];
break;
}
}
rows[row_i].setAttribute('unselectable', 'on'); // IE fix
/**
* The onclick function for rows
*/
rows[row_i].onclick = function(e)
{
var row;
if(!e) e = event;
if (e.ctrlKey == 1) {
sTable.toggle(this);
}else if (e.shiftKey == 1){
row = sTable.getSelectedRow();
if (row !== null) sTable.selectRange(row, this);
}else{
// select it if it wasn't selected already
// or if the object wasn't the only one
if(!sTable.getRowIsSelected(this) || sTable.selectedCount > 1)
sTable.selectOnly(this);
else
sTable.unselectAll();
}
if (e.shiftKey == 1)
{
// if there was something selected
// we clear it.
clear_selection();
}
}
}
/** @type {Array.<!HTMLElement>} */
this.rows = rows;
}
/**
* Select a row.
*
* @param {!HTMLElement|number} index The row number or object to select.
* @param {boolean=} changefocus Change the focus to this element?.
*/
SelecTable.prototype.select = function(index, changefocus){
if(typeof(changefocus) === 'undefined') changefocus = true;
/** @type{!HTMLElement} */
var row = this._getRow(index);
/** @type{HTMLElement} */
var checkbox = row['checkbox'];
if (changefocus){
if(this.reFocused)
{
if (this.selected != null)
{
this.selected.className = this.selected.className.replace(this.reFocused, "");
}
row.className += ' ' + this.config['cssFocused'];
}
this.selected = row;
if (this.config['focusCheckbox'] && checkbox)
{
checkbox.focus();
}
}
if (this.reSelected) row.className += ' ' + this.config['cssSelected'];
if(checkbox)
{
if(!checkbox.checked)
// increment counter only if it wasn't checked
this.selectedCount ++;
checkbox.checked = true;
}
};
/**
* @param {!HTMLElement|number} index The row number or object to unselect.
*/
SelecTable.prototype.unselect = function(index)
{
/** type{!HTMLElement} */
var row = this._getRow(index);
/** @type{HTMLElement} */
var checkbox = row['checkbox'];
if (this.reSelected)
{
row.className = row.className.replace(this.reSelected, "");
}
if(checkbox)
{
if(checkbox.checked)
// decrement counter only if it was checked
this.selectedCount --;
checkbox.checked = false;
}
};
/**
* @param {!HTMLElement|number} index The row number or object to toggle.
*/
SelecTable.prototype.toggle = function(index)
{
/** @type{!HTMLElement} */
var row = this._getRow(index);
if(row['checkbox'].checked) this.unselect(row);
else this.select(row, true);
};
/**
* @param {!HTMLElement|number} row The row number or object to unselect.
* @return {number}
*
* @private
*/
SelecTable.prototype._getRowIndex = function(row){
if (typeof row === 'number') return row;
if(!row || typeof row.nodeType !== 'number' && row.nodeType == 3) throw row;
return row.rowIndex - this.table.tHead.rows.length;
}
/**
* @param {number|!HTMLElement} row The row or the index to it.$
* @return {!HTMLElement}
*
* @private
*/
SelecTable.prototype._getRow = function(row){
if (typeof row === 'number') return this.rows[row];
if(!row || typeof row.nodeType !== 'number' && row.nodeType == 3) throw row;
return row;
}
/**
* @param {!HTMLElement|number} row
* @return {boolean}
*
*/
SelecTable.prototype.getRowIsSelected = function(row)
{
return this.rows[this._getRowIndex(row)]['checkbox'].checked;
}
/**
* Returns the currently selected row.
* @return{?HTMLElement}
*
*/
SelecTable.prototype.getSelectedRow = function()
{
return this.selected;
}
/**
* Select all
*/
SelecTable.prototype.selectAll = function()
{
for(var i=this.rows.length - 1; i >= 0; i--)
this.select(this.rows[i], true);
};
/**
* @param {!HTMLElement|number} index
*/
SelecTable.prototype.selectOnly = function(index)
{
this.unselectAll();
this.select(index);
}
/**
* @param {!HTMLElement|number} start
* @param {!HTMLElement|number} stop * @private
*/
SelecTable.prototype.selectRange = function(start, stop)
{
var i, a=1;
/** @type{number} */
var start_index = this._getRowIndex(start);
/** @type{number} */
var stop_index = this._getRowIndex(stop);
if(start_index > stop_index) a = -1;
for (i = start_index; i != stop_index; i += a) {
this.select(i, false);
};
this.select(stop, true);
}
SelecTable.prototype.unselectAll = function()
{
for (var i=0; i<this.rows.length; i++)
this.unselect(i);
}
// Export
window['SelecTable'] = SelecTable;
window['SelecTable'].prototype['getSelectedRow'] = SelecTable.prototype.getSelectedRow;
// SelecTable.prototype['select'] = SelecTable.prototype.select;
// SelecTable.prototype['unselect'] = SelecTable.prototype.unselect;
// SelecTable.prototype['toggle'] = SelecTable.prototype.toggle; |
import createSvgIcon from './utils/createSvgIcon';
import { jsx as _jsx } from "react/jsx-runtime";
export default createSvgIcon( /*#__PURE__*/_jsx("path", {
d: "M21 3H3c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h5v2h8v-2h5c1.1 0 1.99-.9 1.99-2L23 5c0-1.1-.9-2-2-2zm0 14H3V5h18v12zM4 14v2h2c0-1.11-.89-2-2-2zm0-3v1.43c1.97 0 3.57 1.6 3.57 3.57H9c0-2.76-2.24-5-5-5zm0-3v1.45c3.61 0 6.55 2.93 6.55 6.55H12c0-4.42-3.59-8-8-8z"
}), 'ConnectedTv'); |
KISSY.add('brix/gallery/charts/js/pub/views/modules/sign/main',function(S,Base,Node,Global,SVGElement,SVGGraphics){
var $ = Node.all
function Main(){
var self = this
Main.superclass.constructor.apply(self,arguments);
// self.init()
}
Main.ATTRS = {
w:{
value:0
},
h:{
value:0
},
element:{
value:null
},
_circle:{
value:null
},
_font:{
value:null
}
}
S.extend(Main,Base,{
init:function(){
var self = this
Main.superclass.constructor.apply(self,arguments);
self.set('element', new SVGElement('g')), self.get('element').set('class','layouts_sign')
// self.get('element').set('style','cursor:default'), self.get('element').mouseEvent(false)
self.get('parent').appendChild(self.get('element').element)
self._widget()
},
_widget:function(){
var self = this
var w = 0, h = 0
var element = self.get('element')
var config = self.get('config')
if(config.circle.is){
var circle = config.circle
self.set('_circle', SVGGraphics.circle({'r':circle.radius,'fill':circle.fill}))
var _circle = self.get('_circle')
element.appendChild(_circle.element)
w = circle.radius * 2, h = circle.radius * 2
}
if(config.font.is){
var font = config.font
self.set('_font', SVGGraphics.text({'content':font.content,'size':font.size,'fill':font.fill,'bold':font.bold,'family':font.family}))
var _font = self.get('_font')
element.appendChild(_font.element)
var y = _font.getHeight() / 2 * 0.50
var x = -_font.getWidth() / 2
_font.transformXY(x,y)
if(_font.getWidth() > w){
w = _font.getWidth()
}
if(_font.getHeight() > h){
h = _font.getHeight()
}
}
self.set('w', w)
self.set('h', h)
},
setStyle:function($o){
var self = this
if($o.circle){
self.get('_circle').set('fill',$o.circle.fill)
}
}
});
return Main;
}, {
requires:['base','node','../../../utils/global','../../../utils/svgelement','../../../views/svggraphics'
]
}
); |
import _ from 'lodash';
import { replaceVersion } from 'clayutils';
import { UPDATE_PAGE, REVERT_PAGE, IS_PUBLISHING } from './mutationTypes';
import { UPDATE_PAGE_STATE } from '../page-state/mutationTypes';
import {
save, create, getObject, removeText, remove, getHTML, getMeta
} from '../core-data/api';
import { add as addToQueue } from '../core-data/queue';
import {
pagesRoute, refProp, htmlExt, editExt, urisRoute, scheduleRoute
} from '../utils/references';
import { uriToUrl, urlToUri } from '../utils/urls';
import logger from '../utils/log';
/**
* @module page-data
*/
// saving these paths should NOT trigger a re-render of the page
const log = logger(__filename),
internalPageProps = [
'layout',
'customUrl',
'url',
'urlHistory'
];
/**
* iterate through the paths we're saving
* if one of them ISN'T in the internalPageProps, we should re-render
* @param {array} paths
* @return {boolean}
*/
function shouldRender(paths) {
return !!_.find(paths, path => !_.includes(internalPageProps, path));
}
function logSaveError(uri, e, data, snapshot, store) { // eslint-disable-line
log.error(`Error saving page: ${e.message}`, { action: 'savePage', uri });
store.dispatch('showSnackbar', { type: 'error', message: 'Changes made to current page were not saved!' });
store.dispatch('showSnackbar', {
message: 'Error saving page',
action: 'Retry',
onActionClick: () => store.dispatch('savePage', data, snapshot)
});
}
function queuePageSave(uri, data, oldData, store, {snapshot, paths}) { // eslint-disable-line
return addToQueue(save, [uri, data, true], 'save')
.then(() => getHTML(uri))
.then((html) => {
// note: we don't care about the data we got back from the api
store.commit(UPDATE_PAGE, data);
if (shouldRender(paths)) {
return store.dispatch('render', {
uri, html, snapshot, paths
});
}
})
.catch((e) => {
store.commit(REVERT_PAGE, oldData);
logSaveError(uri, e, data, snapshot, store);
if (shouldRender(paths)) {
return store.dispatch('render', {
uri, html: document, snapshot, paths
});
}
});
}
/**
* save a page's data, but do not re-render
* because, uh, that would just be reloading the page
* @param {object} store
* @param {*} data to save
* @param {boolean} [snapshot] false if we're undoing/redoing
* @return {Promise}
*/
export function savePage(store, data, snapshot) {
let forceRender = data.forceRender || false;
delete data.forceRender;
const oldData = _.get(store, 'state.page.data'),
dataToSave = _.assign({}, oldData, data),
uri = _.get(store, 'state.page.uri'),
// figure out what properties we've changed
// (note: this does a shallow comparison, not deep)
paths = _.reduce(data, (result, val, key) => _.isEqual(val, oldData[key]) && !forceRender ? result : result.concat(key), []);
store.dispatch('startProgress', 'save');
return queuePageSave(uri, dataToSave, oldData, store, { snapshot, paths });
}
/**
* create a new page, then return its editable link
* @param {object} store
* @param {string} id
* @return {Promise}
*/
export function createPage(store, id) {
const prefix = _.get(store, 'state.site.prefix');
store.dispatch('startProgress', 'save');
return getObject(`${prefix}${pagesRoute}${id}`)
.then(data => create(`${prefix}${pagesRoute}`, data))
.then((newPage) => {
store.dispatch('finishProgress', 'save');
return `${uriToUrl(newPage[refProp])}${htmlExt}${editExt}`;
})
.catch((e) => {
log.error(`Error creating page: ${e.message}`, { action: 'createPage', uri: `${prefix}${pagesRoute}${id}` });
store.dispatch('finishProgress', 'error');
store.dispatch('showSnackbar', 'Error creating page');
throw e;
});
}
/**
* set currentlyPublishing in state
* @param {object} store
* @param {boolean} isPublishing
*/
export function isPublishing(store, isPublishing = false) {
store.commit(IS_PUBLISHING, isPublishing);
}
/**
* manually publish the page
* @param {object} store
* @param {string} uri
* @return {Promise}
*/
export function publishPage(store, uri) {
const isScheduled = _.get(store, 'state.page.state.scheduled');
let promise;
store.dispatch('startProgress', 'published');
// unschedule (without updating page state [yet]), then publish the page
if (isScheduled) {
promise = unschedulePage(store, true);
} else {
promise = Promise.resolve(); // do nothing
}
return promise.then(() => {
return addToQueue(save, [`${replaceVersion(uri, 'published')}`], 'published')
.then(() => getMeta(uri)) // now we update the page state, which will include the unschedule event (if applicable)
.then(updatedState => store.commit(UPDATE_PAGE_STATE, updatedState))
.then(() => store.dispatch('isPublishing', false));
});
}
/**
* remove uri from /uris/
* @param {String} uri
* @param {Object} store
* @return {Promise}
*/
function removeURI(uri, store) {
const prefix = _.get(store, 'state.site.prefix');
return removeText(`${prefix}${urisRoute}${btoa(uri)}`);
}
/**
* remove uri from /uris/
* @param {object} store
* @param {string} uri
* @return {Promise}
*/
export function unpublishPage(store, uri) {
const url = _.get(store, 'state.page.state.url'),
publishedURI = urlToUri(url);
store.dispatch('startProgress', 'published');
return removeURI(publishedURI, store)
.then(() => getMeta(replaceVersion(uri)))
.then((updatedState) => {
store.commit(UPDATE_PAGE_STATE, updatedState);
store.dispatch('finishProgress', 'draft');
});
}
/**
* schedule the page to publish
* @param {object} store
* @param {string} uri
* @param {Date} timestamp
* @return {Promise}
*/
export function schedulePage(store, { uri, timestamp }) {
const prefix = _.get(store, 'state.site.prefix'),
scheduleUri = `${prefix}${scheduleRoute}`;
store.dispatch('startProgress', 'scheduled');
return create(scheduleUri, {
at: timestamp,
publish: uriToUrl(uri)
}).then(() => getMeta(uri))
.then((updatedState) => {
store.commit(UPDATE_PAGE_STATE, updatedState);
store.dispatch('finishProgress', 'scheduled');
});
}
/**
* unschedule the page
* get updated page state if the call wasn't made during a page publish
* @param {object} store
* @param {Boolean} [publishing]
* @return {Promise}
*/
export function unschedulePage(store, publishing = false) {
const pageUri = _.get(store, 'state.page.uri'),
scheduleId = btoa(pageUri),
prefix = _.get(store, 'state.site.prefix'),
scheduleUri = `${prefix}${scheduleRoute}/${scheduleId}`;
store.dispatch('startProgress', 'scheduled');
return remove(scheduleUri)
.then(() => {
if (publishing) {
return Promise.resolve();
}
// only make this call on a true unschedule event, not an unschedule during publish
return getMeta(pageUri);
})
.then((updatedState) => {
store.dispatch('finishProgress', 'scheduled');
if (publishing) {
return;
}
store.commit(UPDATE_PAGE_STATE, updatedState);
});
}
|
angular.module('juiceShop').controller('RecycleController', [
'$scope',
'RecycleService',
'UserService',
'ConfigurationService',
function ($scope, recycleService, userService, configurationService) {
'use strict'
configurationService.getApplicationConfiguration().then(function (config) {
if (config && config.application && config.application.recyclePage) {
$scope.topImage = '/public/images/products/' + config.application.recyclePage.topProductImage
$scope.bottomImage = '/public/images/products/' + config.application.recyclePage.bottomProductImage
}
})
function initRecycle () {
userService.whoAmI().then(function (data) {
$scope.recycle = {}
$scope.recycle.UserId = data.id
$scope.userEmail = data.email
})
}
initRecycle()
$scope.save = function () {
recycleService.save($scope.recycle).then(function (savedRecycle) {
$scope.confirmation = 'Thank you for using our recycling service. We will ' + (savedRecycle.isPickup ? ('pick up your pomace on ' + savedRecycle.pickupDate) : 'deliver your recycle box asap') + '.'
initRecycle()
$scope.form.$setPristine()
})
}
function findAll () {
recycleService.find().then(function (recycles) {
$scope.recycles = recycles
}).catch(function (err) {
console.log(err)
})
}
findAll()
}])
|
var Utils = require('./../utils')
module.exports = (function() {
var HasManyDoubleLinked = function(definition, instance) {
this.__factory = definition
this.instance = instance
}
HasManyDoubleLinked.prototype.injectGetter = function(options) {
var self = this, _options = options
var customEventEmitter = new Utils.CustomEventEmitter(function() {
var where = {}, options = _options || {}
//fully qualify
var instancePrimaryKeys = Object.keys(self.instance.daoFactory.primaryKeys)
, instancePrimaryKey = instancePrimaryKeys.length > 0 ? instancePrimaryKeys[0] : 'id'
where[self.__factory.connectorDAO.tableName+"."+self.__factory.identifier] = self.instance[instancePrimaryKey]
var primaryKeys = Object.keys(self.__factory.connectorDAO.rawAttributes)
, foreignKey = primaryKeys.filter(function(pk) { return pk != self.__factory.identifier })[0]
, foreignPrimary = Object.keys(self.__factory.target.primaryKeys)
foreignPrimary = foreignPrimary.length === 1 ? foreignPrimary[0] : 'id'
where[self.__factory.connectorDAO.tableName+"."+foreignKey] = {join: self.__factory.target.tableName+"."+foreignPrimary}
if (options.where) {
if (Array.isArray(options.where)) {
smart = Utils.smartWhere([where, options.where], self.__factory.target.daoFactoryManager.sequelize.options.dialect)
smart = Utils.compileSmartWhere.call(self.__factory.target, smart, self.__factory.target.daoFactoryManager.sequelize.options.dialect)
if (smart.length > 0) {
options.where = smart
}
} else {
smart = Utils.smartWhere([where, options.where], self.__factory.target.daoFactoryManager.sequelize.options.dialect)
smart = Utils.compileSmartWhere.call(self.__factory.target, smart, self.__factory.target.daoFactoryManager.sequelize.options.dialect)
if (smart.length > 0) {
options.where = smart
}
}
} else {
options.where = where;
}
self.__factory.target.findAllJoin(self.__factory.connectorDAO.tableName, options)
.on('success', function(objects) { customEventEmitter.emit('success', objects) })
.on('error', function(err){ customEventEmitter.emit('error', err) })
.on('sql', function(sql) { customEventEmitter.emit('sql', sql)})
})
return customEventEmitter.run()
}
HasManyDoubleLinked.prototype.injectSetter = function(emitterProxy, oldAssociations, newAssociations) {
var self = this
, chainer = new Utils.QueryChainer()
, association = self.__factory.target.associations[self.__factory.associationAccessor]
, foreignIdentifier = association.isSelfAssociation ? association.foreignIdentifier : association.identifier;
var obsoleteAssociations = oldAssociations.filter(function (old) {
// Return only those old associations that are not found in new
return !Utils._.find(newAssociations, function (obj) {
return (!!obj[foreignIdentifier] && !!old[foreignIdentifier] ? obj[foreignIdentifier] === old[foreignIdentifier] : obj.id === old.id)
})
})
, unassociatedObjects = newAssociations.filter(function (obj) {
return !Utils._.find(oldAssociations, function (old) {
return (!!obj[foreignIdentifier] && !!old[foreignIdentifier] ? obj[foreignIdentifier] === old[foreignIdentifier] : obj.id === old.id)
})
})
if (obsoleteAssociations.length > 0) {
var foreignIds = obsoleteAssociations.map(function (associatedObject) {
return associatedObject.id
})
, primaryKeys = Object.keys(self.__factory.connectorDAO.rawAttributes)
, foreignKey = primaryKeys.filter(function(pk) { return pk != self.__factory.identifier })[0]
var where = {}
where[self.__factory.identifier] = self.instance[self.__factory.identifier] || self.instance.id
where[foreignKey] = foreignIds
chainer.add(self.__factory.connectorDAO.destroy(where))
}
if (unassociatedObjects.length > 0) {
var bulk = unassociatedObjects.map(function(unassociatedObject) {
var attributes = {}
attributes[self.__factory.identifier] = self.instance[self.__factory.identifier] || self.instance.id
attributes[foreignIdentifier] = unassociatedObject[foreignIdentifier] || unassociatedObject.id
return attributes
})
chainer.add(self.__factory.connectorDAO.bulkCreate(bulk))
}
chainer
.run()
.success(function() { emitterProxy.emit('success', newAssociations) })
.error(function(err) { emitterProxy.emit('error', err) })
.on('sql', function(sql) { emitterProxy.emit('sql', sql) })
}
HasManyDoubleLinked.prototype.injectAdder = function(emitterProxy, newAssociation) {
var attributes = {}
, association = this.__factory.target.associations[this.__factory.associationAccessor]
, foreignIdentifier = association.isSelfAssociation ? association.foreignIdentifier : association.identifier;
attributes[this.__factory.identifier] = this.instance[this.__factory.identifier] || this.instance.id
attributes[foreignIdentifier] = newAssociation[foreignIdentifier] || newAssociation.id
this.__factory.connectorDAO.create(attributes)
.success(function() { emitterProxy.emit('success', newAssociation) })
.error(function(err) { emitterProxy.emit('error', err) })
.on('sql', function(sql) { emitterProxy.emit('sql', sql) })
}
return HasManyDoubleLinked
})()
|
define({
root: ({
_widgetLabel: "Scalebar",
scale: "Scale"
}),
"ar": 1,
"bs": 1,
"ca": 1,
"cs": 1,
"da": 1,
"de": 1,
"el": 1,
"es": 1,
"et": 1,
"fi": 1,
"fr": 1,
"he": 1,
"hi": 1,
"hr": 1,
"hu": 1,
"it": 1,
"id": 1,
"ja": 1,
"ko": 1,
"lt": 1,
"lv": 1,
"nb": 1,
"nl": 1,
"pl": 1,
"pt-br": 1,
"pt-pt": 1,
"ro": 1,
"ru": 1,
"sl": 1,
"sr": 1,
"sv": 1,
"th": 1,
"tr": 1,
"uk": 1,
"vi": 1,
"zh-cn": 1,
"zh-hk": 1,
"zh-tw": 1
}); |
var assert = require('assert');
var app = require('../lib/app').default;
var wepy = require('../lib/wepy').default;
var App = require('./fake/app');
var wxfake = require('./wxfake');
wxfake.resetGlobal();
describe('app.js', () => {
let appConfig = wepy.$createApp(App, true);
let app = appConfig.$app;
it('wx instance', () => {
assert.strictEqual(app.$wxapp.app, 'app', 'wxapp equal getApp()');
assert.strictEqual(typeof wepy.getUserInfo, 'function', 'api init');
});
it('api call', () => {
wepy.getUserInfo({
success: function (res) {
assert.strictEqual(res.name, 'fakeID', 'wepy.getUserInfo success');
}
});
wepy.login({
fail: function (res) {
assert.strictEqual(res.code, 'xxx', 'wepy.login fail');
}
});
wepy.request({
data: {
number: 1
},
success: function (res) {
assert.strictEqual(res.number, 1, 'wepy.request success');
}
});
assert.strictEqual(wepy.createCanvasContext(), 'createCanvasContext', 'wepy.createCanvasContext called');
});
it('api use promisify', () => {
app.use('promisify');
assert.strictEqual(wepy.getUserInfo() instanceof Promise, true, 'it\'s a Promise');
wepy.getUserInfo().then(function (res) {
assert.strictEqual(res.name, 'fakeID', 'wepy.getUserInfo promisify success');
});
wepy.login().then(function (res) {
}).catch(function (res) {
assert.strictEqual(res.code, 'xxx', 'wepy.login promisify fail');
});
wepy.request({data: {number: 2}}).then(function (res) {
assert.strictEqual(res.number, 2, 'wepy.request success');
});
assert.strictEqual(wepy.createCanvasContext(), 'createCanvasContext', 'wepy.createCanvasContext called');
});
it('api use requestfix', () => {
app.$addons.promisify = undefined;
app.use('requestfix');
assert.strictEqual(wepy.getUserInfo() instanceof Promise, false, 'it\'s not a Promise');
wepy.request({
data: {
number: 1
},
success: function (res) {
assert.strictEqual(res.number, 1, 'wepy.request 1 success');
}
});
wepy.request({
data: {
number: 2
},
success: function (res) {
assert.strictEqual(res.number, 2, 'wepy.request 2 success');
}
});
wepy.request({
data: {
number: 3
},
success: function (res) {
assert.strictEqual(res.number, 3, 'wepy.request 3 success');
}
});
wepy.request({
data: {
number: 4
},
success: function (res) {
assert.strictEqual(res.number, 4, 'wepy.request 4 success');
}
});
wepy.request({
data: {
number: 5
},
success: function (res) {
assert.strictEqual(res.number, 5, 'wepy.request 5 success');
}
});
wepy.request({
data: {
number: 6
},
success: function (res) {
assert.strictEqual(res.number, 6, 'wepy.request 6 success');
}
});
});
it('api use both requestfix and promisify', () => {
app.use('promisify');
app.use('requestfix');
assert.strictEqual(wepy.getUserInfo() instanceof Promise, true, 'it\'s a Promise');
wepy.request({data: {number: 1}}).then(function (res) {
assert.strictEqual(res.number, 1, 'wepy.request 1 success');
});
wepy.request({data: {number: 2}}).then(function (res) {
assert.strictEqual(res.number, 2, 'wepy.request 2 success');
});
wepy.request({data: {number: 3}}).then(function (res) {
assert.strictEqual(res.number, 3, 'wepy.request 3 success');
});
wepy.request({data: {number: 4}}).then(function (res) {
assert.strictEqual(res.number, 4, 'wepy.request 4 success');
});
wepy.request({data: {number: 5}}).then(function (res) {
assert.strictEqual(res.number, 5, 'wepy.request 5 success');
});
wepy.request({data: {number: 6}}).then(function (res) {
assert.strictEqual(res.number, 6, 'wepy.request 6 success');
});
wepy.request({data: {number: 7}}).then(function (res) {
assert.strictEqual(res.number, 7, 'wepy.request 7 success');
});
});
it('api intercept return false', () => {
app.$addons.promisify = undefined;
app.$addons.requestfix = undefined;
app.intercept('request', {
config: function (p) {
return false;
}
});
wepy.request({
data: {number: 1},
success: function (res) {
assert.strictEqual(res.number, 2222222, 'Should not go here');
},
fail: function (e) {
assert.strictEqual(e, 'aborted by interceptor', 'wepy.request intercept test success');
}
});
app.use('promisify');
app.use('requestfix');
wepy.request({data: {number: 1}}).then(function (res) {
assert.strictEqual(res.number, 2222222, 'Should not go here');
}).catch(function (e) {
assert.strictEqual(e, 'aborted by interceptor', 'wepy.request intercept test success');
});
});
it('api intercept', () => {
app.$addons.promisify = undefined;
app.$addons.requestfix = undefined;
app.intercept('request', {
config: function (p) {
p.data.number++;
return p;
},
success: function (p) {
p.number++;
return p;
}
});
wepy.request({
data: {number: 1},
success: function (res) {
assert.strictEqual(res.number, 3, 'wepy.request intercept test success');
},
fail: function (e) {
assert.strictEqual(e, 2222222, 'Should not go here');
}
});
app.use('promisify');
app.use('requestfix');
wepy.request({data: {number: 1}}).then(function (res) {
assert.strictEqual(res.number, 3, 'wepy.request promisfy intercept test success');
}).catch(function (e) {
assert.strictEqual(e, 'aborted by interceptor wrong', 'Should not go here');
});
});
it('api use 3rd part', () => {
let C = function () {
this.name = 'addon';
};
app.use(C, 1, 2, 3);
assert.strictEqual(app.$addons.C.name, 'addon', '3rd part addon');
});
}); |
Package.describe({
name: "vulcan:email-templates",
summary: "Telescope email templates package",
version: '1.3.0',
git: "https://github.com/TelescopeJS/Telescope.git"
});
Package.onUse(function (api) {
api.versionsFrom(['METEOR@1.0']);
api.use([
'vulcan:core@1.3.0',
'vulcan:posts@1.3.0',
'vulcan:comments@1.3.0',
'vulcan:email@1.3.0'
]);
api.addFiles([
'lib/emails.js'
], ['client', 'server']);
api.addFiles([
'lib/server/routes.js',
'lib/server/templates.js'
], ['server']);
api.addAssets([
'lib/server/emails/common/test.handlebars',
'lib/server/emails/common/wrapper.handlebars',
'lib/server/emails/comments/newComment.handlebars',
'lib/server/emails/comments/newReply.handlebars',
'lib/server/emails/posts/newPendingPost.handlebars',
'lib/server/emails/posts/newPost.handlebars',
'lib/server/emails/posts/postApproved.handlebars',
'lib/server/emails/users/accountApproved.handlebars',
'lib/server/emails/users/newUser.handlebars',
'lib/server/emails/newsletter/newsletter.handlebars',
'lib/server/emails/newsletter/newsletterConfirmation.handlebars',
'lib/server/emails/newsletter/postItem.handlebars',
], ['server']);
});
|
cordova.define("cordova-plugin-dialogs.NotificationProxy", function(require, exports, module) {
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
/*global Windows:true, WinJS, toStaticHTML */
var cordova = require('cordova');
var isAlertShowing = false;
var alertStack = [];
// CB-8928: When toStaticHTML is undefined, prompt fails to run
var _cleanHtml = function(html) { return html; };
if (typeof toStaticHTML !== 'undefined') {
_cleanHtml = toStaticHTML;
}
// Windows does not provide native UI for promp dialog so we use some
// simple html-based implementation until it is available
function createPromptDialog(title, message, buttons, defaultText, callback) {
var isPhone = cordova.platformId == "windows" && WinJS.Utilities.isPhone;
var dlgWrap = document.createElement("div");
dlgWrap.style.position = "absolute";
dlgWrap.style.width = "100%";
dlgWrap.style.height = "100%";
dlgWrap.style.backgroundColor = "rgba(0,0,0,0.25)";
dlgWrap.style.zIndex = "100000";
dlgWrap.className = "dlgWrap";
var dlg = document.createElement("div");
dlg.style.width = "100%";
dlg.style.minHeight = "180px";
dlg.style.height = "auto";
dlg.style.overflow = "auto";
dlg.style.backgroundColor = "white";
dlg.style.position = "relative";
dlg.style.lineHeight = "2";
if (isPhone) {
dlg.style.padding = "0px 5%";
} else {
dlg.style.top = "50%"; // center vertically
dlg.style.transform = "translateY(-50%)";
dlg.style.padding = "0px 30%";
}
// dialog layout template
dlg.innerHTML = _cleanHtml("<span id='lbl-title' style='font-size: 24pt'></span><br/>" + // title
"<span id='lbl-message'></span><br/>" + // message
"<input id='prompt-input' style='width: 100%'/><br/>"); // input fields
dlg.querySelector('#lbl-title').appendChild(document.createTextNode(title));
dlg.querySelector('#lbl-message').appendChild(document.createTextNode(message));
dlg.querySelector('#prompt-input').setAttribute('placeholder', defaultText);
function makeButtonCallback(idx) {
return function () {
var value = dlg.querySelector('#prompt-input').value;
dlgWrap.parentNode.removeChild(dlgWrap);
if (callback) {
callback({ input1: value, buttonIndex: idx });
}
};
}
function addButton(idx, label) {
var button = document.createElement('button');
button.style.margin = "8px 0 8px 16px";
button.style.float = "right";
button.style.fontSize = "12pt";
button.tabIndex = idx;
button.onclick = makeButtonCallback(idx + 1);
if (idx === 0) {
button.style.color = "white";
button.style.backgroundColor = "#464646";
} else {
button.style.backgroundColor = "#cccccc";
}
button.style.border = "none";
button.appendChild(document.createTextNode(label));
dlg.appendChild(button);
}
// reverse order is used since we align buttons to the right
for (var idx = buttons.length - 1; idx >= 0; idx--) {
addButton(idx, buttons[idx]);
}
dlgWrap.appendChild(dlg);
document.body.appendChild(dlgWrap);
// make sure input field is under focus
dlg.querySelector('#prompt-input').focus();
return dlgWrap;
}
module.exports = {
alert:function(win, loseX, args) {
if (isAlertShowing) {
var later = function () {
module.exports.alert(win, loseX, args);
};
alertStack.push(later);
return;
}
isAlertShowing = true;
var message = args[0];
var _title = args[1];
var _buttonLabel = args[2];
var md = new Windows.UI.Popups.MessageDialog(message, _title);
md.commands.append(new Windows.UI.Popups.UICommand(_buttonLabel));
md.showAsync().then(function() {
isAlertShowing = false;
if (win) {
win();
}
if (alertStack.length) {
setTimeout(alertStack.shift(), 0);
}
});
},
prompt: function (win, lose, args) {
if (isAlertShowing) {
var later = function () {
module.exports.prompt(win, lose, args);
};
alertStack.push(later);
return;
}
isAlertShowing = true;
var message = args[0],
title = args[1],
buttons = args[2],
defaultText = args[3];
try {
createPromptDialog(title, message, buttons, defaultText, function (evt) {
isAlertShowing = false;
if (win) {
win(evt);
}
});
} catch (e) {
// set isAlertShowing flag back to false in case of exception
isAlertShowing = false;
if (alertStack.length) {
setTimeout(alertStack.shift(), 0);
}
// rethrow exception
throw e;
}
},
confirm:function(win, loseX, args) {
if (isAlertShowing) {
var later = function () {
module.exports.confirm(win, loseX, args);
};
alertStack.push(later);
return;
}
isAlertShowing = true;
try {
var message = args[0];
var _title = args[1];
var buttons = args[2];
var md = new Windows.UI.Popups.MessageDialog(message, _title);
buttons.forEach(function(buttonLabel) {
md.commands.append(new Windows.UI.Popups.UICommand(buttonLabel));
});
md.showAsync().then(function(res) {
isAlertShowing = false;
var result = res ? buttons.indexOf(res.label) + 1 : 0;
if (win) {
win(result);
}
if (alertStack.length) {
setTimeout(alertStack.shift(), 0);
}
});
} catch (e) {
// set isAlertShowing flag back to false in case of exception
isAlertShowing = false;
if (alertStack.length) {
setTimeout(alertStack.shift(), 0);
}
// rethrow exception
throw e;
}
},
beep:function(winX, loseX, args) {
// set a default args if it is not set
args = args && args.length ? args : ["1"];
var snd = new Audio('ms-winsoundevent:Notification.Default');
var count = parseInt(args[0]) || 1;
snd.msAudioCategory = "Alerts";
var onEvent = function () {
if (count > 0) {
snd.play();
} else {
snd.removeEventListener("ended", onEvent);
snd = null;
if (winX) {
winX(); // notification.js just sends null, but this is future friendly
}
}
count--;
};
snd.addEventListener("ended", onEvent);
onEvent();
}
};
require("cordova/exec/proxy").add("Notification",module.exports);
});
|
var $ = require('jquery/dist/jquery');
var log = require('./log');
$(function() {
console.log('hello world');
}); |
// shows this is run through jsbin & you can edit
(function () {
if (window.location.hash == '#noedit') return;
var ie = (!+"\v1");
function set(el, props, hover) {
for (prop in props) {
el.style[prop] = props[prop];
}
}
function hide() {
set(el, { opacity: '0' });
}
var el = document.createElement('a');
set(el, { opacity: 1, position: 'fixed', top: '-1px', right: '-1px', padding: '5px 10px', background: '#ccc', color: '#333', 'text-shadow': '0px 1px 1px #fff', 'border-top-right-radius': '5px', MozBorderRadiusBottomleft: '5px', border: '1px solid #999', textDecoration: 'none', font: '12px "Helvetica Neue", Arial, Helvetica', WebkitTransition: 'opacity ease-out 100ms', MozTransition: 'opacity ease-out 100ms', OTransition: 'opacity ease-out 100ms', transition: 'opacity ease-out 100ms' });
el.innerHTML = 'Edit in jsbin.com';
el.href = window.location.pathname + (window.location.pathname.substr(-1) == '/' ? '' : '/') + 'edit';
el.onmouseover = function () {
this.style.opacity = 1;
};
el.onmouseout = function () {
this.style.opacity = 0;
};
document.body.appendChild(el);
setTimeout(hide, 2000);
var moveTimer = null;
if (document.addEventListener) {
document.addEventListener('mousemove', show, false);
} else {
document.attachEvent('onmousemove', show);
}
function show() {
if (!ie && (el.style.opacity*1) == 0) { // TODO IE compat
el.style.opacity = 1;
} else if (ie) {
set(el, { display: 'block', opacity: '1' });
}
clearTimeout(moveTimer);
moveTimer = setTimeout(hide, 2000);
}
})(); |
// https://babeljs.io/docs/en/babel-plugin-proposal-private-methods
// Test for `classPrivateProperties` and `classPrivateMethods`
class Counter extends HTMLElement {
#xValue = 0;
#render() {}
get #x() { return this.#xValue; }
set #x(value) {
this.#xValue = value;
window.requestAnimationFrame(
this.#render.bind(this));
}
#clicked() {
this.#x++;
}
}
|
'use strict';
angular.module('sidecar.services', ['ngRoute', 'ui.bootstrap'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/services', {
templateUrl: 'services/services.html',
controller: 'servicesCtrl'
});
}])
.factory('stateService', function($http, $q) {
function svcGetServices() {
return $http({
method: 'GET',
url: '/api/services.json',
dataType: 'json',
});
};
var haproxyUrl = window.location.protocol +
'//' + window.location.hostname +
':3212/;csv;norefresh';
function svcGetHaproxy() {
return $http({
method: 'GET',
url: haproxyUrl,
dataType: 'text/plain',
timeout: 300
});
};
var serviceWaiter = $q.defer();
var haproxyWaiter = $q.defer();
var state = {
waitFirstServices: serviceWaiter.promise,
waitFirstHaproxy: haproxyWaiter.promise,
services: {},
haproxy: {},
getServices: function() {
return state.services;
},
getHaproxy: function() {
return state.haproxy;
}
};
// Called on an interval to keep the data up to date
function refreshData() {
svcGetServices().then(function(services) {
state.services = services.data;
serviceWaiter.resolve();
});
svcGetHaproxy().then(function(haproxy) {
state.haproxy = haproxy.data;
haproxyWaiter.resolve();
}).catch(function() {
// didn't get a valid response, maybe we're not running HAproxy
haproxyWaiter.resolve();
});
};
setInterval(refreshData, 4000); // every 4 seconds
return state;
})
.controller('servicesCtrl', function($scope, $interval, stateService) {
$scope.serverList = {};
$scope.clusterName = "";
$scope.servicesList = {};
$scope.collapsed = {};
$scope.expandedServiceInfo = {};
$scope.haproxyInfo = {};
$scope.toggleCollapse = function(svcName) {
$scope.collapsed[svcName] = !$scope.isCollapsed(svcName);
};
$scope.isCollapsed = function(svcName) {
return $scope.collapsed[svcName] == null || $scope.collapsed[svcName];
};
$scope.toggleServiceInfo = function(svcName) {
$scope.expandedServiceInfo[svcName] = !$scope.isExpandedServiceInfo(svcName);
};
$scope.isExpandedServiceInfo = function(svcName) {
return $scope.expandedServiceInfo[svcName];
};
$scope.haproxyHas = function(svc) {
if ($scope.haproxyInfo[svc.Name] == null) return false;
if ($scope.haproxyInfo[svc.Name][svc.Hostname] == null) return false;
if ($scope.haproxyInfo[svc.Name][svc.Hostname][svc.ID] == null) return false;
return true;
};
function updateData() {
// Services
var services = {};
var servicesResponse = stateService.getServices();
for (var svcName in servicesResponse.Services) {
services[svcName] = servicesResponse.Services[svcName].groupBy(function(s) {
var ports = _.map(s.Ports, function(p) { _.pick(p, 'ServicePort') });
return [s.Image, ports, s.Status];
});
if ($scope.collapsed[svcName] == null) {
$scope.collapsed[svcName] = true;
}
}
$scope.servicesList = services;
$scope.clusterName = servicesResponse.ClusterName;
$scope.serverList = servicesResponse.ClusterMembers;
// Haproxy
var haproxyResponse = stateService.getHaproxy();
var raw = {};
try {
raw = Papa.parse(haproxyResponse, { header: true });
} catch(e) {
console.log("Appears there is no HAproxy, skipping")
return;
}
var transform = function(memo, item) {
if (item.svname == 'FRONTEND' || item.svname == 'BACKEND' ||
item['# pxname'] == 'stats' || item['# pxname'] == 'stats_proxy' ||
item['# pxname'] == '') {
return memo
}
// Transform the resulting HAproxy structure into something we can use
var fields = item['# pxname'].split('-');
var svcPort = fields[fields.length-1];
var svcName = fields.slice(0, fields.length-1).join('-');
fields = item.svname.split('-');
var hostname = fields.slice(0, fields.length-1).join('-');
var containerID = fields[fields.length-1];
// Store by servce -> hostname -> container
memo[svcName] = memo[svcName] || {};
memo[svcName][hostname] = memo[svcName][hostname] || {}
memo[svcName][hostname][containerID] = item;
return memo
};
var processed = _.inject(raw.data, transform, {});
$scope.haproxyInfo = processed;
};
// On the first time through, this will update the data and kick off the
// scheduled refresh. Otherwise do nothing.
stateService.waitFirstHaproxy.then(function() {
stateService.waitFirstServices.then(function() {
updateData();
$interval(updateData, 4000); // Update UI every 2 seconds
}, function(){})
}, function(){});
})
.filter('portsStr', function() {
return function(svcPorts) {
var ports = []
for (var i in svcPorts) {
var port = svcPorts[i]
if (port.Port == null) {
continue;
}
if (port.ServicePort != null && port.ServicePort != 0) {
ports.push(port.ServicePort.toString() + "->" + port.Port.toString())
} else {
ports.push(port.Port.toString())
}
}
return ports.join(", ")
};
})
.filter('statusStr', function() {
return function(status) {
switch (status) {
case 0:
return "Alive"
case 2:
return "Unhealthy"
case 3:
return "Unknown"
case 4:
return "Draining"
default:
return "Tombstone"
}
}
})
.filter('timeAgo', function() {
return function(textDate) {
if (textDate == null || textDate == "") {
return "never";
}
var date = Date.parse(textDate)
var seconds = Math.floor((new Date() - date) / 1000);
// Filter things which aren't quite Unix epoch zero but are still bogus
if (seconds > 630720000) { // More than 20 years ago
return "never";
}
var interval = Math.floor(seconds / 31536000);
if (interval > 1) {
return interval + " years ago";
}
interval = Math.floor(seconds / 2592000);
if (interval > 1) {
return interval + " months ago";
}
interval = Math.floor(seconds / 86400);
if (interval > 1) {
return interval + " days ago";
}
interval = Math.floor(seconds / 3600);
if (interval > 1) {
return interval + " hours ago";
}
interval = Math.floor(seconds / 60);
if (interval > 1) {
return interval + " mins ago";
}
return Math.floor(seconds) + " secs ago";
}
})
.filter('imageStr', function() {
return function(imageName) {
if (imageName.length < 25) {
return imageName;
}
return imageName.substr(imageName.length - 25, imageName.length)
}
})
.filter('extractTag', function() {
return function(imageName) {
return imageName.split(':')[1]
}
})
.filter('prettyJSON', function() {
return function(obj) {
return JSON ? JSON.stringify(obj, null, 2) : obj;
}
})
;
if ( ! Array.prototype.groupBy) {
Array.prototype.groupBy = function (f)
{
var groups = {};
this.forEach(function(o) {
var group = JSON.stringify(f(o));
groups[group] = groups[group] || [];
groups[group].push(o);
});
return Object.keys(groups).map(function (group) {
return groups[group];
});
};
}
|
var app = require('app');
var BrowserWindow = require('browser-window');
var mainWindow = null;
app.on('ready', function() {
mainWindow = new BrowserWindow({ width: 800, height: 800 });
mainWindow.loadUrl('file://' + __dirname + '/index.html');
});
|
/*
* Utilities: A classic collection of JavaScript utilities
* Copyright 2112 Matthew Eernisse (mde@fleegix.org)
*
* 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.
*
*/
var core = require('./core')
, inflection = require('./inflection')
, string;
/**
@name string
@namespace string
*/
string = new (function () {
// Regexes for trimming, and character maps for escaping
var _LTR = /^\s+/
, _RTR = /\s+$/
, _TR = /^\s+|\s+$/g
, _NL = /\n|\r|\r\n/g
, _CHARS = {
'&': '&'
, '<': '<'
, '>': '>'
, '"': '"'
, '\'': '''
}
, _UUID_CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('')
, _buildEscape
, _buildEscapeTest;
// Builds the escape/unescape methods using a
// map of characters
_buildEscape = function(direction) {
return function(string) {
string = string || '';
string = string.toString();
var from, to, p;
for(p in _CHARS) {
from = direction == 'to' ? p : _CHARS[p];
to = direction == 'to' ? _CHARS[p] : p;
string = string.replace(new RegExp(from, 'gm'), to);
}
return string;
}
};
// Builds a method that tests for any escapable
// characters, useful for avoiding double-scaping if
// you're not sure if a string has already been escaped
_buildEscapeTest = function(direction) {
return function(string) {
var pat = ''
, p;
for(p in _CHARS) {
pat += direction == 'to' ? p : _CHARS[p];
pat += '|';
}
pat = pat.substr(0, pat.length - 1);
pat = new RegExp(pat, "gm");
return pat.test(string)
}
};
// Escape special XMl chars
this.escapeXML = _buildEscape('to');
// Unescape XML chars to literal representation
this.unescapeXML = _buildEscape('from');
// Test if a string includes special chars
// that need escaping
this.needsEscape = _buildEscapeTest('to');
// Test if a string includes escaped chars
// that need unescaping
this.needsUnescape = _buildEscapeTest('from');
/**
@name string#escapeRegExpChars
@public
@function
@return {String} A string of escaped characters
@description Escapes regex control-characters in strings
used to build regexes dynamically
@param {String} string The string of chars to escape
*/
this.escapeRegExpChars = (function() {
var specials = [ '^', '/', '.', '*', '+', '?', '|', '(', ')',
'[', ']', '{', '}', '\\' ];
sRE = new RegExp('(\\' + specials.join('|\\') + ')', 'g');
return function (string) {
var str = string || '';
str = String(str);
return str.replace(sRE, '\\$1');
};
}).call(this);
/**
@name string#toArray
@public
@function
@return {Array} Returns an array of characters
@description Converts a string to an array
@param {String} string The string to convert
*/
this.toArray = function(string) {
var str = string || ''
, arr = []
, i = -1;
str = String(str);
while (++i < str.length) {
arr.push(str.substr(i, 1));
}
return arr;
};
/**
@name string#reverse
@public
@function
@return {String} Returns the `string` reversed
@description Reverses a string
@param {String} string The string to reverse
*/
this.reverse = function(string) {
var str = string || '';
str = String(str);
return this.toArray(str).reverse().join('');
};
/**
@name string#ltrim
@public
@function
@return {String} Returns the trimmed string
@description Ltrim trims `char` from the left of a `string` and returns it
if no `char` is given it will trim spaces
@param {String} string The string to trim
@param {String} char The character to trim
*/
this.ltrim = function(string, char) {
var str = string || ''
, pat = char ? new RegExp('^' + char + '+') : _LTR;
str = String(str);
return str.replace(pat, '');
};
/**
@name string#rtrim
@public
@function
@return {String} Returns the trimmed string
@description Rtrim trims `char` from the right of a `string` and returns it
if no `char` is given it will trim spaces
@param {String} string The string to trim
@param {String} char The character to trim
*/
this.rtrim = function (string, char) {
var str = string || ''
, pat = char ? new RegExp(char + '+$') : _RTR;
str = String(str);
return str.replace(pat, '');
};
// Alias
this.chomp = this.rtrim;
/**
@name string#trim
@public
@function
@return {String} Returns the trimmed string
@description Trim trims `char` from the left and right of a `string` and returns it
if no `char` is given it will trim spaces
@param {String} string The string to trim
@param {String} char The character to trim
*/
this.trim = function (string, char) {
var str = string || ''
, pat = char ? new RegExp('^' + char + '+|' + char + '+$', 'g') : _TR;
str = String(str);
return str.replace(pat, '');
};
/**
@name string#chop
@public
@function
@description Returns a new String with the last character removed. If the
string ends with \r\n, both characters are removed. Applying chop to an
empty string returns an empty string.
@param {String} string to return with the last character removed.
*/
this.chop = function (string) {
var index
, str = string || '';
str = String(str);
if (str.length) {
// Special-case for \r\n
index = str.indexOf('\r\n');
if (index == str.length - 2) {
return str.substring(0, index);
}
return str.substring(0, str.length - 1);
}
else {
return '';
}
};
/**
@name string#lpad
@public
@function
@return {String} Returns the padded string
@description Lpad adds `char` to the left of `string` until the length
of `string` is more than `width`
@param {String} string The string to pad
@param {String} char The character to pad with
@param {Number} width the width to pad to
*/
this.lpad = function(string, char, width) {
var str = string || ''
, width;
str = String(str);
// Should width be string.length + 1? or the same to be safe
width = parseInt(width, 10) || str.length;
char = char || ' ';
while(str.length < width) {
str = char + str;
}
return str;
};
/**
@name string#rpad
@public
@function
@return {String} Returns the padded string
@description Rpad adds `char` to the right of `string` until the length
of `string` is more than `width`
@param {String} string The string to pad
@param {String} char The character to pad with
@param {Number} width the width to pad to
*/
this.rpad = function(string, char, width) {
var str = string || ''
, width;
str = String(str);
// Should width be string.length + 1? or the same to be safe
width = parseInt(width, 10) || str.length;
char = char || ' ';
while(str.length < width) {
str += char;
}
return str;
};
/**
@name string#pad
@public
@function
@return {String} Returns the padded string
@description Pad adds `char` to the left and right of `string` until the length
of `string` is more than `width`
@param {String} string The string to pad
@param {String} char The character to pad with
@param {Number} width the width to pad to
*/
this.pad = function(string, char, width) {
var str = string || ''
, width;
str = String(str);
// Should width be string.length + 1? or the same to be safe
width = parseInt(width, 10) || str.length;
char = char || ' ';
while(str.length < width) {
str = char + str + char;
}
return str;
};
/**
@name string#truncate
@public
@function
@return {String} Returns the truncated string
@description Truncates a given `string` after a specified `length` if `string` is longer than
`length`. The last characters will be replaced with an `omission` for a total length
not exceeding `length`. If `callback` is given it will fire if `string` is truncated.
@param {String} string The string to truncate
@param {Integer/Object} options Options for truncation, If options is an Integer it will be length
@param {Integer} [options.length=string.length] Length the output string will be
@param {Integer} [options.len] Alias for `length`
@param {String} [options.omission='...'] Replace last characters with an omission
@param {String} [options.ellipsis='...'] Alias for `omission`
@param {String/RegExp} [options.seperator] Break the truncated test at the nearest `seperator`
@param {Function} callback Callback is called only if a truncation is done
*/
this.truncate = function(string, options, callback) {
var str = string || ''
, stringLen
, opts
, stringLenWithOmission
, last
, ignoreCase
, multiLine
, stringToWorkWith
, lastIndexOf
, nextStop
, result
, returnString;
str = String(str);
stringLen = str.length
// If `options` is a number, assume it's the length and
// create a options object with length
if (typeof options === 'number') {
opts = {
length: options
};
}
else {
opts = options || {};
}
// Set `opts` defaults
opts.length = opts.length || stringLen;
opts.omission = opts.omission || opts.ellipsis || '...';
stringLenWithOmission = opts.length - opts.omission.length;
// Set the index to stop at for `string`
if (opts.seperator) {
if (opts.seperator instanceof RegExp) {
// If `seperator` is a regex
if (opts.seperator.global) {
opts.seperator = opts.seperator;
} else {
ignoreCase = opts.seperator.ignoreCase ? 'i' : ''
multiLine = opts.seperator.multiLine ? 'm' : '';
opts.seperator = new RegExp(opts.seperator.source,
'g' + ignoreCase + multiLine);
}
stringToWorkWith = str.substring(0, stringLenWithOmission + 1)
lastIndexOf = -1
nextStop = 0
while ((result = opts.seperator.exec(stringToWorkWith))) {
lastIndexOf = result.index;
opts.seperator.lastIndex = ++nextStop;
}
last = lastIndexOf;
}
else {
// Seperator is a String
last = str.lastIndexOf(opts.seperator, stringLenWithOmission);
}
// If the above couldn't be found, they'll default to -1 so,
// we need to just set it as `stringLenWithOmission`
if (last === -1) {
last = stringLenWithOmission;
}
}
else {
last = stringLenWithOmission;
}
if (stringLen < opts.length) {
return str;
}
else {
returnString = str.substring(0, last) + opts.omission;
returnString += callback ? callback() : '';
return returnString;
}
};
/**
@name string#truncateHTML
@public
@function
@return {String} Returns the HTML safe truncated string
@description Truncates a given `string` inside HTML tags after a specified `length` if string`
is longer than `length`. The last characters will be replaced with an `omission`
for a total length not exceeding `length`. If `callback` is given it will fire if
`string` is truncated. If `once` is true only the first string in the first HTML
tags will be truncated leaving the others as they were
@param {String} string The string to truncate
@param {Integer/Object} options Options for truncation, If options is an Integer it will be length
all Object options are the same as `truncate`
@param {Boolean} [options.once=false] If true, it will only be truncated once, otherwise the
truncation will loop through all text inside HTML tags
@param {Function} callback Callback is called only if a truncation is done
*/
this.truncateHTML = function(string, options, callback) {
var str = string || ''
, returnString = ''
, opts = options;
str = String(str);
// If `options` is a number assume it's the length and create a options object with length
if (typeof opts === 'number') {
var num = opts;
opts = {};
opts.length = num;
} else opts = opts || {};
// Set `default` options for HTML specifics
opts.once = opts.once || false;
var pat = /(<[^>]*>)/ // Patter for matching HTML tags
, arr = [] // Holds the HTML tags and content seperately
, truncated = false
, result = pat.exec(str)
, item
, firstPos
, lastPos
, i;
// Gather the HTML tags and content into the array
while(result) {
firstPos = result.index;
lastPos = pat.lastIndex;
if (firstPos !== 0) {
// Should be content not HTML tags
arr.push(str.substring(0, firstPos));
// Slice content from string
str = str.slice(firstPos);
}
arr.push(result[0]); // Push HTML tags
str = str.slice(result[0].length);
// Re-run the pattern on the new string
result = pat.exec(str);
}
if (str !== '') arr.push(str);
// Loop through array items appending the tags to the string,
// - and truncating the text then appending it to content
i = -1;
while(++i < arr.length) {
item = arr[i];
switch(true) {
// Closing tag
case item.indexOf('</') == 0:
returnString += item;
openTag = null;
break;
// Opening tag
case item.indexOf('<') == 0:
returnString += item;
openTag = item;
break;
// Normal text
default:
if (opts.once && truncated) {
returnString += item;
} else {
returnString += this.truncate(item, opts, callback);
truncated = true;
}
break;
}
}
return returnString;
};
/**
@name string#nl2br
@public
@function
@return {String} The string with converted newlines chars to br tags
@description Nl2br returns a string where all newline chars are turned
into line break HTML tags
@param {String} string The string to convert
*/
this.nl2br = function(string) {
var str = string || '';
str = String(str);
return str.replace(_NL,'<br />');
};
/**
@name string#snakeize
@public
@function
@return {String} The string in a snake_case version
@description Snakeize converts camelCase and CamelCase strings to snake_case strings
@param {String} string The string to convert to snake_case
@param {String} separ='_' The seperator to use
*/
this.snakeize = (function () {
// Only create regexes once on initial load
var repl = /([A-Z]+)/g
, lead = /^_/g;
return function (string, separ) {
var str = string || ''
, sep = separ || '_'
, leading = separ ? new RegExp('^' + sep, 'g') : lead;
str = String(str);
return str.replace(repl, sep + '$1').toLowerCase().
replace(leading, '');
};
}).call(this);
// Aliases
/**
@name string#underscorize
@public
@function
@return {String} The string in a underscorized version
@description Underscorize returns the given `string` converting camelCase and snakeCase to underscores
@param {String} string The string to underscorize
*/
this.underscorize = this.snakeize;
this.underscoreize = this.snakeize;
this.decamelize = this.snakeize;
/**
@name string#camelize
@public
@function
@return {String} The string in a camelCase version
@description Camelize takes a string and optional options and
returns a camelCase version of the given `string`
@param {String} string The string to convert to camelCase
@param {Object} options
@param {Boolean} [options.initialCap] If initialCap is true the returned
string will have a capitalized first letter
@param {Boolean} [options.leadingUnderscore] If leadingUnderscore os true then if
an underscore exists at the beggining
of the string, it will stay there.
Otherwise it'll be removed.
*/
this.camelize = (function () {
// Only create regex once on initial load
var repl = /[-_](\w)/g;
return function (string, options) {
var str = string || ''
, ret
, config = {
initialCap: false
, leadingUnderscore: false
}
, opts = options || {};
str = String(str);
// Backward-compat
if (typeof opts == 'boolean') {
config = {
initialCap: true
};
}
else {
core.mixin(config, opts);
}
ret = str.replace(repl, function (m, m1) {
return m1.toUpperCase();
});
if (config.leadingUnderscore & str.indexOf('_') === 0) {
ret = '_' + this.decapitalize(ret);
}
// If initialCap is true capitalize it
ret = config.initialCap ? this.capitalize(ret) : this.decapitalize(ret);
return ret;
};
}).call(this);
/**
@name string#decapitalize
@public
@function
@return {String} The string with the first letter decapitalized
@description Decapitalize returns the given string with the first letter uncapitalized.
@param {String} string The string to decapitalize
*/
this.decapitalize = function (string) {
var str = string || '';
str = String(str);
return str.substr(0, 1).toLowerCase() + str.substr(1);
};
/**
@name string#capitalize
@public
@function
@return {String} The string with the first letter capitalized
@description capitalize returns the given string with the first letter capitalized.
@param {String} string The string to capitalize
*/
this.capitalize = function (string) {
var str = string || '';
str = String(str);
return str.substr(0, 1).toUpperCase() + str.substr(1);
};
/**
@name string#dasherize
@public
@function
@return {String} The string in a dashed version
@description Dasherize returns the given `string` converting camelCase and snakeCase
to dashes or replace them with the `replace` character.
@param {String} string The string to dasherize
@param {String} replace='-' The character to replace with
*/
this.dasherize = function(string, replace) {
var repl = replace || '-'
return this.snakeize(string, repl);
};
/**
@name string#include
@public
@function
@return {Boolean} Returns true if the string is found in the string to search
@description Searches for a particular string in another string
@param {String} searchIn The string to search for the other string in
@param {String} searchFor The string to search for
*/
this.include = function (searchIn, searchFor) {
var str = searchFor;
if (!str && typeof string != 'string') {
return false;
}
str = String(str);
return (searchIn.indexOf(str) > -1);
};
/*
* getInflections(name<String>, initialCap<String>)
*
* Inflection returns an object that contains different inflections
* created from the given `name`
*/
/**
@name string#getInflections
@public
@function
@return {Object} A Object containing multiple different inflects for the given `name`
@description Inflection returns an object that contains different inflections
created from the given `name`
@param {String} string The string to create inflections from
@param {Object} options
@param {Boolean} [options.initialCap]
*/
this.getInflections = function (name, options) {
var opts = options || {}
, initialCap;
if (!name) {
return;
}
// Backward-compat
if (typeof opts == 'boolean') {
opts = {
initialCap: true
};
}
initialCap = opts.initialCap;
var self = this
, normalizedName = this.snakeize(name)
, nameSingular = inflection.singularize(normalizedName)
, namePlural = inflection.pluralize(normalizedName);
return {
// For filepaths or URLs
filename: {
// neil_peart
singular: nameSingular
// neil_pearts
, plural: namePlural
}
// Constructor names
, constructor: {
// NeilPeart
singular: self.camelize(nameSingular, {initialCap: true})
// NeilPearts
, plural: self.camelize(namePlural, {initialCap: true})
}
, property: {
// neilPeart
singular: self.camelize(nameSingular)
// neilPearts
, plural: self.camelize(namePlural)
}
};
};
// From Math.uuid.js, https://github.com/broofa/node-uuid
// Robert Kieffer (robert@broofa.com), MIT license
this.uuid = function(length, radix) {
var chars = _UUID_CHARS
, uuid = []
, r
, i;
radix = radix || chars.length;
if (length) {
// Compact form
i = -1;
while(++i < length) {
uuid[i] = chars[0 | Math.random()*radix];
}
} else {
// rfc4122, version 4 form
// rfc4122 requires these characters
uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
uuid[14] = '4';
// Fill in random data. At i==19 set the high bits of clock sequence as
// per rfc4122, sec. 4.1.5
i = -1;
while(++i < 36) {
if (!uuid[i]) {
r = 0 | Math.random()*16;
uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
}
}
}
return uuid.join('');
};
})();
module.exports = string;
|
var HelloWorldLayer = cc.Layer.extend({
sprite:null,
ctor:function () {
//////////////////////////////
// 1. super init first
this._super();
/////////////////////////////
// 2. add a menu item with "X" image, which is clicked to quit the program
// you may modify it.
// ask the window size
var size = cc.winSize;
// var mainscene = ccs.load(res.MainScene_json);
// this.addChild(mainscene.node);
// plugins
var mgr = Object.create(MyPluginsMgr);
mgr.init();
this.mgr = mgr;
// Example
cc.MenuItemFont.setFontName('arial');
cc.MenuItemFont.setFontSize(32);
var size = cc.director.getWinSize();
var y = size.height - 50
// AdColony
{
var item = new cc.MenuItemFont("AdColony: ");
var item1 = new cc.MenuItemFont("video", mgr.onAdColonyAd1, mgr);
var item2 = new cc.MenuItemFont("v4vc", mgr.onAdColonyAd2, mgr);
var menu = new cc.Menu(item, item1, item2);
menu.setPosition(size.width/2, y);
menu.alignItemsHorizontallyWithPadding(20);
this.addChild(menu)
}
// Chartboost
{
y -= 50
var item = new cc.MenuItemFont("Chartboost: ");
var item1 = new cc.MenuItemFont("default", mgr.onChartboostDefault, mgr);
var item2 = new cc.MenuItemFont("Level-Complete", mgr.onChartboostLC, mgr);
var menu = new cc.Menu(item, item1, item2);
menu.setPosition(size.width/2, y);
menu.alignItemsHorizontallyWithPadding(20);
this.addChild(menu)
}
// Flurry Analytics
{
y -= 50
var item = new cc.MenuItemFont("Flurry: ");
var item1 = new cc.MenuItemFont("test", mgr.onFlurryTest, mgr);
var menu = new cc.Menu(item, item1);
menu.setPosition(size.width/2, y);
menu.alignItemsHorizontallyWithPadding(20);
this.addChild(menu)
}
// Google Analytics
{
y -= 50
var item = new cc.MenuItemFont("GA: ");
var item1 = new cc.MenuItemFont("test", mgr.onGATest, mgr);
var menu = new cc.Menu(item, item1);
menu.setPosition(size.width/2, y);
menu.alignItemsHorizontallyWithPadding(20);
this.addChild(menu)
}
// IAP
{
y -= 50
var item = new cc.MenuItemFont("IAP: ");
var item1 = new cc.MenuItemFont("purchase", mgr.onIAPPurchase, mgr);
var menu = new cc.Menu(item, item1);
menu.setPosition(size.width/2, y);
menu.alignItemsHorizontallyWithPadding(20);
this.addChild(menu)
}
// Kochava
{
y -= 50
var item = new cc.MenuItemFont("Kochava: ");
var item1 = new cc.MenuItemFont("test", mgr.onKochavaTest, mgr);
var menu = new cc.Menu(item, item1);
menu.setPosition(size.width/2, y);
menu.alignItemsHorizontallyWithPadding(20);
this.addChild(menu)
}
// Tune
{
y -= 50
var item = new cc.MenuItemFont("Tune: ");
var item1 = new cc.MenuItemFont("test", mgr.onTuneTest, mgr);
var menu = new cc.Menu(item, item1);
menu.setPosition(size.width/2, y);
menu.alignItemsHorizontallyWithPadding(20);
this.addChild(menu)
}
// Vungle
{
y -= 50
var item = new cc.MenuItemFont("Vungle: ");
var item1 = new cc.MenuItemFont("video", mgr.onVungleVideo, mgr);
var item2 = new cc.MenuItemFont("reward", mgr.onVungleReward, mgr);
var menu = new cc.Menu(item, item1, item2);
menu.setPosition(size.width/2, y);
menu.alignItemsHorizontallyWithPadding(20);
this.addChild(menu)
}
// // Facebook
// {
// y -= 50
// var item = new cc.MenuItemFont("Facebook: ");
// var item1 = new cc.MenuItemFont("login", mgr.onFacebookLogin, mgr);
// var item2 = new cc.MenuItemFont("logout", mgr.onFacebookLogout, mgr);
// var item3 = new cc.MenuItemFont("check status", mgr.onFacebookCheckStatus, mgr);
// var item4 = new cc.MenuItemFont("shareLink", mgr.onFacebookShareLink, mgr);
// var item5 = new cc.MenuItemFont("dialogLink", mgr.onFacebookDialogLink, mgr);
// var menu = new cc.Menu(item, item1, item2, item3, item4, item5);
// menu.setPosition(size.width/2, y);
// menu.alignItemsHorizontallyWithPadding(20);
// this.addChild(menu)
// }
// // AgeCheq
// {
// y -= 50
// var item = new cc.MenuItemFont("AgeCheq: ");
// var item1 = new cc.MenuItemFont("check", mgr.onAgeCheqCheck, mgr);
// var menu = new cc.Menu(item, item1);
// menu.setPosition(size.width/2, y);
// menu.alignItemsHorizontallyWithPadding(20);
// this.addChild(menu)
// }
return true;
}
});
var HelloWorldScene = cc.Scene.extend({
onEnter:function () {
this._super();
var layer = new HelloWorldLayer();
this.addChild(layer);
}
});
|
import TransformerPass from "./transformer-pass";
import * as messages from "../messages";
import isFunction from "lodash/lang/isFunction";
import traverse from "../traversal";
import isObject from "lodash/lang/isObject";
import assign from "lodash/object/assign";
import * as acorn from "../../acorn";
import File from "./file";
import each from "lodash/collection/each";
/**
* This is the class responsible for normalising a transformers handlers
* as well as constructing a `TransformerPass` that is responsible for
* actually running the transformer over the provided `File`.
*/
export default class Transformer {
constructor(transformerKey: string, transformer: Object) {
transformer = assign({}, transformer);
var take = function (key) {
var val = transformer[key];
delete transformer[key];
return val;
};
this.manipulateOptions = take("manipulateOptions");
this.shouldVisit = take("shouldVisit");
this.metadata = take("metadata") || {};
this.parser = take("parser");
this.post = take("post");
this.pre = take("pre");
//
if (this.metadata.stage != null) {
this.metadata.optional = true;
}
//
this.handlers = this.normalize(transformer);
this.key = transformerKey;
//
if (!this.shouldVisit && !this.handlers.enter && !this.handlers.exit) {
var types = Object.keys(this.handlers);
this.shouldVisit = function (node) {
for (var i = 0; i < types.length; i++) {
if (node.type === types[i]) return true;
}
return false;
};
}
}
normalize(transformer: Object): Object {
if (isFunction(transformer)) {
transformer = { ast: transformer };
}
traverse.explode(transformer);
each(transformer, (fns, type) => {
// hidden property
if (type[0] === "_") {
this[type] = fns;
return;
}
if (type === "enter" || type === "exit") return;
if (isFunction(fns)) fns = { enter: fns };
if (!isObject(fns)) return;
if (!fns.enter) fns.enter = function () { };
if (!fns.exit) fns.exit = function () { };
transformer[type] = fns;
});
return transformer;
}
buildPass(file: File): TransformerPass {
// validate Transformer instance
if (!(file instanceof File)) {
throw new TypeError(messages.get("transformerNotFile", this.key));
}
return new TransformerPass(file, this);
}
}
|
import { storiesOf } from "@kadira/storybook";
import backgrounds from "react-storybook-addon-backgrounds";
import centered from "../../../.storybook/decorators/centered";
import defaultColors from "../../defaults";
import IconSocial, { IconSocialFilled } from "./index";
const story = storiesOf("Social Icons", module)
.addDecorator(centered)
.addDecorator(backgrounds(defaultColors()));
story.add(
"Unfilled",
() => (
<div className="text-center one-whole">
<IconSocial className="icon--facebook" />
<IconSocial className="icon--google" />
<IconSocial className="icon--twitter" />
<IconSocial className="icon--instagram" />
</div>
)
);
story.add(
"Filled",
() => (
<div className="text-center one-whole">
<IconSocialFilled className="icon--facebook" />
<IconSocialFilled className="icon--google" />
<IconSocialFilled className="icon--twitter" />
<IconSocialFilled className="icon--instagram" />
</div>
)
);
|
/**
* Loader, contains list of Controllers module components
*/
define(['./home-ctrl'], function() {
'use strict';
});
|
// [VexFlow](http://vexflow.com) - Copyright (c) Mohit Muthanna 2010.
//
// This class implements a musical system, which is a collection of staves,
// each which can have one or more voices. All voices across all staves in
// the system are formatted together.
import { Element } from './element';
import { Factory } from './factory';
import { Formatter } from './formatter';
import { Note } from './note';
function setDefaults(params, defaults) {
const default_options = defaults.options;
params = Object.assign(defaults, params);
params.options = Object.assign(default_options, params.options);
return params;
}
export class System extends Element {
constructor(params = {}) {
super();
this.setAttribute('type', 'System');
this.setOptions(params);
this.parts = [];
}
setOptions(options = {}) {
this.options = setDefaults(options, {
x: 10,
y: 10,
width: 500,
connector: null,
spaceBetweenStaves: 12, // stave spaces
factory: null,
debugFormatter: false,
formatIterations: 0, // number of formatter tuning steps
options: {},
});
this.factory = this.options.factory || new Factory({ renderer: { el: null } });
}
setContext(context) {
super.setContext(context);
this.factory.setContext(context);
return this;
}
addConnector(type = 'double') {
this.connector = this.factory.StaveConnector({
top_stave: this.parts[0].stave,
bottom_stave: this.parts[this.parts.length - 1].stave,
type,
});
return this.connector;
}
addStave(params) {
params = setDefaults(params, {
stave: null,
voices: [],
spaceAbove: 0, // stave spaces
spaceBelow: 0, // stave spaces
debugNoteMetrics: false,
options: {},
});
if (!params.stave) {
const options = { left_bar: false };
params.stave = this.factory.Stave({
x: this.options.x,
y: this.options.y,
width: this.options.width,
options,
});
}
params.voices.forEach(voice =>
voice
.setContext(this.context)
.setStave(params.stave)
.getTickables()
.forEach(tickable => tickable.setStave(params.stave))
);
this.parts.push(params);
return params.stave;
}
format() {
const formatter = new Formatter();
this.formatter = formatter;
let y = this.options.y;
let startX = 0;
let allVoices = [];
const debugNoteMetricsYs = [];
// Join the voices for each stave.
this.parts.forEach(part => {
y = y + part.stave.space(part.spaceAbove);
part.stave.setY(y);
formatter.joinVoices(part.voices);
y = y + part.stave.space(part.spaceBelow);
y = y + part.stave.space(this.options.spaceBetweenStaves);
if (part.debugNoteMetrics) {
debugNoteMetricsYs.push({ y, voice: part.voices[0] });
y += 15;
}
allVoices = allVoices.concat(part.voices);
startX = Math.max(startX, part.stave.getNoteStartX());
});
// Update the start position of all staves.
this.parts.forEach(part => part.stave.setNoteStartX(startX));
const justifyWidth = this.options.width - (startX - this.options.x) - Note.STAVEPADDING;
formatter.format(allVoices, justifyWidth);
for (let i = 0; i < this.options.formatIterations; i++) {
formatter.tune();
}
this.startX = startX;
this.debugNoteMetricsYs = debugNoteMetricsYs;
this.lastY = y;
}
draw() {
// Render debugging information, if requested.
const ctx = this.checkContext();
this.setRendered();
if (this.options.debugFormatter) {
Formatter.plotDebugging(ctx, this.formatter, this.startX, this.options.y, this.lastY);
}
this.debugNoteMetricsYs.forEach(d => {
d.voice.getTickables().forEach(note => Note.plotMetrics(ctx, note, d.y));
});
}
}
|
import Ember from 'ember';
import app from '../app';
import { normalizeURLSafeBase64 } from '../utils/base64';
export default Ember.Controller.extend({
queryParams: {access_key: null},
access_key: null,
modelChanged: function() {
// TODO: unsubscribe
app.pubnub.subscribe({
channel: this.get('model.dashboard_channel'),
message: function(message){
if ('file' in message) {
this.store.push(this.store.normalize('file', message['file']));
}
if ('break' in message) {
this.store.push(this.store.normalize('break', message['break']));
}
}.bind(this)
});
}.observes('model'),
lastBreakChanged: function() {
this.get('model.lastBreak').then(function () {
// TODO: avoid delay issue, cancel outdate schedule
Ember.run.scheduleOnce('afterRender', this, this.afterRenderEvent);
}.bind(this));
}.observes('model.lastBreak'),
lastFileChanged: function () {
this.get('model.lastFile').then(function () {
// TODO: avoid delay issue, cancel outdate schedule
Ember.run.scheduleOnce('afterRender', this, this.afterRenderEvent);
}.bind(this));
}.observes('model.lastFile'),
currentCodeChanged: function () {
Ember.run.scheduleOnce('afterRender', this, this.afterRenderEvent);
}.observes('model.currentCode'),
afterRenderEvent: function () {
Ember.$('.line-highlight').removeClass('line-highlight');
var lineno = this.get('model.lastBreak').get('lineno');
var currentLine = Ember.$(`#line-${lineno}`);
if (!currentLine.length) {
return;
}
currentLine.addClass('line-highlight');
Ember.$('html, body').animate({
scrollTop: currentLine.offset().top - (Ember.$(window).height() / 2)
}, 500);
},
needsAccessKeyChanged: function () {
var needsAccessKey = this.get('model.needsAccessKey');
if (!needsAccessKey) {
Ember.$('#session-access-key-modal').modal('hide');
return;
}
Ember.run.scheduleOnce('afterRender', this, function () {
Ember.$('#session-access-key-modal').modal();
});
}.observes('model.needsAccessKey'),
inputAccessKeyChanged: function () {
this.set('accessKeyError', null);
}.observes('inputAccessKey'),
accessKeyError: null,
accessKeyURL: Ember.computed('', function() {
if (Ember.isNone(this.get('model.accessKey'))) {
return null;
}
var baseURL = window.location.href.split('#')[0];
return baseURL + this.get('target').generate(
'session',
this.get('model'),
{
queryParams: {access_key: this.get('model.accessKey')}
}
);
}),
paramAccessKeyChanged: function() {
var self = this;
var session = this.get('model');
if (Ember.isNone(session)) {
return;
}
var accessKey = this.get('access_key');
if (!Ember.isNone(accessKey)) {
accessKey = normalizeURLSafeBase64(accessKey);
if (session.validateAccessKey(accessKey)) {
session.set('accessKey', accessKey);
this.set('access_key', null);
self.transitionToRoute('session', session);
}
}
}.observes('access_key', 'model'),
actions: {
returnFunction: function(){
this.get('model').returnFunc();
},
next: function(){
this.get('model').next();
},
step: function(){
this.get('model').step();
},
resume: function(){
this.get('model').resume();
},
decrypt: function(){
var inputAccessKey = normalizeURLSafeBase64(this.get('inputAccessKey'));
if (Ember.isBlank(inputAccessKey)) {
this.set('accessKeyError', 'Cannot be blank');
console.log('Blank access key');
return;
}
if (!this.get('model').validateAccessKey(inputAccessKey)) {
this.set('accessKeyError', 'Bad access key');
console.log('Bad access key');
return;
}
this.get('model').set('accessKey', inputAccessKey);
Ember.$('#session-access-key-modal').modal('hide');
}
}
});
|
var searchData=
[
['plasmid_2epy',['plasmid.py',['../plasmid_8py.html',1,'']]]
];
|
/*===
0.00
1.00
1.00
0.9999
0.99990
1.23457e+7
1.234568e+7
12345678
12345678.0
8.76543e+7
8.765432e+7
87654321
87654321.0
5.556e+4
55555
4.444e+4
44444
1.000e+5
99999
0
0
0.0
0.00
0
0
0.0
0.00
===*/
function precisionTest() {
function test(x, n) {
print(new Number(x).toPrecision(n));
}
test(0, 3);
test(1, 3);
test(0.9999, 3);
test(0.9999, 4);
test(0.9999, 5);
test(12345678, 6); // rounds up
test(12345678, 7); // rounds up
test(12345678, 8);
test(12345678, 9);
test(87654321, 6); // rounds down
test(87654321, 7); // rounds down
test(87654321, 8);
test(87654321, 9);
test(55555, 4); // rounds up
test(55555, 5);
test(44444, 4); // rounds down
test(44444, 5);
test(99999, 4); // rounds up, carries
test(99999, 5);
// NB: precision=0 is a RangeError
test(+0, undefined); // -> ToString()
test(+0, 1);
test(+0, 2);
test(+0, 3);
test(-0, undefined); // -> ToString()
test(-0, 1);
test(-0, 2);
test(-0, 3);
}
try {
precisionTest();
} catch (e) {
print(e);
}
|
app.directive('restrict', function($parse) {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, iElement, iAttrs, controller) {
scope.$watch(iAttrs.ngModel, function(value) {
if (!value) {
return;
}
if (value != undefined){
$parse(iAttrs.ngModel).assign(scope, parseInt(value));
}
});
}
}
});
app.directive("ngTap", function() {
return function($scope, $element, $attributes) {
var tapped;
tapped = false;
$element.bind("click", function() {
if (!tapped) {
return $scope.$apply($attributes["ngTap"]);
}
});
$element.bind("touchstart", function(event) {
return tapped = true;
});
$element.bind("touchmove", function(event) {
tapped = false;
return event.stopImmediatePropagation();
});
return $element.bind("touchend", function(event) {
if (tapped) {
$scope.$apply($attributes["ngTap"]);
return event.stopImmediatePropagation();
}
});
};
});
app.filter('startFrom', function() {
return function(input, start) {
start = +start; //parse to int
return input.slice(start);
}
});
app.filter('scoreRange', function() {
return function(input) {
for (var i=1; i<=180; i++){
if ( i <= 171 || i == 174 || i == 177 || i == 180 ){
input.push(i);
}
}
return input;
};
});
app.filter('range', function() {
return function(input, total) {
total = parseInt(total);
for (var i=0; i<total; i++)
input.push(i);
return input;
};
}); |
import cx from 'classnames'
import PropTypes from 'prop-types'
import React from 'react'
import {
customPropTypes,
getUnhandledProps,
META,
useValueAndKey,
} from '../../lib'
import TableCell from './TableCell'
/**
* A table can have a header cell.
*/
function TableHeaderCell(props) {
const { as, className, sorted } = props
const classes = cx(
useValueAndKey(sorted, 'sorted'),
className,
)
const rest = getUnhandledProps(TableHeaderCell, props)
return <TableCell {...rest} as={as} className={classes} />
}
TableHeaderCell._meta = {
name: 'TableHeaderCell',
type: META.TYPES.COLLECTION,
parent: 'Table',
}
TableHeaderCell.propTypes = {
/** An element type to render as (string or function). */
as: customPropTypes.as,
/** Additional classes. */
className: PropTypes.string,
/** A header cell can be sorted in ascending or descending order. */
sorted: PropTypes.oneOf(['ascending', 'descending']),
}
TableHeaderCell.defaultProps = {
as: 'th',
}
export default TableHeaderCell
|
/**
* @class SelectField
* @extends FormField
* @param config {Object} Configuration object
* @constructor
* @description A select field node
*/
Y.SelectField = Y.Base.create('select-field', Y.ChoiceField, [Y.WidgetParent, Y.WidgetChild], {
FIELD_TEMPLATE : '<select></select>',
/**
* @property SelectField.DEFAULT_OPTION_TEXT
* @type String
* @description The display title of the default choice in the select box
*/
DEFAULT_OPTION_TEXT : 'Choose one',
/**
* @method _renderFieldNode
* @protected
* @description Draws the select node into the contentBox
*/
_renderFieldNode: function() {
Y.SelectField.superclass.constructor.superclass._renderFieldNode.apply(this, arguments);
this._renderOptionNodes();
},
/**
* @method _renderOptionNodes
* @protected
* @description Renders the option nodes into the select node
*/
_renderOptionNodes: function() {
var choices = this.get('choices'),
elOption;
// Create the "Choose one" option
if (this.get('useDefaultOption') === true) {
elOption = Y.Node.create(Y.SelectField.OPTION_TEMPLATE);
this._fieldNode.appendChild(elOption);
}
Y.Array.each(choices,
function(c, i, a) {
elOption = Y.Node.create(Y.SelectField.OPTION_TEMPLATE);
this._fieldNode.appendChild(elOption);
},
this);
},
/**
* @method _syncFieldNode
* @protected
* @description Syncs the select node with the instance attributes
*/
_syncFieldNode: function() {
Y.SelectField.superclass.constructor.superclass._syncFieldNode.apply(this, arguments);
this._fieldNode.setAttrs({
size : this.get('size'),
multiple: (this.get('multi') === true ? 'multiple': '')
});
},
/**
* @method _syncOptionNodes
* @protected
* @description Syncs the option nodes with the choices attribute
*/
_syncOptionNodes: function() {
var choices = this.get('choices') || [],
contentBox = this.get('contentBox'),
options = contentBox.all('option'),
useDefaultOption = this.get('useDefaultOption'),
currentVal = this.get('value');
if (useDefaultOption === true) {
choices.unshift({
label : this.DEFAULT_OPTION_TEXT,
value: ''
});
}
options.each(function(node, index, nodeList) {
var label = choices[index].label,
val = choices[index].value;
node.setAttrs({
innerHTML: label,
value: val
});
if (currentVal == val) {
node.setAttrs({
selected: true,
defaultSelected: true
});
}
},
this);
if (!currentVal && !useDefaultOption && choices[0]) {
this.set('value', choices[0].value);
}
},
/**
* @method _afterChoiceChange
* @description When the available options for the select field change,
* the old ones are removed and the new ones are rendered.
*/
_afterChoicesChange: function(evt) {
var options = this._fieldNode.all("option");
options.remove();
this._renderOptionNodes();
this._syncOptionNodes();
},
/**
* @method clear
* @description Restores the selected option to the default
*/
clear: function() {
this._fieldNode.value = '';
},
bindUI: function() {
Y.SelectField.superclass.constructor.superclass.bindUI.apply(this, arguments);
this.after('choicesChange', this._afterChoicesChange);
},
syncUI: function() {
Y.SelectField.superclass.syncUI.apply(this, arguments);
this._syncOptionNodes();
}
},
{
/**
* @property SelectField.OPTION_TEMPLATE
* @type String
* @description Template used to draw an option node
*/
OPTION_TEMPLATE: '<option></option>',
ATTRS: {
/**
* @attribute useDefaultOption
* @type Boolean
* @default true
* @description If true, the first option will use the DEFAULT_OPTION_TEXT
* to create a blank option
*/
useDefaultOption: {
validator: Y.Lang.isBoolean,
value: true
},
/**
* @attribute choices
* @type Array
* @description The choices to render into this field
*/
choices: {
validator: function(val) {
if (this.get("useDefaultOption") &&
Y.Lang.isArray(val) &&
val.length === 0) {
// Empty arrays are okay if useDefaultOption is 'true'
return true;
} else {
return this._validateChoices(val);
}
}
},
/**
* @attribute size
* @type String
* @default 0
* @description Value of 'size' attribute of the select element.
*/
size : {
validator : Y.Lang.isString,
value : '0'
}
}
});
|
module.exports={A:{A:{"2":"H D G E A B EB"},B:{"2":"C p x J L N I"},C:{"2":"0 1 2 3 4 5 6 8 9 YB BB F K H D G E A B C p x J L N I O P Q R S T U V W X Y Z b c d e f g h i j k l m n o M q r s t u v w y WB QB"},D:{"1":"GB HB IB","2":"0 1 2 3 4 F K H D G E A B C p x J L N I O P Q R S T U V W X Y Z b c d e f g h i j k l m n o M q r s t u v w","194":"5 6 8 9 y KB aB FB a"},E:{"2":"F K H D G E A B C JB CB LB MB NB OB PB z RB"},F:{"2":"0 7 E B C J L N I O P Q R S T U V W X Y Z b c d e f g h i j k l m n o M q r s t u v w SB TB UB VB z AB XB"},G:{"2":"G CB ZB DB bB cB dB eB fB gB hB iB jB kB"},H:{"2":"lB"},I:{"2":"BB F a mB nB oB pB DB qB rB"},J:{"2":"D A"},K:{"2":"7 A B C M z AB"},L:{"194":"a"},M:{"2":"y"},N:{"2":"A B"},O:{"2":"sB"},P:{"2":"F K tB"},Q:{"2":"uB"},R:{"2":"vB"}},B:4,C:"Magnetometer"};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.