code
stringlengths 2
1.05M
|
|---|
/*eslint-disable no-console */
'use strict';
var ng = require('../helpers/ng');
var tmp = require('../helpers/tmp');
var Promise = require('angular-cli/ember-cli/lib/ext/promise');
var fs = require('fs');
var path = require('path');
var chai = require('chai');
var sinon = require('sinon');
var ExecStub = require('../helpers/exec-stub');
var https = require('https');
var SilentError = require('silent-error');
const expect = chai.expect;
const fsWriteFile = Promise.denodeify(fs.writeFile);
const fsMkdir = Promise.denodeify(fs.mkdir);
describe('Acceptance: ng github-pages:deploy', function() {
let execStub;
let project = 'foo',
initialBranch = 'master',
ghPagesBranch = 'gh-pages',
message = 'new gh-pages version',
remote = 'origin git@github.com:username/project.git (fetch)';
function setupDist() {
return fsMkdir('./dist')
.then(() => {
let indexHtml = path.join(process.cwd(), 'dist', 'index.html');
let indexData = `<title>project</title>\n<base href="/">`;
return fsWriteFile(indexHtml, indexData, 'utf8');
});
}
beforeEach(function() {
this.timeout(10000);
return tmp.setup('./tmp')
.then(() => process.chdir('./tmp'))
.then(() => ng(['new', project, '--skip-npm']))
.then(() => setupDist())
.finally(() => execStub = new ExecStub());
});
afterEach(function() {
this.timeout(10000);
return tmp.teardown('./tmp')
.then(() => expect(execStub.hasFailed()).to.be.false)
.then(() => expect(execStub.hasEmptyStack()).to.be.true)
.finally(() => execStub.restore());
});
it('should fail with uncommited changes', function() {
this.timeout(10000);
execStub.addExecSuccess('git status --porcelain', 'M dir/file.ext');
return ng(['github-pages:deploy', '--skip-build'])
.then(() => {
throw new SilentError('Should fail with uncommited changes but passing.');
}, (ret) => {
expect(ret.name).to.equal('SilentError');
expect(ret.isSilentError).to.equal(true);
});
});
it('should deploy with defaults to existing remote', function () {
execStub.addExecSuccess('git status --porcelain')
.addExecSuccess('git rev-parse --abbrev-ref HEAD', initialBranch)
.addExecSuccess('git remote -v', remote)
.addExecSuccess(`git checkout ${ghPagesBranch}`)
.addExecSuccess('git ls-files')
.addExecSuccess('git rm -r ')
.addExecSuccess('git add .')
.addExecSuccess(`git commit -m "${message}"`)
.addExecSuccess(`git checkout ${initialBranch}`)
.addExecSuccess(`git push origin ${ghPagesBranch}:${ghPagesBranch}`)
.addExecSuccess('git remote -v', remote);
return ng(['github-pages:deploy', '--skip-build']);
});
it('should deploy with token and username', function () {
let token = 'token',
username = 'bar';
execStub.addExecSuccess('git status --porcelain')
.addExecSuccess('git rev-parse --abbrev-ref HEAD', initialBranch)
.addExecSuccess('git remote -v', remote)
.addExecSuccess(`git checkout ${ghPagesBranch}`)
.addExecSuccess('git ls-files')
.addExecSuccess('git rm -r ')
.addExecSuccess('git add .')
.addExecSuccess(`git commit -m "${message}"`)
.addExecSuccess(`git checkout ${initialBranch}`)
.addExecSuccess(`git push https://${token}@github.com/${username}/${project}.git ${ghPagesBranch}:${ghPagesBranch}`)
.addExecSuccess('git remote -v', remote);
return ng(['github-pages:deploy', '--skip-build', `--gh-token=${token}`, `--gh-username=${username}`]);
})
it('should deploy with token only', function () {
let token = 'token';
execStub.addExecSuccess('git status --porcelain')
.addExecSuccess('git rev-parse --abbrev-ref HEAD', initialBranch)
.addExecSuccess('git remote -v', remote)
.addExecSuccess(`git checkout ${ghPagesBranch}`)
.addExecSuccess('git ls-files')
.addExecSuccess('git rm -r ')
.addExecSuccess('git add .')
.addExecSuccess(`git commit -m "${message}"`)
.addExecSuccess(`git checkout ${initialBranch}`)
.addExecSuccess('git remote -v', remote)
.addExecSuccess(`git push https://${token}@github.com/username/${project}.git ${ghPagesBranch}:${ghPagesBranch}`)
.addExecSuccess('git remote -v', remote);
return ng(['github-pages:deploy', '--skip-build', `--gh-token=${token}`]);
});
it('should deploy with changed defaults', function() {
let userPageBranch = 'master',
message = 'not new gh-pages version';
execStub.addExecSuccess('git status --porcelain')
.addExecSuccess('git rev-parse --abbrev-ref HEAD', initialBranch)
.addExecSuccess('git remote -v', remote)
.addExecSuccess(`git checkout ${ghPagesBranch}`)
.addExecSuccess('git ls-files')
.addExecSuccess('git rm -r ')
.addExecSuccess('git add .')
.addExecSuccess(`git commit -m "${message}"`)
.addExecSuccess(`git checkout ${initialBranch}`)
.addExecSuccess(`git push origin ${ghPagesBranch}:${userPageBranch}`)
.addExecSuccess('git remote -v', remote);
return ng(['github-pages:deploy', '--skip-build', `--message=${message}`, '--user-page']);
});
it('should create branch if needed', function() {
execStub.addExecSuccess('git status --porcelain')
.addExecSuccess('git rev-parse --abbrev-ref HEAD', initialBranch)
.addExecSuccess('git remote -v', remote)
.addExecError(`git checkout ${ghPagesBranch}`)
.addExecSuccess(`git checkout --orphan ${ghPagesBranch}`)
.addExecSuccess('git rm --cached -r .')
.addExecSuccess('git add .gitignore')
.addExecSuccess('git clean -f -d')
.addExecSuccess(`git commit -m \"initial ${ghPagesBranch} commit\"`)
.addExecSuccess('git ls-files')
.addExecSuccess('git rm -r ')
.addExecSuccess('git add .')
.addExecSuccess(`git commit -m "${message}"`)
.addExecSuccess(`git checkout ${initialBranch}`)
.addExecSuccess(`git push origin ${ghPagesBranch}:${ghPagesBranch}`)
.addExecSuccess('git remote -v', remote);
return ng(['github-pages:deploy', '--skip-build']);
});
it('should create repo if needed', function() {
let noRemote = '',
token = 'token',
username = 'username';
execStub.addExecSuccess('git status --porcelain')
.addExecSuccess('git rev-parse --abbrev-ref HEAD', initialBranch)
.addExecSuccess('git remote -v', noRemote)
.addExecSuccess(`git remote add origin git@github.com:${username}/${project}.git`)
.addExecSuccess(`git push -u https://${token}@github.com/${username}/${project}.git ${initialBranch}`)
.addExecSuccess(`git checkout ${ghPagesBranch}`)
.addExecSuccess('git ls-files')
.addExecSuccess('git rm -r ')
.addExecSuccess('git add .')
.addExecSuccess(`git commit -m "${message}"`)
.addExecSuccess(`git checkout ${initialBranch}`)
.addExecSuccess(`git push https://${token}@github.com/${username}/${project}.git ${ghPagesBranch}:${ghPagesBranch}`)
.addExecSuccess('git remote -v', remote);
var httpsStub = sinon.stub(https, 'request', httpsRequestStubFunc);
function httpsRequestStubFunc(req) {
let responseCb;
let expectedPostData = JSON.stringify({
'name': project
});
let expectedReq = {
hostname: 'api.github.com',
port: 443,
path: '/user/repos',
method: 'POST',
headers: {
'Authorization': `token ${token}`,
'Content-Type': 'application/json',
'Content-Length': expectedPostData.length,
'User-Agent': 'angular-cli-github-pages'
}
}
expect(req).to.eql(expectedReq);
return {
on: (event, cb) => responseCb = cb,
write: (postData) => expect(postData).to.eql(expectedPostData),
end: () => responseCb({ statusCode: 201 })
}
}
return ng(['github-pages:deploy', '--skip-build', `--gh-token=${token}`,
`--gh-username=${username}`])
.then(() => httpsStub.restore());
});
it('should stop deploy if create branch fails', function() {
let noRemote = '',
token = 'token',
username = 'username';
execStub.addExecSuccess('git status --porcelain')
.addExecSuccess('git rev-parse --abbrev-ref HEAD', initialBranch)
.addExecSuccess('git remote -v', noRemote);
var httpsStub = sinon.stub(https, 'request', httpsRequestStubFunc);
function httpsRequestStubFunc(req) {
let responseCb;
let expectedPostData = JSON.stringify({
'name': project
});
let expectedReq = {
hostname: 'api.github.com',
port: 443,
path: '/user/repos',
method: 'POST',
headers: {
'Authorization': `token ${token}`,
'Content-Type': 'application/json',
'Content-Length': expectedPostData.length,
'User-Agent': 'angular-cli-github-pages'
}
}
expect(req).to.eql(expectedReq);
return {
on: (event, cb) => responseCb = cb,
write: (postData) => expect(postData).to.eql(expectedPostData),
end: () => responseCb({ statusCode: 401, statusMessage: 'Unauthorized' })
}
}
return ng(['github-pages:deploy', '--skip-build', `--gh-token=${token}`,
`--gh-username=${username}`])
.then(() => {
throw new SilentError('Should not pass the deploy.');
}, (ret) => {
expect(ret.name).to.equal('SilentError');
expect(ret.isSilentError).to.equal(true);
})
.then(() => httpsStub.restore());
});
it('should fail gracefully when checkout has permissions failure', function() {
execStub.addExecSuccess('git status --porcelain')
.addExecSuccess('git rev-parse --abbrev-ref HEAD', initialBranch)
.addExecSuccess('git remote -v', remote)
.addExecSuccess(`git checkout ${ghPagesBranch}`)
.addExecSuccess('git ls-files')
.addExecSuccess('git rm -r ')
.addExecSuccess('git add .')
.addExecSuccess(`git commit -m "${message}"`)
.addExecError(`git checkout ${initialBranch}`, 'error: cannot stat \'src/client\': Permission denied');
return ng(['github-pages:deploy', '--skip-build'])
.then(() => {
throw new SilentError('Should not pass the deploy.');
}, (ret) => {
expect(ret.name).to.equal('SilentError');
expect(ret.isSilentError).to.equal(true);
expect(ret.message).to.contain('There was a permissions error');
});
});
});
|
define([
'underscore',
'backbone',
'snapjs',
'text!template_path/HomeTemplate.html'
], function(_, Backbone, Snap, HomeTemplate) {
var HomeView = Backbone.View.extend({
initialize: function(options) {
this.render = _.bind(this.render, this);
},
render: function() {
_.templateSettings.variable = "data";
console.info("Rendering Home")
var userDetail = App.globalUserData.userInfo;
var compiledTemplate = _.template(HomeTemplate, userDetail);
$(this.el).html(compiledTemplate);
$(this.el).hide();
// Modify the model of the sidebar now to trigger a render of new data
App.SideBarView.sideBarData.resetSettings();
App.SideBarView.sideBarData.set("demo", true)
return this;
},
close: function(closedCallback) {
$(this.el).fadeOut(300, function() {
this.remove();
});
closedCallback();
},
onShow: function() {
$(this.el).fadeIn();
}
});
return HomeView;
});
|
/*global define*/
define([
'./AxisAlignedBoundingBox',
'./Cartesian2',
'./Cartesian3',
'./defaultValue',
'./defined',
'./defineProperties',
'./DeveloperError',
'./Ellipsoid',
'./IntersectionTests',
'./Matrix4',
'./Plane',
'./Ray',
'./Transforms'
], function(
AxisAlignedBoundingBox,
Cartesian2,
Cartesian3,
defaultValue,
defined,
defineProperties,
DeveloperError,
Ellipsoid,
IntersectionTests,
Matrix4,
Plane,
Ray,
Transforms) {
"use strict";
/**
* A plane tangent to the provided ellipsoid at the provided origin.
* If origin is not on the surface of the ellipsoid, it's surface projection will be used.
* If origin as at the center of the ellipsoid, an exception will be thrown.
* @alias EllipsoidTangentPlane
* @constructor
*
* @param {Ellipsoid} ellipsoid The ellipsoid to use.
* @param {Cartesian3} origin The point on the surface of the ellipsoid where the tangent plane touches.
*
* @exception {DeveloperError} origin must not be at the center of the ellipsoid.
*/
var EllipsoidTangentPlane = function(origin, ellipsoid) {
//>>includeStart('debug', pragmas.debug);
if (!defined(origin)) {
throw new DeveloperError('origin is required.');
}
//>>includeEnd('debug');
ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
origin = ellipsoid.scaleToGeodeticSurface(origin);
//>>includeStart('debug', pragmas.debug);
if (!defined(origin)) {
throw new DeveloperError('origin must not be at the center of the ellipsoid.');
}
//>>includeEnd('debug');
var eastNorthUp = Transforms.eastNorthUpToFixedFrame(origin, ellipsoid);
this._ellipsoid = ellipsoid;
this._origin = origin;
this._xAxis = Cartesian3.fromCartesian4(Matrix4.getColumn(eastNorthUp, 0));
this._yAxis = Cartesian3.fromCartesian4(Matrix4.getColumn(eastNorthUp, 1));
var normal = Cartesian3.fromCartesian4(Matrix4.getColumn(eastNorthUp, 2));
this._plane = Plane.fromPointNormal(origin, normal);
};
defineProperties(EllipsoidTangentPlane.prototype, {
/**
* Gets the ellipsoid.
* @memberof EllipsoidTangentPlane.prototype
* @type {Ellipsoid}
*/
ellipsoid : {
get : function() {
return this._ellipsoid;
}
},
/**
* Gets the origin.
* @memberof EllipsoidTangentPlane.prototype
* @type {Cartesian3}
*/
origin : {
get : function() {
return this._origin;
}
}
});
var tmp = new AxisAlignedBoundingBox();
/**
* Creates a new instance from the provided ellipsoid and the center
* point of the provided Cartesians.
*
* @param {Ellipsoid} ellipsoid The ellipsoid to use.
* @param {Cartesian3} cartesians The list of positions surrounding the center point.
*/
EllipsoidTangentPlane.fromPoints = function(cartesians, ellipsoid) {
//>>includeStart('debug', pragmas.debug);
if (!defined(cartesians)) {
throw new DeveloperError('cartesians is required.');
}
//>>includeEnd('debug');
var box = AxisAlignedBoundingBox.fromPoints(cartesians, tmp);
return new EllipsoidTangentPlane(box.center, ellipsoid);
};
var projectPointOntoPlaneRay = new Ray();
var projectPointOntoPlaneCartesian3 = new Cartesian3();
/**
* Computes the projection of the provided 3D position onto the 2D plane.
*
* @param {Cartesian3} cartesian The point to project.
* @param {Cartesian2} [result] The object onto which to store the result.
* @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if none was provided.
*/
EllipsoidTangentPlane.prototype.projectPointOntoPlane = function(cartesian, result) {
//>>includeStart('debug', pragmas.debug);
if (!defined(cartesian)) {
throw new DeveloperError('cartesian is required.');
}
//>>includeEnd('debug');
var ray = projectPointOntoPlaneRay;
ray.origin = cartesian;
Cartesian3.normalize(cartesian, ray.direction);
var intersectionPoint = IntersectionTests.rayPlane(ray, this._plane, projectPointOntoPlaneCartesian3);
if (!defined(intersectionPoint)) {
Cartesian3.negate(ray.direction, ray.direction);
intersectionPoint = IntersectionTests.rayPlane(ray, this._plane, projectPointOntoPlaneCartesian3);
}
if (defined(intersectionPoint)) {
var v = Cartesian3.subtract(intersectionPoint, this._origin, intersectionPoint);
var x = Cartesian3.dot(this._xAxis, v);
var y = Cartesian3.dot(this._yAxis, v);
if (!defined(result)) {
return new Cartesian2(x, y);
}
result.x = x;
result.y = y;
return result;
}
return undefined;
};
/**
* Computes the projection of the provided 3D positions onto the 2D plane.
*
* @param {Cartesian3[]} cartesians The array of points to project.
* @param {Cartesian2[]} [result] The array of Cartesian2 instances onto which to store results.
* @returns {Cartesian2[]} The modified result parameter or a new array of Cartesian2 instances if none was provided.
*/
EllipsoidTangentPlane.prototype.projectPointsOntoPlane = function(cartesians, result) {
//>>includeStart('debug', pragmas.debug);
if (!defined(cartesians)) {
throw new DeveloperError('cartesians is required.');
}
//>>includeEnd('debug');
if (!defined(result)) {
result = [];
}
var count = 0;
var length = cartesians.length;
for ( var i = 0; i < length; i++) {
var p = this.projectPointOntoPlane(cartesians[i], result[count]);
if (defined(p)) {
result[count] = p;
count++;
}
}
result.length = count;
return result;
};
var projectPointsOntoEllipsoidScratch = new Cartesian3();
/**
* Computes the projection of the provided 2D positions onto the 3D ellipsoid.
*
* @param {Cartesian2[]} cartesians The array of points to project.
* @param {Cartesian3[]} [result] The array of Cartesian3 instances onto which to store results.
* @returns {Cartesian3[]} The modified result parameter or a new array of Cartesian3 instances if none was provided.
*/
EllipsoidTangentPlane.prototype.projectPointsOntoEllipsoid = function(cartesians, result) {
//>>includeStart('debug', pragmas.debug);
if (!defined(cartesians)) {
throw new DeveloperError('cartesians is required.');
}
//>>includeEnd('debug');
var length = cartesians.length;
if (!defined(result)) {
result = new Array(length);
} else {
result.length = length;
}
var ellipsoid = this._ellipsoid;
var origin = this._origin;
var xAxis = this._xAxis;
var yAxis = this._yAxis;
var tmp = projectPointsOntoEllipsoidScratch;
for ( var i = 0; i < length; ++i) {
var position = cartesians[i];
Cartesian3.multiplyByScalar(xAxis, position.x, tmp);
if (!defined(result[i])) {
result[i] = new Cartesian3();
}
var point = Cartesian3.add(origin, tmp, result[i]);
Cartesian3.multiplyByScalar(yAxis, position.y, tmp);
Cartesian3.add(point, tmp, point);
ellipsoid.scaleToGeocentricSurface(point, point);
}
return result;
};
return EllipsoidTangentPlane;
});
|
"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: "M7 21h10v-1H7v1zM7 3v1h10V3H7z",
opacity: ".3"
}, "0"), /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M17 6v8.17l2 2V3c0-1.1-.9-1.99-2-1.99L7 1c-.85 0-1.58.55-1.87 1.3L8.83 6H17zM7 3h10v1H7V3zm14.19 18.19L2.81 2.81 1.39 4.22 5 7.83V21c0 1.1.9 2 2 2h10c.85 0 1.58-.55 1.87-1.3l.91.91 1.41-1.42zM17 21H7v-1h10v1zM7 18V9.83L15.17 18H7z"
}, "1")], 'NoCellTwoTone');
exports.default = _default;
|
/** captcha.js */
onready(function(){
var e = document.getElementById("captcha_img");
if(!e) return; // no captcha
var original_url = e.src;
e.onclick = function() {
e.src = original_url + "?t="+new Date().getTime();
}
});
|
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
// Renderers that don't support persistence
// can re-export everything from this module.
function shim(...args: any) {
throw new Error(
'The current renderer does not support persistence. ' +
'This error is likely caused by a bug in React. ' +
'Please file an issue.',
);
}
// Persistence (when unsupported)
export const supportsPersistence = false;
export const cloneInstance = shim;
export const createContainerChildSet = shim;
export const appendChildToContainerChildSet = shim;
export const finalizeContainerChildren = shim;
export const replaceContainerChildren = shim;
export const getOffscreenContainerType = shim;
export const getOffscreenContainerProps = shim;
export const cloneHiddenInstance = shim;
export const cloneHiddenTextInstance = shim;
|
// This version reads and converts PDF page by page
const path = require('path')
const util = require('util')
const async = require('async')
const fs = require('fs')
// const replace = require('replace')
const logger = require(path.resolve(__dirname, 'logging.js'))('out.log')
const BOOK = 'r_6'
const SECTIONS = [
{ section: "1", first_page: 358, last_page: 358, csvstream: fs.createWriteStream('isikud_r6_1.csv') },
// { section: "2", first_page: 360, last_page: 713, csvstream: fs.createWriteStream('isikud_r6_2.csv') },
// { section: "3", first_page: 780, last_page: 796, csvstream: fs.createWriteStream('isikud_r6_3.csv') },
// { section: "4", first_page: 807, last_page: 856, csvstream: fs.createWriteStream('isikud_r6_4.csv') },
// { section: "5", first_page: 872, last_page: 881, csvstream: fs.createWriteStream('isikud_r6_5.csv') }
]
let pages = []
let lines = []
SECTIONS.forEach( (s) => { pages[s.section] = [] })
async.eachSeries(SECTIONS, (section, callback) => {
let pn_arr = []
for (var page_number = section.first_page; page_number <= section.last_page; page_number++) {
pn_arr.push(page_number)
}
async.eachSeries(pn_arr, (page_number, callback) => {
// console.log('Page ' + section.section + '.' + page_number + ' from PDF');
let converted_page_filename = path.resolve(
__dirname,
'pages',
'converted',
+ section.section + '.' + page_number + '.txt'
)
fs.access(converted_page_filename, (err) => {
if (!err) {
unsplitConvertedPage(section, converted_page_filename, (err) => {
return callback(err)
})
return
}
// console.log('Convert page ' + section.section + '.' + page_number + ' from PDF');
var exec = require('child_process').exec
var cmd = 'pdftotext -nopgbrk -enc UTF-8'
+ ' -f ' + page_number
+ ' -l ' + page_number
+ ' -layout "' + BOOK + '.pdf" "' + converted_page_filename + '"'
// console.log(cmd);
exec(cmd, function(error, stdout, stderr) {
if (error | stderr | stdout) {
// console.error(error);
// console.error(stderr);
// console.error(stdout);
return callback(null)
}
unsplitConvertedPage(section, converted_page_filename, (err) => {
return callback(err)
})
return
})
})
}, function done() {
// console.log('END section ' + section.section)
callback(null)
} )
}, function done() {
lines.forEach((line) => {console.log(line)})
// console.log('ENDZ converting and unsplitting')
})
const unsplitConvertedPage = function(section, converted_page_filename, callback) {
let page_number = path.basename(converted_page_filename).split('.')[1]
let unsplitted_page_filename = path.resolve(
__dirname,
'pages',
'unsplit',
section.section + '.' + page_number + '.txt'
)
// console.log('Unsplitting from ' + converted_page_filename + ' to ' + unsplitted_page_filename)
const lineReader = require('readline').createInterface({
input: fs.createReadStream(converted_page_filename)
})
let raw_lines = []
let is_first_line = true
let page_number_re = /^ {0,125}([0-9]{1,3})$/
lineReader.on('line', function (line) {
if (is_first_line) {
is_first_line = false
return
}
else if (line === '') {
return
}
else if (page_number_re.exec(line)) {
pages[section.section][page_number] = mergePage(raw_lines)
return
}
else {
raw_lines.push(line)
return
}
})
lineReader.on('close', function (line) {
// console.log('unsplitted page ' + section.section + '.' + page_number + '.')
return callback(null)
// readRecords(section, pages)
// console.log(isikud.length)
})
}
const mergePage = function(raw_lines) {
function findSplit(raw_lines, log) {
let positionMap = []
for (var i = 0; i < 150; i++) {
positionMap[i] = true
}
raw_lines.forEach(function(line) {
if (log) { console.log(line) }
let temp = ''
for (var i = 0; i < line.length; i++) {
positionMap[i] = positionMap[i] && (line.charAt(i) === ' ' ? true : false)
// console.log(i,line.charAt(i))
temp = temp + (line.charAt(i) === ' ' ? '+' : '-')
}
if (log) { console.log(temp) }
})
if (log) { return }
split_re = /^(\-*)(\+*)(\-*)\+/
let match = split_re.exec(
positionMap
.map(function(n){ return n ? '+' : '-' })
.join('')
)
// In case of pattern mismatch
// if (match[3] === '' || match[2].charAt(0) !== '+') {
// console.log('ERR');
// findSplit(raw_lines, true)
// console.log(positionMap
// .map(function(n){ return n ? '+' : '-' })
// .join(''))
// console.log(match)
// process.exit()
// }
// console.log(' left:',(match[1].length + 1))
// console.log(JSON.stringify(positionMap, null, 4));
// process.exit()
return {left: match[1].length, split: match[2].length}
}
let lefthalf = []
let righthalf = []
let split = findSplit(raw_lines)
let line_split_str = '^(.{1,' + split.left + '}).{0,' + split.split + '}(.*)$'
let line_split_re = new RegExp(line_split_str)
raw_lines.forEach(function(line) {
match = line_split_re.exec(line)
if (match) {
if (match[1].trim().length > 1) {
lefthalf.push((match[1]))
}
if (match[2] && match[2].trim().length > 1) {
righthalf.push((match[2]))
}
}
})
let page = lefthalf.concat(righthalf)
page.forEach((line) => {
lines.push(line)
})
return page
}
|
'use strict';
var runMochaJSON = require('./helpers').runMochaJSON;
var invokeMocha = require('./helpers').invokeMocha;
var MULTIPLE_DONE = require('../../lib/errors').constants.MULTIPLE_DONE;
describe('multiple calls to done()', function() {
var res;
describe('from a spec', function() {
before(function(done) {
runMochaJSON('multiple-done', function(err, result) {
res = result;
done(err);
});
});
it('results in failure', function() {
expect(res, 'to have failed test count', 1)
.and('to have passed test count', 1)
.and('to have pending test count', 0)
.and('to have failed');
});
it('throws a descriptive error', function() {
expect(res, 'to have failed with error', {
message: /done\(\) called multiple times in test <should fail in a test-case> \(of root suite\) of file.+multiple-done\.fixture\.js/,
code: MULTIPLE_DONE
});
});
});
describe('with error passed on second call', function() {
before(function(done) {
runMochaJSON('multiple-done-with-error', function(err, result) {
res = result;
done(err);
});
});
it('results in failure', function() {
expect(res, 'to have failed test count', 1)
.and('to have passed test count', 1)
.and('to have pending test count', 0)
.and('to have failed');
});
it('should throw a descriptive error', function() {
expect(res, 'to have failed with error', {
message: /done\(\) called multiple times in test <should fail in a test-case> \(of root suite\) of file.+multiple-done-with-error\.fixture\.js; in addition, done\(\) received error: Error: second error/,
code: MULTIPLE_DONE
});
});
});
describe('with multiple specs', function() {
before(function(done) {
runMochaJSON('multiple-done-specs', function(err, result) {
res = result;
done(err);
});
});
it('results in failure', function() {
expect(res, 'to have failed test count', 1)
.and('to have passed test count', 2)
.and('to have pending test count', 0)
.and('to have failed');
});
it('correctly attributes the error', function() {
expect(res.failures[0], 'to satisfy', {
fullTitle: 'suite test1',
err: {
message: /done\(\) called multiple times in test <suite test1> of file.+multiple-done-specs\.fixture\.js/,
code: MULTIPLE_DONE
}
});
});
});
describe('from a before hook', function() {
before(function(done) {
runMochaJSON('multiple-done-before', function(err, result) {
res = result;
done(err);
});
});
it('results in failure', function() {
expect(res, 'to have failed test count', 1)
.and('to have passed test count', 1)
.and('to have pending test count', 0)
.and('to have failed');
});
it('correctly attributes the error', function() {
expect(res.failures[0], 'to satisfy', {
fullTitle: 'suite1 "before all" hook in "suite1"',
err: {
message: /done\(\) called multiple times in hook <suite1 "before all" hook in "suite1"> of file.+multiple-done-before\.fixture\.js/
}
});
});
});
describe('from a "before each" hook', function() {
before(function(done) {
runMochaJSON('multiple-done-before-each', function(err, result) {
res = result;
done(err);
});
});
it('results in a failure', function() {
expect(res, 'to have failed test count', 2)
.and('to have passed test count', 2)
.and('to have pending test count', 0)
.and('to have exit code', 2);
});
it('correctly attributes the errors', function() {
expect(res.failures[0], 'to equal', res.failures[1]).and('to satisfy', {
fullTitle: 'suite1 "before each" hook in "suite1"',
err: {
message: /done\(\) called multiple times in hook <suite1 "before each" hook in "suite1"> of file.+multiple-done-before-each\.fixture\.js/,
multiple: [
{
code: 'ERR_MOCHA_MULTIPLE_DONE'
}
]
}
});
});
});
describe('when done() called asynchronously', function() {
before(function(done) {
// we can't be sure that mocha won't fail with an uncaught exception here, which would cause any JSON
// output to be befouled; we need to run "raw" and capture STDERR
invokeMocha(
require.resolve('./fixtures/multiple-done-async.fixture.js'),
function(err, result) {
res = result;
done(err);
},
'pipe'
);
});
it('results in error', function() {
expect(res, 'to satisfy', {
code: expect.it('to be greater than', 0),
output: /done\(\) called multiple times in test <should fail in an async test case> \(of root suite\) of file.+multiple-done-async\.fixture\.js/
});
});
});
});
|
var Geometry = require('../c2d/Geometry');
/**
* Mutable storage for sets of 3d points
*
* Can be used for calculation of bounds
* Doesn't have anything related to particular DisplayObject
* Renderers can use it to upload data to vertex buffer or to copy data to other buffers
*
* @class
* @extends PIXI.Geometry
* @memberof PIXI
*/
function Geometry3d() {
Geometry.call(this);
this.stride = 3;
this.is3d = true;
}
Geometry3d.prototype = Object.create(Geometry.prototype);
Geometry3d.prototype.constructor = Geometry3d;
module.exports = Geometry3d;
Geometry3d.fromBuffers = function (vertices, indices) {
var geometry = new Geometry3d();
geometry.vertices = vertices || null;
geometry.indices = indices || null;
return geometry;
};
|
/* global hexo */
'use strict'
const { resolve, basename } = require('path')
const { readFileSync } = require('fs')
const cheerio = require('cheerio')
const fullUrlFor = hexo.extend.helper.get('full_url_for').bind(hexo)
const localizedPath = ['tutorials', 'filters', 'tags', 'playground', 'api']
hexo.extend.helper.register('page_nav', function () {
const type = this.page.canonical_path.split('/')[0]
const sidebar = this.site.data.sidebar[type]
const path = basename(this.path)
const list = {}
const prefix = 'sidebar.' + type + '.'
for (const i in sidebar) {
if (typeof sidebar[i] === 'string') list[sidebar[i]] = i
else for (const j in sidebar[i]) list[sidebar[i][j]] = j
}
const keys = Object.keys(list)
const index = keys.indexOf(path)
let result = ''
if (index > 0) {
result += `<a href="${keys[index - 1]}" class="article-footer-prev" title="${this.__(prefix + list[keys[index - 1]])}"><i class="icon-chevron-left"></i><span>${this.__('page.prev')}</span></a>`
}
if (index < keys.length - 1) {
result += `<a href="${keys[index + 1]}" class="article-footer-next" title="${this.__(prefix + list[keys[index + 1]])}"><span>${this.__('page.next')}</span><i class="icon-chevron-right"></i></a>`
}
return result
})
hexo.extend.helper.register('raw', function (filepath) {
const content = readFileSync(resolve(this.view_dir, filepath), 'utf8')
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''')
return content
})
hexo.extend.helper.register('doc_sidebar', function (className) {
const type = this.page.canonical_path.split('/')[0]
const sidebar = this.site.data.sidebar[type]
const path = basename(this.path)
let result = ''
const { __ } = this
const prefix = 'sidebar.' + type + '.'
if (typeof sidebar === 'undefined') {
return ''
}
for (const [title, menu] of Object.entries(sidebar)) {
if (typeof menu === 'string') renderLink(title, menu)
else renderSection(title, menu)
}
return result
function renderLink (text, link) {
let itemClass = className + '-link'
if (link === path) itemClass += ' current'
const localized = __(prefix + text) === prefix + text ? text : __(prefix + text)
result += '<a href="' + link + '" class="' + itemClass + '">' + localized + '</a>'
}
function renderSection (title, menu) {
result += '<strong class="' + className + '-title">' + __(prefix + title) + '</strong>'
for (const [text, link] of Object.entries(menu)) renderLink(text, link)
}
})
hexo.extend.helper.register('header_menu', function (className) {
const menu = this.site.data.menu
let result = ''
const lang = this.page.lang
const isEnglish = lang === 'en'
for (const [title, path] of Object.entries(menu)) {
let langPath = path
if (!isEnglish && ~localizedPath.indexOf(title)) langPath = lang + path
const url = this.url_for(langPath)
const active = ('/' + this.page.canonical_path).slice(0, path.length) === path ? ' active' : ''
result += `<a href="${url}" class="${className}-link${active}">${this.__('menu.' + title)}</a>`
}
return result
})
hexo.extend.helper.register('canonical_url', function (lang) {
let path = this.page.path
if (lang && lang !== 'en') path = lang + '/' + path
return fullUrlFor(path)
})
hexo.extend.helper.register('url_for_lang', function (path) {
const lang = this.page.lang
let url = this.url_for(path)
if (lang !== 'en' && path[0] === '/') url = '/' + lang + path
return url
})
hexo.extend.helper.register('raw_link', path => `https://github.com/harttle/liquidjs/edit/master/docs/source/${path}`)
hexo.extend.helper.register('page_anchor', str => {
const $ = cheerio.load(str, { decodeEntities: false })
const headings = $('h1, h2, h3, h4, h5, h6')
if (!headings.length) return str
headings.each(function () {
const id = $(this).attr('id')
$(this)
.addClass('article-heading')
.append(`<a class="article-anchor" href="#${id}" aria-hidden="true"></a>`)
})
return $.html()
})
// Will be replace with fullUrlFor after hexo v4 release
hexo.extend.helper.register('canonical_path_for_nav', function () {
const path = this.page.canonical_path
for (const slug of localizedPath) if (path.startsWith(slug)) return path
return ''
})
hexo.extend.helper.register('lang_name', function (lang) {
const data = this.site.data.languages[lang]
return data.name || data
})
hexo.extend.helper.register('hexo_version', function () {
return this.env.version
})
|
define(["bundles/framework/bundle/mapwmts/service/WmtsLayerModelBuilder"], function() {
Oskari.cls('Oskari.mapframework.wmts.service.WmtsLayerModelBuilder').category({
/**
* parses any additional fields to model
*/
parseLayerData: function(layer, mapLayerJson, maplayerService) {
layer.setWmtsName(mapLayerJson.wmsName);
if (mapLayerJson.wmsUrl) {
var wmsUrls = mapLayerJson.wmsUrl.split(",");
for (var i = 0; i < wmsUrls.length; i++) {
layer.addWmtsUrl(wmsUrls[i]);
}
}
var styleBuilder = Oskari.clazz.builder('Oskari.mapframework.domain.Style');
var styleSpec;
for (var i = 0, ii = mapLayerJson.styles.length; i < ii; ++i) {
styleSpec = mapLayerJson.styles[i];
var style = styleBuilder();
style.setName(styleSpec.identifier);
style.setTitle(styleSpec.identifier);
layer.addStyle(style);
if (styleSpec.isDefault) {
layer.selectStyle(styleSpec.identifier);
break;
}
}
/*
* layer.setWmtsMatrixSet(mapLayerJson.tileMatrixSetData);
*
* layer.setWmtsLayerDef(mapLayerJson.tileLayerData);
*/
layer.setFeatureInfoEnabled(true);
if (mapLayerJson.tileMatrixSetData && mapLayerJson.tileLayerData) {
/* ver 2 */
layer.setWmtsMatrixSet(mapLayerJson.tileMatrixSetData);
layer.setWmtsLayerDef(mapLayerJson.tileLayerData);
} else if (mapLayerJson.tileMatrixSetData && mapLayerJson.tileMatrixSetId) {
/* ver 1 */
var tileMatrixSetId = mapLayerJson.tileMatrixSetId;
if (mapLayerJson.tileMatrixSetData.contents && mapLayerJson.tileMatrixSetData.contents.tileMatrixSets) {
var tileMatrixSet = mapLayerJson.tileMatrixSetData.contents.tileMatrixSets[tileMatrixSetId];
layer.setWmtsMatrixSet(tileMatrixSet);
}
var wmtsLayerName = layer.getWmtsName();
var wmtsLayersArr = mapLayerJson.tileMatrixSetData.contents.layers;
for (var n = 0; n < wmtsLayersArr.length; n++) {
if (wmtsLayersArr[n].identifier == wmtsLayerName) {
layer.setWmtsLayerDef(wmtsLayersArr[n]);
break;
}
}
}
layer._data = mapLayerJson;
layer.setWmtsCaps(mapLayerJson.caps);
// NOTE! OL2 only as OL2 changed format from {lat: x, lon: y} to [x,y]
// which differs from OL3 usage
}
});
});
|
var util = require('util');
var webrtc = require('./adapter');
//var Datastore = require('nedb');
function Arty(options) {
if (!options) {
options = {};
}
this.options = options;
this.seeds = options.seeds || ['ws://localhost:20500'];
this.peers = {};
this._pendingDataChannels = {};
this._dataChannels = {};
this.iceServers = options.iceServers || [{url:'stun:stun.l.google.com:19302'}];
}
util.inherits(Arty, require('events').EventEmitter);
Arty.prototype.start = function() {
var self = this;
self.p = P.create();
// TODO: multiple seed attempts
self.onramp = self.p.connect(self.seeds[0]);
self.onramp.on('message', self._addPeer);
self.emit('start');
};
Arty.prototype._addPeer = function(peerAddress) {
var self = this;
// TODO: use hash.js to generate a real hash.
var hash = peerAddress;
self.peers[hash] = self.onramp.connect(peerAddress);
self.peers[hash].on('message', self._route);
self.emit('peer', self.peers[hash]);
};
Arty.prototype._errorHandler = function(err) {
console.error(err);
};
Arty.prototype._makeDataChannel = function() {
var self = this;
var channel = self.pc.createDataChannel('fabric', { reliable: true });
channel.onopen = function() {
console.log('Channel connected!');
};
channel.onmessage = function(e) {
try {
var data = JSON.parse(e.data);
console.log('incoming data:', data);
} catch (err) {
return console.error(e);
}
};
channel.onerror = self._errorHandler;
};
Arty.prototype._connectRTC = function() {
var self = this;
console.log('connectRTC', self.name);
var opts = [
{ iceServers: self.iceServers },
{ optional: [{DtlsSrtpKeyAgreement: false}] }
];
console.log('opts:', opts);
self.pc = new webrtc.RTCPeerConnection(opts);
};
Arty.prototype._makeOffer = function() {
var self = this;
self._connectRTC();
self._makeDataChannel();
self.pc.onsignalingstatechange = self._onSignalingStateChange;
self.pc.oniceconnectionstatechange = self._onICEConnectionStateChange;
self.pc.onicegatheringstatechange = self._onICEGatheringStateChange;
self.pc.createOffer(function(desc) {
self.pc.setLocalDescription(desc, function() {
console.log('set local success');
});
});
self.pc.onicecandidate = function(candidate) {
self._onICECandidate.apply(self, [candidate]);
};
};
Arty.prototype._handleOffer = function(data) {
var self = this;
console.log('handleOffer...', self.name);
var offer = new webrtc.RTCSessionDescription(data);
self._connectRTC();
self.pc.onsignalingstatechange = self._onSignalingStateChange;
self.pc.oniceconnectionstatechange = self._onICEConnectionStateChange;
self.pc.onicegatheringstatechange = self._onICEGatheringStateChange;
self.pc.onicecandidate = function(candidate) {
console.log('handleOffer candidate...', self.name);
self._onICECandidate.apply(self, [candidate]);
};
self._handleDataChannels(offer);
};
Arty.prototype._handleDataChannels = function(offer) {
var self = this;
console.log('handle data channel', self.name);
var dataChannelSettings = {
reliable: {
ordered: true,
maxRetransmits: 0
},
};
var labels = Object.keys(dataChannelSettings);
console.log('labels:', labels);
self.pc.ondatachannel = function(evt) {
console.log('datachannel!', evt);
var channel = evt.channel;
var label = channel.label;
self._pendingDataChannels[label] = channel;
channel.onopen = function() {
console.log('channel open!');
self._dataChannels[label] = channel;
delete self._pendingDataChannels[label];
if (Object.keys(self._dataChannels).length === labels.length) {
console.log('connected! :)');
}
};
channel.onmessage = function(evt) {
try {
var data = JSON.parse(evt.data);
console.log('channel data:', data);
self.emit('message', data);
} catch (e) {
console.error(e);
}
};
};
console.log('datachannel, setting remote description...');
console.log('dat offer:', offer);
self.pc.setRemoteDescription(offer, function() {
self.pc.createAnswer(function(answer) {
console.log('_createAnswer', answer);
self.pc.setLocalDescription(answer, function() {
console.log('set local success!');
}, self._errorHandler);
self.emit('answer', answer);
}, self._errorHandler);
}, self._errorHandler);
};
Arty.prototype._setRemoteDescription = function(desc) {
var self = this;
self.pc.setRemoteDescription(desc);
};
Arty.prototype._setLocalDescription = function(desc) {
var self = this;
self.pc.setLocalDescription(desc);
};
Arty.prototype._onICECandidate = function(candidate) {
var self = this;
console.log('onicecandidate!', self.name);
if (candidate.candidate === null) {
console.log('CONSOLE LOGGING THE NULL ROUTE! expecting an answer');
console.log('local description:', self.pc.localDescription);
self.emit('offer', self.pc.localDescription);
}
};
Arty.prototype._onSignalingStateChange = function(state) {
//console.info('signaling state change:', state);
};
Arty.prototype._onICEConnectionStateChange = function(state) {
//console.info('ice connection state change:', state);
};
Arty.prototype._onICEGatheringStateChange = function(state) {
//console.info('ice gathering state change:', state);
};
Arty.prototype._route = function(message) {
console.log('received message:', message);
this.emit('message', message);
};
Arty.prototype.send = function(message) {
var self = this;
console.log('self._dataChannels', self._dataChannels);
console.log('self._pendingDataChannels', self._pendingDataChannels);
};
Arty.prototype._broadcast = function(message) {
for (var peer in this.peers) {
this.peers[peer].send(message);
}
};
module.exports = Arty;
|
import Adapter from 'restle-memory';
import Router from '../router';
import express from 'express';
export default (instance, options = {}) => {
Object.assign(instance, {
models: {},
adapter: options.adapter || new Adapter(),
router: new Router(options),
app: express(),
namespace: options.namespace ? `/${options.namespace}` : '',
port: options.port || 3000,
cors: options.cors || '*',
});
}
|
function pesan_err(pesan) {
var temp = '<div class="alert alert-warning alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button><h4><i class="icon fa fa-ban"></i> Error</h4> ' + pesan + ' </div>';
return temp;
}
function pesan_succ(pesan) {
var temp = '<div class="alert alert-success alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button><h4><i class="icon fa fa-check"></i> Success</h4> ' + pesan + ' </div>';
return temp;
}
|
if (typeof Promise === 'undefined') {
require('promise/lib/rejection-tracking').enable();
window.Promise = require('promise/lib/es6-extensions.js');
}
Object.assign = require('object-assign');
|
import * as t from 'constants/ActionTypes';
import { comicManagers } from 'services';
import { addRecentComic, updateReadingRecord } from 'actions/ConfigActions';
import { replaceChapterCache } from 'actions';
export const initComicManager = ({site, chapterID, readingChapterID}) => {
return (dispatch, getState) => {
let comicManager = comicManagers.selectComicManager(site);
comicManager.getComic(chapterID).then(comicInfo => {
const {
comicID,
comicName,
coverImage,
chapters,
latestChapter
} = comicInfo;
if (chapterID === readingChapterID) {
return;
}
dispatch({type: t.CLEAR_COMIC_IMAGES});
replaceChapterCache({comicID, chapters});
dispatch({
type: t.SET_COMIC_NAME,
comicName: comicName
});
dispatch({
type: t.INIT_COMIC_MANAGER,
comicManager: comicManager,
chapters: chapters,
comicID: comicID
});
const { readingRecord } = getState().config;
/* load last read chapter */
if (typeof readingRecord[comicID] !== 'undefined') {
const { _id, _rev, ...readingComicRecord } = readingRecord[comicID];
const reverseRecordMap = Object.keys(readingComicRecord).reduce((prev, cur) => {
return {...prev, [readingComicRecord[cur]]: cur};
}, {});
const lastChapterID = reverseRecordMap[Math.max(...Object.keys(reverseRecordMap).map(Number).filter(Number.isInteger))];
chapterID = lastChapterID;
} else {
// start from first chapter
chapterID = chapters[chapters.length-1].chapterID;
}
comicManager.getChapterImages(chapterID).then(images => {
let chapterItem = chapters.find(item => item.chapterID == chapterID);
updateReadingRecord({comicID, chapterID})(dispatch);
addRecentComic({comicID, coverImage, comicName, latestChapter})(dispatch);
dispatch({
type: t.SWITCH_CHAPTER,
readingChapters: [chapterItem],
readingImages: [images],
appBarTitle: chapterItem.title,
readingChapterID: chapterID
});
});
});
};
};
export const switchChapter = (chapterItem) => {
return dispatch => {
dispatch({type: t.SWITCH_CHAPTER_REQUEST, chapterItem});
};
};
|
/* eslint-disable no-console */
/**
* Wraps a function. When the wrapped function is called
* an error is emitted *once*.
* @function
* @param {function} func the deprecated function
* @param {string} [msg="{func.name} is deprecated"]
* @return {function} wrapped *func*
* @example
* import {deprecate} from 'js-utils';
* function deprecatedFunc() {}
* export const func = deprecate(deprecatedFunc);
*/
export let deprecate;
if (process.env.NODE_ENV !== 'production') {
deprecate = (func, msg = `${func.name || 'unknown'} is deprecated`) => {
let warned = false;
return function $deprecate(...args) {
if (!warned) {
console::(console.warn || console.log)(msg);
if (typeof console.trace === 'function') {
console.trace();
}
warned = true;
}
return this::func(...args);
};
};
} else {
deprecate = func => func;
}
|
'use strict';
const egg = require('egg');
const Application = egg.Application;
const Agent = egg.Agent;
const EGG_PATH = Symbol.for('egg#eggPath');
class DemoAgent extends Agent {
get [EGG_PATH]() {
return __dirname;
}
}
class DemoApplication extends Application {
get [EGG_PATH]() {
return __dirname;
}
}
Object.assign(exports, egg);
exports.Application = DemoApplication;
exports.Agent = DemoAgent;
|
function findMinAndMax(arr) {
arr.sort(function (a,b) {
return a>b;
});
console.log("Min: "+arr[0]+", Max: "+arr[arr.length-1]);
}
//findMinAndMax([1, 2, 1, 15, 20, 5, 7, 31]);
//findMinAndMax([2, 2, 2, 2, 2]);
findMinAndMax([500, 1, -23, 0, -300, 28, 35, 12]);
|
(function() {
'use strict';
// TODO: replace app with your module name
angular.module('app.shell')
.directive('skBusyIndicator', ['baseUrl', skBusyIndicator]);
function skBusyIndicator(baseUrl) {
var directive = {
controller: ['$rootScope', '$scope', controller],
restrict: 'E',
replace: true,
templateUrl: baseUrl + 'shell/skBusyIndicator.html'
};
return directive;
function controller($rootScope, $scope) {
$scope.isBusy = false;
$rootScope.$on("appActivityService:isBusyChanged", function (event, args) {
$scope.isBusy = args.busy;
});
}
}
})();
|
import _ from 'lodash'
import cx from 'classnames'
import React, { PropTypes } from 'react'
import {
customPropTypes,
getUnhandledProps,
getElementType,
META,
SUI,
} from '../../lib'
import BreadcrumbDivider from './BreadcrumbDivider'
import BreadcrumbSection from './BreadcrumbSection'
/**
* A breadcrumb is used to show hierarchy between content.
*/
function Breadcrumb(props) {
const { children, className, divider, icon, size, sections } = props
const classes = cx('ui', className, size, 'breadcrumb')
const rest = getUnhandledProps(Breadcrumb, props)
const ElementType = getElementType(Breadcrumb, props)
if (children) {
return <ElementType {...rest} className={classes}>{children}</ElementType>
}
const childElements = []
_.each(sections, (section, index) => {
// section
const breadcrumbSection = BreadcrumbSection.create(section)
childElements.push(breadcrumbSection)
// divider
if (index !== sections.length - 1) {
// TODO generate a key from breadcrumbSection.props once this is merged:
// https://github.com/Semantic-Org/Semantic-UI-React/pull/645
//
// Stringify the props of the section as the divider key.
//
// Section: { content: 'Home', link: true, onClick: handleClick }
// Divider key: content=Home|link=true|onClick=handleClick
let key
if (section.key) {
key = `${section.key}_divider`
} else {
key = _.map(breadcrumbSection.props, (v, k) => {
return `${k}=${typeof v === 'function' ? v.name || 'func' : v}`
}).join('|')
}
childElements.push(BreadcrumbDivider.create({ content: divider, icon, key }))
}
})
return <ElementType {...rest} className={classes}>{childElements}</ElementType>
}
Breadcrumb._meta = {
name: 'Breadcrumb',
type: META.TYPES.COLLECTION,
props: {
size: _.without(SUI.SIZES, 'medium'),
},
}
Breadcrumb.propTypes = {
/** An element type to render as (string or function). */
as: customPropTypes.as,
/** Primary content. */
children: PropTypes.node,
/** Additional classes. */
className: PropTypes.string,
/** Shorthand for primary content of the Breadcrumb.Divider. */
divider: customPropTypes.every([
customPropTypes.disallow(['icon']),
customPropTypes.contentShorthand,
]),
/** For use with the sections prop. Render as an `Icon` component with `divider` class instead of a `div` in
* Breadcrumb.Divider. */
icon: customPropTypes.every([
customPropTypes.disallow(['divider']),
customPropTypes.itemShorthand,
]),
/** Shorthand array of props for Breadcrumb.Section. */
sections: customPropTypes.collectionShorthand,
/** Size of Breadcrumb */
size: PropTypes.oneOf(Breadcrumb._meta.props.size),
}
Breadcrumb.Divider = BreadcrumbDivider
Breadcrumb.Section = BreadcrumbSection
export default Breadcrumb
|
define(['react'], function(React) {
var reactComponent = React.createClass({displayName: "reactComponent",
getInitialState: function() {
return ({
title : "mindQ",
username: "rajesh"
});
},
render: function() {
return (
React.createElement("div", {className: "row header-row"},
React.createElement("div", {className: "col-md-12"},
React.createElement("div", {className: "text-right title"}, React.createElement("h3", {className: "text-right"}, " ", this.state.title, " "))
)
)
);
}
});
var componentObj = {};
componentObj.el = function() {
return React.createElement(reactComponent);
}
return componentObj;
});
|
var net = require('net');
var cmds = [
"NOOP"
, "HELO Enlogic"
, "MAIL FROM:<kris.zhang@enlogic.com>"
, "RCPT TO:<kris.zhang@enlogic.com>"
, "RCPT TO:<justin.luo@enlogic.com>"
, "DATA"
, "DATE:2006-6-1 22:11:01"
, "FROM:kris.zhang@enlogic.com"
, "TO:kris.zhang@enlogic.com, justin.luo@enlogic.com"
, "SUBJECT:Test"
, "REPLY-TO:kris.zhang@sina.com"
, ""
, "This is a test mail send by SMTP"
, "\r\n."
, "QUIT"
];
var client = net.connect({host:"192.168.1.4", port:25}, function() {
for (var i = 0, l = cmds.length; i < l; i++) {
(function(i){
setTimeout(function() {
console.log(cmds[i]);
client.write(cmds[i] + "\r\n");
}, i * 6000);
})(i);
}
});
client.on('data', function(data) { console.log(data.toString()); });
client.on('end', function() { console.log('client disconnected'); });
|
'use strict'
const figgyPudding = require('figgy-pudding')
const index = require('./lib/entry-index')
const memo = require('./lib/memoization')
const write = require('./lib/content/write')
const to = require('mississippi').to
const PutOpts = figgyPudding({
algorithms: {
default: ['sha512']
},
integrity: {},
memoize: {},
metadata: {},
pickAlgorithm: {},
size: {},
tmpPrefix: {},
uid: {},
gid: {},
single: {},
sep: {},
error: {},
strict: {}
})
module.exports = putData
function putData (cache, key, data, opts) {
opts = PutOpts(opts)
return write(cache, data, opts).then(res => {
return index.insert(
cache, key, res.integrity, opts.concat({ size: res.size })
).then(entry => {
if (opts.memoize) {
memo.put(cache, entry, data, opts)
}
return res.integrity
})
})
}
module.exports.stream = putStream
function putStream (cache, key, opts) {
opts = PutOpts(opts)
let integrity
let size
const contentStream = write.stream(
cache, opts
).on('integrity', int => {
integrity = int
}).on('size', s => {
size = s
})
let memoData
let memoTotal = 0
const stream = to((chunk, enc, cb) => {
contentStream.write(chunk, enc, () => {
if (opts.memoize) {
if (!memoData) { memoData = [] }
memoData.push(chunk)
memoTotal += chunk.length
}
cb()
})
}, cb => {
contentStream.end(() => {
index.insert(cache, key, integrity, opts.concat({ size })).then(entry => {
if (opts.memoize) {
memo.put(cache, entry, Buffer.concat(memoData, memoTotal), opts)
}
stream.emit('integrity', integrity)
cb()
})
})
})
let erred = false
stream.once('error', err => {
if (erred) { return }
erred = true
contentStream.emit('error', err)
})
contentStream.once('error', err => {
if (erred) { return }
erred = true
stream.emit('error', err)
})
return stream
}
|
define(['altair/facades/declare',
'../_Base'
], function (declare, _Base) {
return declare([_Base], {
});
});
|
/**
* @license
* Copyright 2014 David Wolverton
* Available under MIT license <https://raw.githubusercontent.com/dwolverton/my/master/LICENSE.txt>
*/
define([
"mytime/model/modelRegistry",
"mytime/model/TimeEntry", "mytime/model/Task",
"mytime/controller/TimeEntryController", "mytime/controller/TaskController",
"mytime/util/store/EnhancedMemoryStore",
"mytime/persistence/LocalStorage",
"mytime/mock-data"
], function(
modelRegistry,
TimeEntry, Task,
TimeEntryController, TaskController,
EnhancedMemoryStore,
LocalStorage,
mockData
) {
modelRegistry.set("timeEntryStore", EnhancedMemoryStore.createObservable());
modelRegistry.set("taskStore", EnhancedMemoryStore.createObservable());
LocalStorage.loadStore("timeEntryStore", modelRegistry.get("timeEntryStore"), TimeEntry);
LocalStorage.loadStore("taskStore", modelRegistry.get("taskStore"), Task);
new TimeEntryController();
new TaskController();
// mockData();
});
|
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
const benv = require("benv")
const Backbone = require("backbone")
const sinon = require("sinon")
const CurrentUser = require("../../../../models/current_user")
const Artworks = require("../../../../collections/artworks.coffee")
const Partner = require("../../../../models/partner.coffee")
const Profile = require("../../../../models/profile.coffee")
const Articles = require("../../../../collections/articles.coffee")
const _ = require("underscore")
const { resolve } = require("path")
const { fabricate } = require("@artsy/antigravity")
describe("PartnerView", function () {
before(done =>
benv.setup(function () {
benv.expose({ $: benv.require("jquery") })
Backbone.$ = $
return done()
})
)
after(() => benv.teardown())
return describe("when setting up tabs", function () {
beforeEach(function (done) {
sinon.stub(Backbone, "sync")
return benv.render(
resolve(__dirname, "../../templates/index.jade"),
{
profile: new Profile(fabricate("partner_profile")),
sd: { PROFILE: fabricate("partner_profile") },
asset() {},
params: {},
},
() => {
let mod
const PartnerView = (mod = benv.requireWithJadeify(
resolve(__dirname, "../../client/view"),
["tablistTemplate"]
))
this.profile = new Profile(fabricate("partner_profile"))
this.partner = this.profile.related().owner
mod.__set__("sectionToView", {})
mod.__set__("tablistTemplate", (this.tablistTemplate = sinon.stub()))
this.view = new PartnerView({
profile: this.profile,
partner: this.partner,
el: $("body"),
})
return done()
}
)
})
afterEach(() => Backbone.sync.restore())
describe("#getDisplayableSections", function () {
describe("with minimal data to display", function () {
beforeEach(function () {
return this.partner.set({
partner_artists_count: 0,
displayable_shows_count: 0,
published_not_for_sale_artworks_count: 0,
published_for_sale_artworks_count: 0,
})
})
it("gallery", function () {
this.partner.set({
type: "Gallery",
claimed: true,
// This assumes that galleries do not have the option to disable the artists section
display_artists_section: true,
})
this.profile.set({ owner_type: "PartnerGallery" })
const sections = this.view.getDisplayableSections(
this.view.getSections()
)
return sections.should.eql(["overview", "contact"])
})
return it("institution", function () {
this.partner.set({
type: "Institution",
display_artists_section: false,
})
this.profile.set({ owner_type: "PartnerInstitution" })
const sections = this.view.getDisplayableSections(
this.view.getSections()
)
return sections.should.eql(["overview", "about"])
})
})
return describe("with maximum data to display", function () {
beforeEach(function () {
return this.partner.set({
partner_artists_count: 1,
displayable_shows_count: 1,
display_artists_section: true,
published_not_for_sale_artworks_count: 1,
published_for_sale_artworks_count: 1,
})
})
describe("gallery", function () {
beforeEach(function () {
this.partner.set({
type: "Gallery",
claimed: true,
})
return this.profile.set({ owner_type: "PartnerGallery" })
})
it("returns proper sections when display works section is disabled", function () {
this.partner.set({ display_works_section: false })
const sections = this.view.getDisplayableSections(
this.view.getSections()
)
return sections.should.eql([
"overview",
"shows",
"artists",
"contact",
])
})
it("returns proper sections when display work section is enabled", function () {
this.partner.set({ display_works_section: true })
const sections = this.view.getDisplayableSections(
this.view.getSections()
)
return sections.should.eql([
"overview",
"shows",
"works",
"artists",
"contact",
])
})
it("includes articles when @partnerArticlesCount > 0", function () {
this.view.partnerArticlesCount = 1
const sections = this.view.getDisplayableSections(
this.view.getSections()
)
return sections.should.eql([
"overview",
"shows",
"artists",
"articles",
"contact",
])
})
return it("does not include articles when @partnerArticlesCount is 0", function () {
this.view.partnerArticlesCount = 0
const sections = this.view.getDisplayableSections(
this.view.getSections()
)
return sections.should.eql([
"overview",
"shows",
"artists",
"contact",
])
})
})
return describe("institution", function () {
beforeEach(function () {
this.partner.set({ type: "Institution" })
return this.profile.set({ owner_type: "PartnerInstitution" })
})
it("returns proper sections when display works section is disabled", function () {
this.partner.set({ display_works_section: false })
const sections = this.view.getDisplayableSections(
this.view.getSections()
)
return sections.should.eql([
"overview",
"shows",
"artists",
"shop",
"about",
])
})
it("returns proper sections when display work section is enabled", function () {
this.partner.set({ display_works_section: true })
const sections = this.view.getDisplayableSections(
this.view.getSections()
)
return sections.should.eql([
"overview",
"shows",
"collection",
"artists",
"shop",
"about",
])
})
it("returns proper sections when display_artists_section is disabled", function () {
this.partner.set({ display_artists_section: false })
const sections = this.view.getDisplayableSections(
this.view.getSections()
)
return sections.should.eql(["overview", "shows", "shop", "about"])
})
it("returns proper sections when display_artists_section is enabled", function () {
this.partner.set({ display_artists_section: true })
const sections = this.view.getDisplayableSections(
this.view.getSections()
)
return sections.should.eql([
"overview",
"shows",
"artists",
"shop",
"about",
])
})
it("includes articles when @partnerArticlesCount > 0", function () {
this.view.partnerArticlesCount = 1
const sections = this.view.getDisplayableSections(
this.view.getSections()
)
return sections.should.eql([
"overview",
"shows",
"articles",
"artists",
"shop",
"about",
])
})
return it("does not include articles when @partnerArticlesCount is 0", function () {
this.view.partnerArticlesCount = 0
const sections = this.view.getDisplayableSections(
this.view.getSections()
)
return sections.should.eql([
"overview",
"shows",
"artists",
"shop",
"about",
])
})
})
})
})
describe("#initializeTablistAndContent", () =>
it("renders tabs properly", function () {
this.view.initializeTablistAndContent()
_.last(this.tablistTemplate.args)[0]
.profile.get("id")
.should.equal(this.profile.get("id"))
return _.last(this.tablistTemplate.args)[0].sections.should.eql([
"overview",
"about",
])
}))
return describe("#initializePartnerAndCounts", function () {
it("returns a thenable promise", function () {
return this.view
.initializePartnerAndCounts()
.then.should.be.a.Function()
})
it("makes proper requests to fetch partner and articles", function () {
this.view.initializePartnerAndCounts()
const requests = _.last(Backbone.sync.args, 2)
requests[0][1]
.url()
.should.endWith(`/api/v1/partner/${this.partner.get("id")}`)
requests[1][1].url.should.endWith("/api/articles")
return requests[1][2].data.should.eql({
partner_id: this.partner.get("_id"),
limit: 1,
published: true,
count: true,
})
})
return it("fetches and returns partner and articles and sets articles count", function () {
const nextSyncCall = Backbone.sync.args.length
const articles = new Articles([
fabricate("article"),
fabricate("article"),
])
articles.count = 2
Backbone.sync.onCall(nextSyncCall).yieldsTo("success", this.partner)
Backbone.sync.onCall(nextSyncCall + 1).yieldsTo("success", articles)
return this.view.initializePartnerAndCounts().then(() => {
return this.view.partnerArticlesCount.should.equal(2)
})
})
})
})
})
|
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @jest-environment jsdom
*/
/* eslint-env browser */
import {isError} from '../utils';
// Copied from https://github.com/graingert/angular.js/blob/a43574052e9775cbc1d7dd8a086752c979b0f020/test/AngularSpec.js#L1883
describe('isError', () => {
function testErrorFromDifferentContext(createError) {
const iframe = document.createElement('iframe');
document.body.appendChild(iframe);
try {
const error = createError(iframe.contentWindow);
expect(isError(error)).toBe(true);
} finally {
iframe.parentElement.removeChild(iframe);
}
}
it('should not assume objects are errors', () => {
const fakeError = {message: 'A fake error', stack: 'no stack here'};
expect(isError(fakeError)).toBe(false);
});
it('should detect simple error instances', () => {
expect(isError(new Error())).toBe(true);
});
it('should detect errors from another context', () => {
testErrorFromDifferentContext(win => new win.Error());
});
it('should detect DOMException errors from another context', () => {
testErrorFromDifferentContext(win => {
try {
win.document.querySelectorAll('');
} catch (e) {
return e;
}
return null;
});
});
});
|
var tableToCSV = {
export: function(elm /*, delimiter */) {
var table = elm;
var rows = this.getRows(table);
var lines = [];
var delimiter = delimiter || ',';
for (var i = 0, numOfRows = rows.length; i < numOfRows; i++) {
var cols = this.getCols(rows[i]);
var line = [];
for (var j = 0, numOfCols = cols.length; j < numOfCols; j++) {
var text = cols[j].textContent || cols[j].innerText;
text = '"'+text.replace(/"/g, '""')+'"';
line.push(text);
}
lines.push(line.join(delimiter));
}
return lines.join("\r\n");
},
getRows: function(elm){
return Util.getNodesByName(elm, 'tr');
},
getCols: function(elm){
return Util.getNodesByName(elm, ['td', 'th']);
}
}
var Util = {
getNodesByName: function(elm /*, string or array*/) {
var children = elm.childNodes;
var nodeNames = ('string' === typeof arguments[1]) ? [arguments[1]] : arguments[1] ;
nodeNames = nodeNames.map(function(str){ return str.toLowerCase() });
var results = [];
for (var i = 0, max = children.length; i < max; i++ ) {
if (nodeNames.indexOf(children[i].nodeName.toLowerCase()) !== -1)
{
results.push(children[i]);
}
else
{
results = results.concat(this.getNodesByName(children[i], nodeNames));
}
}
return results;
}
}
window.onload = function(){
document.getElementById('download').addEventListener('click', function (e){
var csv = tableToCSV.export(document.getElementById('tbl0'));
var sjisArray = Encoding.convert(Encoding.stringToCode(csv), {to: 'SJIS'});
var blob = new Blob([new Uint8Array(sjisArray)], {type: 'text/csv'});
if (window.navigator.msSaveBlob) {
e.preventDefault();
window.navigator.msSaveBlob(blob, this.getAttribute('download'));
}
else {
this.href = URL.createObjectURL(blob);
}
});
}
function movRow(oj){
if(swt(oj)=='tbl0')
var targetId = 'tbl1'
else
var targetId = 'tbl0'
//クローン行作成
var coj = oj.parentNode.parentNode.cloneNode(true)
//ターゲットテーブルへクローン追加
var targetTable = document.getElementById(targetId)
targetTable.firstChild.insertBefore( coj , null )
//カレント行削除
oj.parentNode.parentNode.parentNode.removeChild(oj.parentNode.parentNode)
}
function movRowRight(oj)
{
var targetId = 'tbl1'
//クローン行作成
var coj = oj.parentNode.parentNode.cloneNode(true)
//ターゲットテーブルへクローン追加
var targetTable = document.getElementById(targetId)
targetTable.firstChild.insertBefore( coj , null)
//カレント行削除
oj.parentNode.parentNode.parentNode.removeChild(oj.parentNode.parentNode)
}
function movRowLeft(oj)
{
var targetId = 'tbl0'
//クローン行作成
var coj = oj.parentNode.parentNode.cloneNode(true)
//ターゲットテーブルへクローン追加
var targetTable = document.getElementById(targetId)
targetTable.firstChild.insertBefore( coj , null )
//カレント行削除
oj.parentNode.parentNode.parentNode.removeChild(oj.parentNode.parentNode)
}
function AllNotSend() {
var table = document.getElementById('tbl0');
var collection = table.rows;
for(var i=1; i<table.rows.length;){
var tr = collection.item(1);
var td = tr.cells.item(1);
movRowRight(td.firstChild);
}
}
function AllSend() {
var table = document.getElementById('tbl1');
var collection = table.rows;
for(var i=1; i<table.rows.length;){
var tr = collection.item(1);
var td = tr.cells.item(1);
movRowLeft(td.firstChild);
}
}
function hakodate(){
var table = document.getElementById('tbl1')
var collection = table.rows
for(var i=0; i<table.rows.length;){
var tr = collection.item(i)
var td = tr.cells.item(3)
if(td.firstChild.nodeValue.indexOf('函館市') != -1){
movRowLeft(td.firstChild)
}else if(td.firstChild.nodeValue.indexOf('七飯町') != -1){
movRowLeft(td.firstChild)
}else if(td.firstChild.nodeValue.indexOf('北斗市') != -1){
movRowLeft(td.firstChild)
}else if(td.firstChild.nodeValue.indexOf('森町') != -1){
movRowLeft(td.firstChild)
}else{
i++;
}
}
}
function first(){
var table = document.getElementById('tbl1')
var collection = table.rows
for(var i=0; i<table.rows.length;){
var tr = collection.item(i)
var td = tr.cells.item(6)
if(td.firstChild.nodeValue.indexOf('1年生') != -1){
movRowLeft(td.firstChild)
}else{
i++;
}
}
}
function second(){
var table = document.getElementById('tbl1')
var collection = table.rows
for(var i=0; i<table.rows.length;){
var tr = collection.item(i)
var td = tr.cells.item(6)
if(td.firstChild.nodeValue.indexOf('2年生') != -1){
movRowLeft(td.firstChild)
}else{
i++;
}
}
}
function third(){
var table = document.getElementById('tbl1')
var collection = table.rows
for(var i=0; i<table.rows.length;){
var tr = collection.item(i)
var td = tr.cells.item(6)
if(td.firstChild.nodeValue.indexOf('3年生') != -1){
movRowLeft(td.firstChild)
}else{
i++;
}
}
}
function fourth(){
var table = document.getElementById('tbl1')
var collection = table.rows
for(var i=0; i<table.rows.length;){
var tr = collection.item(i)
var td = tr.cells.item(6)
if(td.firstChild.nodeValue.indexOf('4年生') != -1){
movRowLeft(td.firstChild)
}else{
i++;
}
}
}
function fifth(){
var table = document.getElementById('tbl1')
var collection = table.rows
for(var i=0; i<table.rows.length;){
var tr = collection.item(i)
var td = tr.cells.item(6)
if(td.firstChild.nodeValue.indexOf('5年生') != -1){
movRowLeft(td.firstChild)
}else{
i++;
}
}
}
function sixth(){
var table = document.getElementById('tbl1')
var collection = table.rows
for(var i=0; i<table.rows.length;){
var tr = collection.item(i)
var td = tr.cells.item(6)
if(td.firstChild.nodeValue.indexOf('6年生') != -1){
movRowLeft(td.firstChild)
}else{
i++;
}
}
}
function swt(oj){
return oj.parentNode.parentNode.parentNode.parentNode.getAttribute('id')
}
function boxCheck(){
for(var i=0;i<6;i++){
if(document.chbox.elements[i].checked == true){
AllNotSend();
break;
}
}
for(var i=0;i<6;i++){
if(document.chbox.elements[i].checked == true){
if(i==0){first();}
if(i==1){second();}
if(i==2){third();}
if(i==3){fourth();}
if(i==4){fifth();}
if(i==5){sixth();}
}
}
if(document.chbox.elements[0].checked == false &&
document.chbox.elements[1].checked == false &&
document.chbox.elements[2].checked == false &&
document.chbox.elements[3].checked == false &&
document.chbox.elements[4].checked == false &&
document.chbox.elements[5].checked == false){
alert("学年にチェックをつけてください");
}
}
function home(){
href = "botn.html";
ret = confirm("スタート画面に戻ります。よろしいですか?");
if(ret == true){
location.href = href;
}
}
|
// Flags: --expose-internals --no-warnings
'use strict';
const common = require('../common');
const {
Event,
EventTarget,
defineEventHandler
} = require('internal/event_target');
const {
ok,
deepStrictEqual,
strictEqual,
throws,
} = require('assert');
const { once } = require('events');
const { promisify } = require('util');
const delay = promisify(setTimeout);
// The globals are defined.
ok(Event);
ok(EventTarget);
// The warning event has special behavior regarding attaching listeners
let lastWarning;
process.on('warning', (e) => {
lastWarning = e;
});
// Utility promise for parts of the test that need to wait for eachother -
// Namely tests for warning events
/* eslint-disable no-unused-vars */
let asyncTest = Promise.resolve();
// First, test Event
{
const ev = new Event('foo');
strictEqual(ev.type, 'foo');
strictEqual(ev.cancelable, false);
strictEqual(ev.defaultPrevented, false);
strictEqual(typeof ev.timeStamp, 'number');
// Compatibility properties with the DOM
deepStrictEqual(ev.composedPath(), []);
strictEqual(ev.returnValue, true);
strictEqual(ev.bubbles, false);
strictEqual(ev.composed, false);
strictEqual(ev.isTrusted, false);
strictEqual(ev.eventPhase, 0);
strictEqual(ev.cancelBubble, false);
// Not cancelable
ev.preventDefault();
strictEqual(ev.defaultPrevented, false);
}
{
const ev = new Event('foo');
strictEqual(ev.cancelBubble, false);
ev.cancelBubble = true;
strictEqual(ev.cancelBubble, true);
}
{
const ev = new Event('foo');
strictEqual(ev.cancelBubble, false);
ev.stopPropagation();
strictEqual(ev.cancelBubble, true);
}
{
const ev = new Event('foo');
strictEqual(ev.cancelBubble, false);
ev.cancelBubble = 'some-truthy-value';
strictEqual(ev.cancelBubble, true);
}
{
// No argument behavior - throw TypeError
throws(() => {
new Event();
}, TypeError);
// Too many arguments passed behavior - ignore additional arguments
const ev = new Event('foo', {}, {});
strictEqual(ev.type, 'foo');
}
{
const ev = new Event('foo');
strictEqual(ev.cancelBubble, false);
ev.cancelBubble = true;
strictEqual(ev.cancelBubble, true);
}
{
const ev = new Event('foo');
strictEqual(ev.cancelBubble, false);
ev.stopPropagation();
strictEqual(ev.cancelBubble, true);
}
{
const ev = new Event('foo');
strictEqual(ev.cancelBubble, false);
ev.cancelBubble = 'some-truthy-value';
strictEqual(ev.cancelBubble, true);
}
{
const ev = new Event('foo', { cancelable: true });
strictEqual(ev.type, 'foo');
strictEqual(ev.cancelable, true);
strictEqual(ev.defaultPrevented, false);
ev.preventDefault();
strictEqual(ev.defaultPrevented, true);
throws(() => new Event(Symbol()), TypeError);
}
{
const ev = new Event('foo');
deepStrictEqual(Object.keys(ev), ['isTrusted']);
}
{
const eventTarget = new EventTarget();
const ev1 = common.mustCall(function(event) {
strictEqual(event.type, 'foo');
strictEqual(this, eventTarget);
strictEqual(event.eventPhase, 2);
}, 2);
const ev2 = {
handleEvent: common.mustCall(function(event) {
strictEqual(event.type, 'foo');
strictEqual(this, ev2);
})
};
eventTarget.addEventListener('foo', ev1);
eventTarget.addEventListener('foo', ev2, { once: true });
ok(eventTarget.dispatchEvent(new Event('foo')));
eventTarget.dispatchEvent(new Event('foo'));
eventTarget.removeEventListener('foo', ev1);
eventTarget.dispatchEvent(new Event('foo'));
}
{
// event subclassing
const SubEvent = class extends Event {};
const ev = new SubEvent('foo');
const eventTarget = new EventTarget();
const fn = common.mustCall((event) => strictEqual(event, ev));
eventTarget.addEventListener('foo', fn, { once: true });
eventTarget.dispatchEvent(ev);
}
{
const eventTarget = new EventTarget();
const event = new Event('foo', { cancelable: true });
eventTarget.addEventListener('foo', (event) => event.preventDefault());
ok(!eventTarget.dispatchEvent(event));
}
{
// Adding event listeners with a boolean useCapture
const eventTarget = new EventTarget();
const event = new Event('foo');
const fn = common.mustCall((event) => strictEqual(event.type, 'foo'));
eventTarget.addEventListener('foo', fn, false);
eventTarget.dispatchEvent(event);
}
{
const uncaughtException = common.mustCall((err, event) => {
strictEqual(err.message, 'boom');
strictEqual(event.type, 'foo');
}, 4);
// Whether or not the handler function is async or not, errors
// are routed to uncaughtException
process.on('error', uncaughtException);
const eventTarget = new EventTarget();
const ev1 = async () => { throw new Error('boom'); };
const ev2 = () => { throw new Error('boom'); };
const ev3 = { handleEvent() { throw new Error('boom'); } };
const ev4 = { async handleEvent() { throw new Error('boom'); } };
// Errors in a handler won't stop calling the others.
eventTarget.addEventListener('foo', ev1, { once: true });
eventTarget.addEventListener('foo', ev2, { once: true });
eventTarget.addEventListener('foo', ev3, { once: true });
eventTarget.addEventListener('foo', ev4, { once: true });
eventTarget.dispatchEvent(new Event('foo'));
}
{
const eventTarget = new EventTarget();
// Once handler only invoked once
const ev = common.mustCall((event) => {
// Can invoke the same event name recursively
eventTarget.dispatchEvent(new Event('foo'));
});
// Errors in a handler won't stop calling the others.
eventTarget.addEventListener('foo', ev, { once: true });
eventTarget.dispatchEvent(new Event('foo'));
}
{
// Coercion to string works
strictEqual((new Event(1)).type, '1');
strictEqual((new Event(false)).type, 'false');
strictEqual((new Event({})).type, String({}));
const target = new EventTarget();
[
'foo',
{}, // No type event
undefined,
1,
false
].forEach((i) => {
throws(() => target.dispatchEvent(i), {
code: 'ERR_INVALID_ARG_TYPE'
});
});
[
'foo',
1,
{}, // No handleEvent function
false,
].forEach((i) => {
throws(() => target.addEventListener('foo', i), {
code: 'ERR_INVALID_ARG_TYPE'
});
});
[
'foo',
1,
{}, // No handleEvent function
false
].forEach((i) => {
throws(() => target.removeEventListener('foo', i), {
code: 'ERR_INVALID_ARG_TYPE'
});
});
}
{
const target = new EventTarget();
once(target, 'foo').then(common.mustCall());
target.dispatchEvent(new Event('foo'));
}
{
const target = new EventTarget();
const event = new Event('foo');
event.stopImmediatePropagation();
target.addEventListener('foo', common.mustNotCall());
target.dispatchEvent(event);
}
{
const target = new EventTarget();
const event = new Event('foo');
target.addEventListener('foo', common.mustCall((event) => {
event.stopImmediatePropagation();
}));
target.addEventListener('foo', common.mustNotCall());
target.dispatchEvent(event);
}
{
const target = new EventTarget();
const event = new Event('foo');
target.addEventListener('foo', common.mustCall((event) => {
event.stopImmediatePropagation();
}));
target.addEventListener('foo', common.mustNotCall());
target.dispatchEvent(event);
}
{
const target = new EventTarget();
const event = new Event('foo');
strictEqual(event.target, null);
target.addEventListener('foo', common.mustCall((event) => {
strictEqual(event.target, target);
strictEqual(event.currentTarget, target);
strictEqual(event.srcElement, target);
}));
target.dispatchEvent(event);
}
{
const target1 = new EventTarget();
const target2 = new EventTarget();
const event = new Event('foo');
target1.addEventListener('foo', common.mustCall((event) => {
throws(() => target2.dispatchEvent(event), {
code: 'ERR_EVENT_RECURSION'
});
}));
target1.dispatchEvent(event);
}
{
const target = new EventTarget();
const a = common.mustCall(() => target.removeEventListener('foo', a));
const b = common.mustCall(2);
target.addEventListener('foo', a);
target.addEventListener('foo', b);
target.dispatchEvent(new Event('foo'));
target.dispatchEvent(new Event('foo'));
}
{
const target = new EventTarget();
const a = common.mustCall(3);
target.addEventListener('foo', a, { capture: true });
target.addEventListener('foo', a, { capture: false });
target.dispatchEvent(new Event('foo'));
target.removeEventListener('foo', a, { capture: true });
target.dispatchEvent(new Event('foo'));
target.removeEventListener('foo', a, { capture: false });
target.dispatchEvent(new Event('foo'));
}
{
const target = new EventTarget();
strictEqual(target.toString(), '[object EventTarget]');
const event = new Event('');
strictEqual(event.toString(), '[object Event]');
}
{
const target = new EventTarget();
defineEventHandler(target, 'foo');
target.onfoo = common.mustCall();
target.dispatchEvent(new Event('foo'));
}
{
const target = new EventTarget();
defineEventHandler(target, 'foo');
let count = 0;
target.onfoo = () => count++;
target.onfoo = common.mustCall(() => count++);
target.dispatchEvent(new Event('foo'));
strictEqual(count, 1);
}
{
const target = new EventTarget();
defineEventHandler(target, 'foo');
let count = 0;
target.addEventListener('foo', () => count++);
target.onfoo = common.mustCall(() => count++);
target.dispatchEvent(new Event('foo'));
strictEqual(count, 2);
}
{
const target = new EventTarget();
defineEventHandler(target, 'foo');
const fn = common.mustNotCall();
target.onfoo = fn;
strictEqual(target.onfoo, fn);
target.onfoo = null;
target.dispatchEvent(new Event('foo'));
}
{
// `this` value of dispatchEvent
const target = new EventTarget();
const target2 = new EventTarget();
const event = new Event('foo');
ok(target.dispatchEvent.call(target2, event));
[
'foo',
{},
[],
1,
null,
undefined,
false,
Symbol(),
/a/
].forEach((i) => {
throws(() => target.dispatchEvent.call(i, event), {
code: 'ERR_INVALID_THIS'
});
});
}
{
strictEqual(Event.NONE, 0);
strictEqual(Event.CAPTURING_PHASE, 1);
strictEqual(Event.AT_TARGET, 2);
strictEqual(Event.BUBBLING_PHASE, 3);
strictEqual(new Event('foo').eventPhase, Event.NONE);
const target = new EventTarget();
target.addEventListener('foo', common.mustCall((e) => {
strictEqual(e.eventPhase, Event.AT_TARGET);
}), { once: true });
target.dispatchEvent(new Event('foo'));
}
{
const target = new EventTarget();
const ev = new Event('toString');
const fn = common.mustCall((event) => strictEqual(event.type, 'toString'));
target.addEventListener('toString', fn);
target.dispatchEvent(ev);
}
{
const target = new EventTarget();
const ev = new Event('__proto__');
const fn = common.mustCall((event) => strictEqual(event.type, '__proto__'));
target.addEventListener('__proto__', fn);
target.dispatchEvent(ev);
}
{
const eventTarget = new EventTarget();
// Single argument throws
throws(() => eventTarget.addEventListener('foo'), TypeError);
// Null events - does not throw
eventTarget.addEventListener('foo', null);
eventTarget.removeEventListener('foo', null);
eventTarget.addEventListener('foo', undefined);
eventTarget.removeEventListener('foo', undefined);
// Strings, booleans
throws(() => eventTarget.addEventListener('foo', 'hello'), TypeError);
throws(() => eventTarget.addEventListener('foo', false), TypeError);
throws(() => eventTarget.addEventListener('foo', Symbol()), TypeError);
asyncTest = asyncTest.then(async () => {
const eventTarget = new EventTarget();
// Single argument throws
throws(() => eventTarget.addEventListener('foo'), TypeError);
// Null events - does not throw
eventTarget.addEventListener('foo', null);
eventTarget.removeEventListener('foo', null);
// Warnings always happen after nextTick, so wait for a timer of 0
await delay(0);
strictEqual(lastWarning.name, 'AddEventListenerArgumentTypeWarning');
strictEqual(lastWarning.target, eventTarget);
lastWarning = null;
eventTarget.addEventListener('foo', undefined);
await delay(0);
strictEqual(lastWarning.name, 'AddEventListenerArgumentTypeWarning');
strictEqual(lastWarning.target, eventTarget);
eventTarget.removeEventListener('foo', undefined);
// Strings, booleans
throws(() => eventTarget.addEventListener('foo', 'hello'), TypeError);
throws(() => eventTarget.addEventListener('foo', false), TypeError);
throws(() => eventTarget.addEventListener('foo', Symbol()), TypeError);
});
}
|
import isArchive from 'is-archive';
isArchive('any-string');
(isArchive('any-string'): boolean);
// $FlowExpectedError
isArchive(4);
// $FlowExpectedError
isArchive({});
// $FlowExpectedError
isArchive();
// $FlowExpectedError
isArchive(null);
// $FlowExpectedError
(isArchive('any-string'): number);
|
// # Custom Middleware
// The following custom middleware functions cannot yet be unit tested, and as such are kept separate from
// the testable custom middleware functions in middleware.js
var api = require('../api'),
bodyParser = require('body-parser'),
config = require('../config'),
crypto = require('crypto'),
errors = require('../errors'),
express = require('express'),
fs = require('fs'),
hbs = require('express-hbs'),
logger = require('morgan'),
middleware = require('./middleware'),
path = require('path'),
routes = require('../routes'),
slashes = require('connect-slashes'),
storage = require('../storage'),
url = require('url'),
_ = require('lodash'),
passport = require('passport'),
oauth = require('./oauth'),
oauth2orize = require('oauth2orize'),
authStrategies = require('./auth-strategies'),
utils = require('../utils'),
sitemapHandler = require('../data/sitemap/handler'),
capnp = require('capnp'),
Promise = require('bluebird'),
blogApp,
setupMiddleware;
// ##Custom Middleware
var HackSession = capnp.importSystem("hack-session.capnp");
var publicIdPromise;
// ### GhostLocals Middleware
// Expose the standard locals that every external page should have available,
// separating between the theme and the admin
function ghostLocals(req, res, next) {
// Make sure we have a locals value.
res.locals = res.locals || {};
res.locals.version = config.ghostVersion;
// relative path from the URL
res.locals.relativeUrl = req.path;
var context = {user: 1};
if (res.isAdmin) {
req.user = { id: 1 };
if (!publicIdPromise) {
var connection = capnp.connect("unix:/tmp/sandstorm-api");
var session = connection.restore("HackSessionContext", HackSession.HackSessionContext);
publicIdPromise = session.getPublicId();
}
// res.locals.csrfToken = req.csrfToken();
Promise.all([
api.users.read({id: req.user.id, include: 'roles', context: context}),
publicIdPromise
]).then(function (values) {
var currentUser = values[0].users[0],
publicIdData = values[1];
if (currentUser.name === "Sandstorm") {
console.log('Changing sandstorm user name');
var hackUser = {id: '1', context: context};
currentUser.name = decodeURIComponent(req.headers['x-sandstorm-username']);
api.users.edit(values[0], hackUser).then(function () {console.log('Successfully changed user name');}).otherwise(function (err) {console.log('Failed changed user name', err);});
}
_.extend(res.locals, {
currentUser: {
name: currentUser.name,
email: currentUser.email,
image: currentUser.image
},
sandstormHostname: publicIdData.hostname,
sandstormPublicId: publicIdData.publicId,
sandstormAutoUrl: publicIdData.autoUrl,
sandstormIsDemoUser: publicIdData.isDemoUser
});
next();
}).catch(function (err) {
console.log('Error logging in', err);
next();
});
} else {
next();
}
}
// ### Activate Theme
// Helper for manageAdminAndTheme
function activateTheme(activeTheme) {
var hbsOptions,
themePartials = path.join(config.paths.themePath, activeTheme, 'partials');
// clear the view cache
blogApp.cache = {};
// set view engine
hbsOptions = {partialsDir: [config.paths.helperTemplates]};
fs.stat(themePartials, function (err, stats) {
// Check that the theme has a partials directory before trying to use it
if (!err && stats && stats.isDirectory()) {
hbsOptions.partialsDir.push(themePartials);
}
});
blogApp.engine('hbs', hbs.express3(hbsOptions));
// Update user error template
errors.updateActiveTheme(activeTheme);
// Set active theme variable on the express server
blogApp.set('activeTheme', activeTheme);
}
// ### decideIsAdmin Middleware
// Uses the URL to detect whether this response should be an admin response
// This is used to ensure the right content is served, and is not for security purposes
function decideIsAdmin(req, res, next) {
res.isAdmin = req.url.lastIndexOf('/ghost/', 0) === 0;
next();
}
// ### configHbsForContext Middleware
// Setup handlebars for the current context (admin or theme)
function configHbsForContext(req, res, next) {
var themeData = config.theme;
if (req.secure && config.urlSSL) {
// For secure requests override .url property with the SSL version
themeData = _.clone(themeData);
themeData.url = config.urlSSL.replace(/\/$/, '');
}
hbs.updateTemplateOptions({data: {blog: themeData}});
blogApp.set('views', path.join(config.paths.themePath, blogApp.get('activeTheme')));
// Pass 'secure' flag to the view engine
// so that templates can choose 'url' vs 'urlSSL'
res.locals.secure = req.secure;
next();
}
// ### updateActiveTheme
// Updates the blogApp's activeTheme variable and subsequently
// activates that theme's views with the hbs templating engine if it
// is not yet activated.
function updateActiveTheme(req, res, next) {
api.settings.read({context: {internal: true}, key: 'activeTheme'}).then(function (response) {
var activeTheme = response.settings[0];
// Check if the theme changed
if (activeTheme.value !== blogApp.get('activeTheme')) {
// Change theme
if (!config.paths.availableThemes.hasOwnProperty(activeTheme.value)) {
if (!res.isAdmin) {
// Throw an error if the theme is not available, but not on the admin UI
return errors.throwError('The currently active theme ' + activeTheme.value + ' is missing.');
}
} else {
activateTheme(activeTheme.value);
}
}
next();
}).catch(function (err) {
// Trying to start up without the active theme present, setup a simple hbs instance
// and render an error page straight away.
blogApp.engine('hbs', hbs.express3());
next(err);
});
}
// Redirect to setup if no user exists
function redirectToSetup(req, res, next) {
/*jslint unparam:true*/
api.authentication.isSetup().then(function (exists) {
if (!exists.setup[0].status && !req.path.match(/\/setup\//)) {
return res.redirect(config.paths.subdir + '/ghost/setup/');
}
next();
}).catch(function (err) {
return next(new Error(err));
});
}
// Detect uppercase in req.path
function uncapitalise(req, res, next) {
var pathToTest = req.path,
isSignupOrReset = req.path.match(/(\/ghost\/(signup|reset)\/)/i),
isAPI = req.path.match(/(\/ghost\/api\/v[\d\.]+\/.*?\/)/i);
if (isSignupOrReset) {
pathToTest = isSignupOrReset[1];
}
// Do not lowercase anything after /api/v0.1/ to protect :key/:slug
if (isAPI) {
pathToTest = isAPI[1];
}
if (/[A-Z]/.test(pathToTest)) {
res.set('Cache-Control', 'public, max-age=' + utils.ONE_YEAR_S);
res.redirect(301, req.url.replace(pathToTest, pathToTest.toLowerCase()));
} else {
next();
}
}
function isSSLrequired(isAdmin) {
var forceSSL = url.parse(config.url).protocol === 'https:' ? true : false,
forceAdminSSL = (isAdmin && config.forceAdminSSL);
if (forceSSL || forceAdminSSL) {
return true;
}
return false;
}
// Check to see if we should use SSL
// and redirect if needed
function checkSSL(req, res, next) {
if (isSSLrequired(res.isAdmin)) {
if (!req.secure) {
var forceAdminSSL = config.forceAdminSSL,
redirectUrl;
// Check if forceAdminSSL: { redirect: false } is set, which means
// we should just deny non-SSL access rather than redirect
if (forceAdminSSL && forceAdminSSL.redirect !== undefined && !forceAdminSSL.redirect) {
return res.sendStatus(403);
}
redirectUrl = url.parse(config.urlSSL || config.url);
return res.redirect(301, url.format({
protocol: 'https:',
hostname: redirectUrl.hostname,
port: redirectUrl.port,
pathname: req.path,
query: req.query
}));
}
}
next();
}
// ### ServeSharedFile Middleware
// Handles requests to robots.txt and favicon.ico (and caches them)
function serveSharedFile(file, type, maxAge) {
var content,
filePath = path.join(config.paths.corePath, 'shared', file),
re = /(\{\{blog-url\}\})/g;
return function serveSharedFile(req, res, next) {
if (req.url === '/' + file) {
if (content) {
res.writeHead(200, content.headers);
res.end(content.body);
} else {
fs.readFile(filePath, function (err, buf) {
if (err) {
return next(err);
}
if (type === 'text/xsl' || type === 'text/plain') {
buf = buf.toString().replace(re, config.url.replace(/\/$/, ''));
}
content = {
headers: {
'Content-Type': type,
'Content-Length': buf.length,
ETag: '"' + crypto.createHash('md5').update(buf, 'utf8').digest('hex') + '"',
'Cache-Control': 'public, max-age=' + maxAge
},
body: buf
};
res.writeHead(200, content.headers);
res.end(content.body);
});
}
} else {
next();
}
};
}
setupMiddleware = function (blogAppInstance, adminApp) {
var logging = config.logging,
corePath = config.paths.corePath,
oauthServer = oauth2orize.createServer();
// silence JSHint without disabling unused check for the whole file
authStrategies = authStrategies;
// Cache express server instance
blogApp = blogAppInstance;
middleware.cacheBlogApp(blogApp);
middleware.cacheOauthServer(oauthServer);
oauth.init(oauthServer, middleware.resetSpamCounter);
// Make sure 'req.secure' is valid for proxied requests
// (X-Forwarded-Proto header will be checked, if present)
blogApp.enable('trust proxy');
// Logging configuration
if (logging !== false) {
if (blogApp.get('env') !== 'development') {
blogApp.use(logger('combined', logging));
} else {
blogApp.use(logger('dev', logging));
}
}
// Favicon
blogApp.use(serveSharedFile('favicon.ico', 'image/x-icon', utils.ONE_DAY_S));
blogApp.use(serveSharedFile('sitemap.xsl', 'text/xsl', utils.ONE_DAY_S));
// Static assets
blogApp.use('/shared', express['static'](path.join(corePath, '/shared'), {maxAge: utils.ONE_HOUR_MS}));
blogApp.use('/content/images', storage.getStorage().serve());
blogApp.use('/ghost/scripts', express['static'](path.join(corePath, '/built/scripts'), {maxAge: utils.ONE_YEAR_MS}));
blogApp.use('/public', express['static'](path.join(corePath, '/built/public'), {maxAge: utils.ONE_YEAR_MS}));
// First determine whether we're serving admin or theme content
blogApp.use(decideIsAdmin);
blogApp.use(updateActiveTheme);
blogApp.use(configHbsForContext);
// Admin only config
blogApp.use('/ghost', express['static'](path.join(corePath, '/client/assets'), {maxAge: utils.ONE_YEAR_MS}));
// Force SSL
// NOTE: Importantly this is _after_ the check above for admin-theme static resources,
// which do not need HTTPS. In fact, if HTTPS is forced on them, then 404 page might
// not display properly when HTTPS is not available!
blogApp.use(checkSSL);
adminApp.set('views', config.paths.adminViews);
// Theme only config
blogApp.use(middleware.staticTheme());
// Serve robots.txt if not found in theme
blogApp.use(serveSharedFile('robots.txt', 'text/plain', utils.ONE_HOUR_S));
// site map
sitemapHandler(blogApp);
// Add in all trailing slashes
blogApp.use(slashes(true, {
headers: {
'Cache-Control': 'public, max-age=' + utils.ONE_YEAR_S
}
}));
blogApp.use(uncapitalise);
// Body parsing
blogApp.use(bodyParser.json());
blogApp.use(bodyParser.urlencoded({extended: true}));
blogApp.use(passport.initialize());
// ### Caching
blogApp.use(middleware.cacheControl('public'));
adminApp.use(middleware.cacheControl('private'));
blogApp.use(routes.apiBaseUri, middleware.cacheControl('private'));
// enable authentication
blogApp.use(middleware.authenticate);
// local data
blogApp.use(ghostLocals);
// ### Routing
// Set up API routes
blogApp.use(routes.apiBaseUri, routes.api(middleware));
// Mount admin express app to /ghost and set up routes
adminApp.use(middleware.redirectToSetup);
adminApp.use(routes.admin());
blogApp.use('/ghost', adminApp);
// Set up Frontend routes
blogApp.use(routes.frontend());
// ### Error handling
// 404 Handler
blogApp.use(errors.error404);
// 500 Handler
blogApp.use(errors.error500);
};
module.exports = setupMiddleware;
// Export middleware functions directly
module.exports.middleware = middleware;
// Expose middleware functions in this file as well
module.exports.middleware.redirectToSetup = redirectToSetup;
|
/**
* angular-strap
* @version v2.1.6 - 2015-02-03
* @link http://mgcrea.github.io/angular-strap
* @author Olivier Louvignes (olivier@mg-crea.com)
* @license MIT License, http://www.opensource.org/licenses/MIT
*/
'use strict';
angular.module('mgcrea.ngStrap.helpers.dimensions', [])
.factory('dimensions', ["$document", "$window", function($document, $window) {
var jqLite = angular.element;
var fn = {};
/**
* Test the element nodeName
* @param element
* @param name
*/
var nodeName = fn.nodeName = function(element, name) {
return element.nodeName && element.nodeName.toLowerCase() === name.toLowerCase();
};
/**
* Returns the element computed style
* @param element
* @param prop
* @param extra
*/
fn.css = function(element, prop, extra) {
var value;
if (element.currentStyle) { //IE
value = element.currentStyle[prop];
} else if (window.getComputedStyle) {
value = window.getComputedStyle(element)[prop];
} else {
value = element.style[prop];
}
return extra === true ? parseFloat(value) || 0 : value;
};
/**
* Provides read-only equivalent of jQuery's offset function:
* @required-by bootstrap-tooltip, bootstrap-affix
* @url http://api.jquery.com/offset/
* @param element
*/
fn.offset = function(element) {
var boxRect = element.getBoundingClientRect();
var docElement = element.ownerDocument;
return {
width: boxRect.width || element.offsetWidth,
height: boxRect.height || element.offsetHeight,
top: boxRect.top + (window.pageYOffset || docElement.documentElement.scrollTop) - (docElement.documentElement.clientTop || 0),
left: boxRect.left + (window.pageXOffset || docElement.documentElement.scrollLeft) - (docElement.documentElement.clientLeft || 0)
};
};
/**
* Provides read-only equivalent of jQuery's position function
* @required-by bootstrap-tooltip, bootstrap-affix
* @url http://api.jquery.com/offset/
* @param element
*/
fn.position = function(element) {
var offsetParentRect = {top: 0, left: 0},
offsetParentElement,
offset;
// Fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is it's only offset parent
if (fn.css(element, 'position') === 'fixed') {
// We assume that getBoundingClientRect is available when computed position is fixed
offset = element.getBoundingClientRect();
} else {
// Get *real* offsetParentElement
offsetParentElement = offsetParent(element);
// Get correct offsets
offset = fn.offset(element);
if (!nodeName(offsetParentElement, 'html')) {
offsetParentRect = fn.offset(offsetParentElement);
}
// Add offsetParent borders
offsetParentRect.top += fn.css(offsetParentElement, 'borderTopWidth', true);
offsetParentRect.left += fn.css(offsetParentElement, 'borderLeftWidth', true);
}
// Subtract parent offsets and element margins
return {
width: element.offsetWidth,
height: element.offsetHeight,
top: offset.top - offsetParentRect.top - fn.css(element, 'marginTop', true),
left: offset.left - offsetParentRect.left - fn.css(element, 'marginLeft', true)
};
};
/**
* Returns the closest, non-statically positioned offsetParent of a given element
* @required-by fn.position
* @param element
*/
var offsetParent = function offsetParentElement(element) {
var docElement = element.ownerDocument;
var offsetParent = element.offsetParent || docElement;
if(nodeName(offsetParent, '#document')) return docElement.documentElement;
while(offsetParent && !nodeName(offsetParent, 'html') && fn.css(offsetParent, 'position') === 'static') {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || docElement.documentElement;
};
/**
* Provides equivalent of jQuery's height function
* @required-by bootstrap-affix
* @url http://api.jquery.com/height/
* @param element
* @param outer
*/
fn.height = function(element, outer) {
var value = element.offsetHeight;
if(outer) {
value += fn.css(element, 'marginTop', true) + fn.css(element, 'marginBottom', true);
} else {
value -= fn.css(element, 'paddingTop', true) + fn.css(element, 'paddingBottom', true) + fn.css(element, 'borderTopWidth', true) + fn.css(element, 'borderBottomWidth', true);
}
return value;
};
/**
* Provides equivalent of jQuery's width function
* @required-by bootstrap-affix
* @url http://api.jquery.com/width/
* @param element
* @param outer
*/
fn.width = function(element, outer) {
var value = element.offsetWidth;
if(outer) {
value += fn.css(element, 'marginLeft', true) + fn.css(element, 'marginRight', true);
} else {
value -= fn.css(element, 'paddingLeft', true) + fn.css(element, 'paddingRight', true) + fn.css(element, 'borderLeftWidth', true) + fn.css(element, 'borderRightWidth', true);
}
return value;
};
return fn;
}]);
|
/**!
* Sortable
* @author RubaXa <trash@rubaxa.org>
* @license MIT
*/
(function (factory) {
"use strict";
if (typeof define === "function" && define.amd) {
define(factory);
}
else if (typeof module != "undefined" && typeof module.exports != "undefined") {
module.exports = factory();
}
else if (typeof Package !== "undefined") {
Sortable = factory(); // export for Meteor.js
}
else {
/* jshint sub:true */
window["Sortable"] = factory();
}
})(function () {
"use strict";
var dragEl,
parentEl,
ghostEl,
cloneEl,
rootEl,
nextEl,
scrollEl,
scrollParentEl,
lastEl,
lastCSS,
lastParentCSS,
oldIndex,
newIndex,
activeGroup,
autoScroll = {},
tapEvt,
touchEvt,
moved,
/** @const */
RSPACE = /\s+/g,
expando = 'Sortable' + (new Date).getTime(),
win = window,
document = win.document,
parseInt = win.parseInt,
supportDraggable = !!('draggable' in document.createElement('div')),
supportCssPointerEvents = (function (el) {
el = document.createElement('x');
el.style.cssText = 'pointer-events:auto';
return el.style.pointerEvents === 'auto';
})(),
_silent = false,
abs = Math.abs,
slice = [].slice,
touchDragOverListeners = [],
_autoScroll = _throttle(function (/**Event*/evt, /**Object*/options, /**HTMLElement*/rootEl) {
// Bug: https://bugzilla.mozilla.org/show_bug.cgi?id=505521
if (rootEl && options.scroll) {
var el,
rect,
sens = options.scrollSensitivity,
speed = options.scrollSpeed,
x = evt.clientX,
y = evt.clientY,
winWidth = window.innerWidth,
winHeight = window.innerHeight,
vx,
vy
;
// Delect scrollEl
if (scrollParentEl !== rootEl) {
scrollEl = options.scroll;
scrollParentEl = rootEl;
if (scrollEl === true) {
scrollEl = rootEl;
do {
if ((scrollEl.offsetWidth < scrollEl.scrollWidth) ||
(scrollEl.offsetHeight < scrollEl.scrollHeight)
) {
break;
}
/* jshint boss:true */
} while (scrollEl = scrollEl.parentNode);
}
}
if (scrollEl) {
el = scrollEl;
rect = scrollEl.getBoundingClientRect();
vx = (abs(rect.right - x) <= sens) - (abs(rect.left - x) <= sens);
vy = (abs(rect.bottom - y) <= sens) - (abs(rect.top - y) <= sens);
}
if (!(vx || vy)) {
vx = (winWidth - x <= sens) - (x <= sens);
vy = (winHeight - y <= sens) - (y <= sens);
/* jshint expr:true */
(vx || vy) && (el = win);
}
if (autoScroll.vx !== vx || autoScroll.vy !== vy || autoScroll.el !== el) {
autoScroll.el = el;
autoScroll.vx = vx;
autoScroll.vy = vy;
clearInterval(autoScroll.pid);
if (el) {
autoScroll.pid = setInterval(function () {
if (el === win) {
win.scrollTo(win.pageXOffset + vx * speed, win.pageYOffset + vy * speed);
} else {
vy && (el.scrollTop += vy * speed);
vx && (el.scrollLeft += vx * speed);
}
}, 24);
}
}
}
}, 30),
_prepareGroup = function (options) {
var group = options.group;
if (!group || typeof group != 'object') {
group = options.group = {name: group};
}
['pull', 'put'].forEach(function (key) {
if (!(key in group)) {
group[key] = true;
}
});
options.groups = ' ' + group.name + (group.put.join ? ' ' + group.put.join(' ') : '') + ' ';
}
;
/**
* @class Sortable
* @param {HTMLElement} el
* @param {Object} [options]
*/
function Sortable(el, options) {
this.el = el; // root element
this.options = options = _extend({}, options);
// Export instance
el[expando] = this;
// Default options
var defaults = {
group: Math.random(),
sort: true,
disabled: false,
store: null,
handle: null,
scroll: true,
scrollSensitivity: 30,
scrollSpeed: 10,
draggable: /[uo]l/i.test(el.nodeName) ? 'li' : '>*',
ghostClass: 'sortable-ghost',
chosenClass: 'sortable-chosen',
ignore: 'a, img',
filter: null,
animation: 0,
setData: function (dataTransfer, dragEl) {
dataTransfer.setData('Text', dragEl.textContent);
},
dropBubble: false,
dragoverBubble: false,
dataIdAttr: 'data-id',
delay: 0,
forceFallback: false,
fallbackClass: 'sortable-fallback',
fallbackOnBody: false
};
// Set default options
for (var name in defaults) {
!(name in options) && (options[name] = defaults[name]);
}
_prepareGroup(options);
// Bind all private methods
for (var fn in this) {
if (fn.charAt(0) === '_') {
this[fn] = this[fn].bind(this);
}
}
// Setup drag mode
this.nativeDraggable = options.forceFallback ? false : supportDraggable;
// Bind events
_on(el, 'mousedown', this._onTapStart);
_on(el, 'touchstart', this._onTapStart);
if (this.nativeDraggable) {
_on(el, 'dragover', this);
_on(el, 'dragenter', this);
}
touchDragOverListeners.push(this._onDragOver);
// Restore sorting
options.store && this.sort(options.store.get(this));
}
Sortable.prototype = /** @lends Sortable.prototype */ {
constructor: Sortable,
_onTapStart: function (/** Event|TouchEvent */evt) {
var _this = this,
el = this.el,
options = this.options,
type = evt.type,
touch = evt.touches && evt.touches[0],
target = (touch || evt).target,
originalTarget = target,
filter = options.filter;
if (type === 'mousedown' && evt.button !== 0 || options.disabled) {
return; // only left button or enabled
}
target = _closest(target, options.draggable, el);
if (!target) {
return;
}
// get the index of the dragged element within its parent
oldIndex = _index(target);
// Check filter
if (typeof filter === 'function') {
if (filter.call(this, evt, target, this)) {
_dispatchEvent(_this, originalTarget, 'filter', target, el, oldIndex);
evt.preventDefault();
return; // cancel dnd
}
}
else if (filter) {
filter = filter.split(',').some(function (criteria) {
criteria = _closest(originalTarget, criteria.trim(), el);
if (criteria) {
_dispatchEvent(_this, criteria, 'filter', target, el, oldIndex);
return true;
}
});
if (filter) {
evt.preventDefault();
return; // cancel dnd
}
}
if (options.handle && !_closest(originalTarget, options.handle, el)) {
return;
}
// Prepare `dragstart`
this._prepareDragStart(evt, touch, target);
},
_prepareDragStart: function (/** Event */evt, /** Touch */touch, /** HTMLElement */target) {
var _this = this,
el = _this.el,
options = _this.options,
ownerDocument = el.ownerDocument,
dragStartFn;
if (target && !dragEl && (target.parentNode === el)) {
tapEvt = evt;
rootEl = el;
dragEl = target;
parentEl = dragEl.parentNode;
nextEl = dragEl.nextSibling;
activeGroup = options.group;
dragStartFn = function () {
// Delayed drag has been triggered
// we can re-enable the events: touchmove/mousemove
_this._disableDelayedDrag();
// Make the element draggable
dragEl.draggable = true;
// Chosen item
_toggleClass(dragEl, _this.options.chosenClass, true);
// Bind the events: dragstart/dragend
_this._triggerDragStart(touch);
};
// Disable "draggable"
options.ignore.split(',').forEach(function (criteria) {
_find(dragEl, criteria.trim(), _disableDraggable);
});
_on(ownerDocument, 'mouseup', _this._onDrop);
_on(ownerDocument, 'touchend', _this._onDrop);
_on(ownerDocument, 'touchcancel', _this._onDrop);
if (options.delay) {
// If the user moves the pointer or let go the click or touch
// before the delay has been reached:
// disable the delayed drag
_on(ownerDocument, 'mouseup', _this._disableDelayedDrag);
_on(ownerDocument, 'touchend', _this._disableDelayedDrag);
_on(ownerDocument, 'touchcancel', _this._disableDelayedDrag);
_on(ownerDocument, 'mousemove', _this._disableDelayedDrag);
_on(ownerDocument, 'touchmove', _this._disableDelayedDrag);
_this._dragStartTimer = setTimeout(dragStartFn, options.delay);
} else {
dragStartFn();
}
}
},
_disableDelayedDrag: function () {
var ownerDocument = this.el.ownerDocument;
clearTimeout(this._dragStartTimer);
_off(ownerDocument, 'mouseup', this._disableDelayedDrag);
_off(ownerDocument, 'touchend', this._disableDelayedDrag);
_off(ownerDocument, 'touchcancel', this._disableDelayedDrag);
_off(ownerDocument, 'mousemove', this._disableDelayedDrag);
_off(ownerDocument, 'touchmove', this._disableDelayedDrag);
},
_triggerDragStart: function (/** Touch */touch) {
if (touch) {
// Touch device support
tapEvt = {
target: dragEl,
clientX: touch.clientX,
clientY: touch.clientY
};
this._onDragStart(tapEvt, 'touch');
}
else if (!this.nativeDraggable) {
this._onDragStart(tapEvt, true);
}
else {
_on(dragEl, 'dragend', this);
_on(rootEl, 'dragstart', this._onDragStart);
}
try {
if (document.selection) {
document.selection.empty();
} else {
window.getSelection().removeAllRanges();
}
} catch (err) {
}
},
_dragStarted: function () {
if (rootEl && dragEl) {
// Apply effect
_toggleClass(dragEl, this.options.ghostClass, true);
Sortable.active = this;
// Drag start event
_dispatchEvent(this, rootEl, 'start', dragEl, rootEl, oldIndex);
}
},
_emulateDragOver: function () {
if (touchEvt) {
if (this._lastX === touchEvt.clientX && this._lastY === touchEvt.clientY) {
return;
}
this._lastX = touchEvt.clientX;
this._lastY = touchEvt.clientY;
if (!supportCssPointerEvents) {
_css(ghostEl, 'display', 'none');
}
var target = document.elementFromPoint(touchEvt.clientX, touchEvt.clientY),
parent = target,
groupName = ' ' + this.options.group.name + '',
i = touchDragOverListeners.length;
if (parent) {
do {
if (parent[expando] && parent[expando].options.groups.indexOf(groupName) > -1) {
while (i--) {
touchDragOverListeners[i]({
clientX: touchEvt.clientX,
clientY: touchEvt.clientY,
target: target,
rootEl: parent
});
}
break;
}
target = parent; // store last element
}
/* jshint boss:true */
while (parent = parent.parentNode);
}
if (!supportCssPointerEvents) {
_css(ghostEl, 'display', '');
}
}
},
_onTouchMove: function (/**TouchEvent*/evt) {
if (tapEvt) {
// only set the status to dragging, when we are actually dragging
if (!Sortable.active) {
this._dragStarted();
}
// as well as creating the ghost element on the document body
this._appendGhost();
var touch = evt.touches ? evt.touches[0] : evt,
dx = touch.clientX - tapEvt.clientX,
dy = touch.clientY - tapEvt.clientY,
translate3d = evt.touches ? 'translate3d(' + dx + 'px,' + dy + 'px,0)' : 'translate(' + dx + 'px,' + dy + 'px)';
moved = true;
touchEvt = touch;
_css(ghostEl, 'webkitTransform', translate3d);
_css(ghostEl, 'mozTransform', translate3d);
_css(ghostEl, 'msTransform', translate3d);
_css(ghostEl, 'transform', translate3d);
evt.preventDefault();
}
},
_appendGhost: function () {
if (!ghostEl) {
var rect = dragEl.getBoundingClientRect(),
css = _css(dragEl),
ghostRect;
ghostEl = dragEl.cloneNode(true);
_toggleClass(ghostEl, this.options.ghostClass, false);
_toggleClass(ghostEl, this.options.fallbackClass, true);
_css(ghostEl, 'top', rect.top - parseInt(css.marginTop, 10));
_css(ghostEl, 'left', rect.left - parseInt(css.marginLeft, 10));
_css(ghostEl, 'width', rect.width);
_css(ghostEl, 'height', rect.height);
_css(ghostEl, 'opacity', '0.8');
_css(ghostEl, 'position', 'fixed');
_css(ghostEl, 'zIndex', '100000');
_css(ghostEl, 'pointerEvents', 'none');
this.options.fallbackOnBody && document.body.appendChild(ghostEl) || rootEl.appendChild(ghostEl);
// Fixing dimensions.
ghostRect = ghostEl.getBoundingClientRect();
_css(ghostEl, 'width', rect.width * 2 - ghostRect.width);
_css(ghostEl, 'height', rect.height * 2 - ghostRect.height);
}
},
_onDragStart: function (/**Event*/evt, /**boolean*/useFallback) {
var dataTransfer = evt.dataTransfer,
options = this.options;
this._offUpEvents();
if (activeGroup.pull == 'clone') {
cloneEl = dragEl.cloneNode(true);
_css(cloneEl, 'display', 'none');
rootEl.insertBefore(cloneEl, dragEl);
}
if (useFallback) {
if (useFallback === 'touch') {
// Bind touch events
_on(document, 'touchmove', this._onTouchMove);
_on(document, 'touchend', this._onDrop);
_on(document, 'touchcancel', this._onDrop);
} else {
// Old brwoser
_on(document, 'mousemove', this._onTouchMove);
_on(document, 'mouseup', this._onDrop);
}
this._loopId = setInterval(this._emulateDragOver, 50);
}
else {
if (dataTransfer) {
dataTransfer.effectAllowed = 'move';
options.setData && options.setData.call(this, dataTransfer, dragEl);
}
_on(document, 'drop', this);
setTimeout(this._dragStarted, 0);
}
},
_onDragOver: function (/**Event*/evt) {
var el = this.el,
target,
dragRect,
revert,
options = this.options,
group = options.group,
groupPut = group.put,
isOwner = (activeGroup === group),
canSort = options.sort;
if (evt.preventDefault !== void 0) {
evt.preventDefault();
!options.dragoverBubble && evt.stopPropagation();
}
moved = true;
if (activeGroup && !options.disabled &&
(isOwner
? canSort || (revert = !rootEl.contains(dragEl)) // Reverting item into the original list
: activeGroup.pull && groupPut && (
(activeGroup.name === group.name) || // by Name
(groupPut.indexOf && ~groupPut.indexOf(activeGroup.name)) // by Array
)
) &&
(evt.rootEl === void 0 || evt.rootEl === this.el) // touch fallback
) {
// Smart auto-scrolling
_autoScroll(evt, options, this.el);
if (_silent) {
return;
}
target = _closest(evt.target, options.draggable, el);
dragRect = dragEl.getBoundingClientRect();
if (revert) {
_cloneHide(true);
if (cloneEl || nextEl) {
rootEl.insertBefore(dragEl, cloneEl || nextEl);
}
else if (!canSort) {
rootEl.appendChild(dragEl);
}
return;
}
if ((el.children.length === 0) || (el.children[0] === ghostEl) ||
(el === evt.target) && (target = _ghostIsLast(el, evt))
) {
if (target) {
if (target.animated) {
return;
}
targetRect = target.getBoundingClientRect();
}
_cloneHide(isOwner);
if (_onMove(rootEl, el, dragEl, dragRect, target, targetRect) !== false) {
if (!dragEl.contains(el)) {
el.appendChild(dragEl);
parentEl = el; // actualization
}
this._animate(dragRect, dragEl);
target && this._animate(targetRect, target);
}
}
else if (target && !target.animated && target !== dragEl && (target.parentNode[expando] !== void 0)) {
if (lastEl !== target) {
lastEl = target;
lastCSS = _css(target);
lastParentCSS = _css(target.parentNode);
}
var targetRect = target.getBoundingClientRect(),
width = targetRect.right - targetRect.left,
height = targetRect.bottom - targetRect.top,
floating = /left|right|inline/.test(lastCSS.cssFloat + lastCSS.display)
|| (lastParentCSS.display == 'flex' && lastParentCSS['flex-direction'].indexOf('row') === 0),
isWide = (target.offsetWidth > dragEl.offsetWidth),
isLong = (target.offsetHeight > dragEl.offsetHeight),
halfway = (floating ? (evt.clientX - targetRect.left) / width : (evt.clientY - targetRect.top) / height) > 0.5,
nextSibling = target.nextElementSibling,
moveVector = _onMove(rootEl, el, dragEl, dragRect, target, targetRect),
after
;
if (moveVector !== false) {
_silent = true;
setTimeout(_unsilent, 30);
_cloneHide(isOwner);
if (moveVector === 1 || moveVector === -1) {
after = (moveVector === 1);
}
else if (floating) {
var elTop = dragEl.offsetTop,
tgTop = target.offsetTop;
if (elTop === tgTop) {
after = (target.previousElementSibling === dragEl) && !isWide || halfway && isWide;
} else {
after = tgTop > elTop;
}
} else {
after = (nextSibling !== dragEl) && !isLong || halfway && isLong;
}
if (!dragEl.contains(el)) {
if (after && !nextSibling) {
el.appendChild(dragEl);
} else {
target.parentNode.insertBefore(dragEl, after ? nextSibling : target);
}
}
parentEl = dragEl.parentNode; // actualization
this._animate(dragRect, dragEl);
this._animate(targetRect, target);
}
}
}
},
_animate: function (prevRect, target) {
var ms = this.options.animation;
if (ms) {
var currentRect = target.getBoundingClientRect();
_css(target, 'transition', 'none');
_css(target, 'transform', 'translate3d('
+ (prevRect.left - currentRect.left) + 'px,'
+ (prevRect.top - currentRect.top) + 'px,0)'
);
target.offsetWidth; // repaint
_css(target, 'transition', 'all ' + ms + 'ms');
_css(target, 'transform', 'translate3d(0,0,0)');
clearTimeout(target.animated);
target.animated = setTimeout(function () {
_css(target, 'transition', '');
_css(target, 'transform', '');
target.animated = false;
}, ms);
}
},
_offUpEvents: function () {
var ownerDocument = this.el.ownerDocument;
_off(document, 'touchmove', this._onTouchMove);
_off(ownerDocument, 'mouseup', this._onDrop);
_off(ownerDocument, 'touchend', this._onDrop);
_off(ownerDocument, 'touchcancel', this._onDrop);
},
_onDrop: function (/**Event*/evt) {
var el = this.el,
options = this.options;
clearInterval(this._loopId);
clearInterval(autoScroll.pid);
clearTimeout(this._dragStartTimer);
// Unbind events
_off(document, 'mousemove', this._onTouchMove);
if (this.nativeDraggable) {
_off(document, 'drop', this);
_off(el, 'dragstart', this._onDragStart);
}
this._offUpEvents();
if (evt) {
if (moved) {
evt.preventDefault();
!options.dropBubble && evt.stopPropagation();
}
ghostEl && ghostEl.parentNode.removeChild(ghostEl);
if (dragEl) {
if (this.nativeDraggable) {
_off(dragEl, 'dragend', this);
}
_disableDraggable(dragEl);
// Remove class's
_toggleClass(dragEl, this.options.ghostClass, false);
_toggleClass(dragEl, this.options.chosenClass, false);
if (rootEl !== parentEl) {
newIndex = _index(dragEl);
if (newIndex != -1) {
// drag from one list and drop into another
_dispatchEvent(null, parentEl, 'sort', dragEl, rootEl, oldIndex, newIndex);
_dispatchEvent(this, rootEl, 'sort', dragEl, rootEl, oldIndex, newIndex);
// Add event
_dispatchEvent(null, parentEl, 'add', dragEl, rootEl, oldIndex, newIndex);
// Remove event
_dispatchEvent(this, rootEl, 'remove', dragEl, rootEl, oldIndex, newIndex);
}
}
else {
// Remove clone
cloneEl && cloneEl.parentNode.removeChild(cloneEl);
if (dragEl.nextSibling !== nextEl) {
// Get the index of the dragged element within its parent
newIndex = _index(dragEl);
if (newIndex != -1) {
// drag & drop within the same list
_dispatchEvent(this, rootEl, 'update', dragEl, rootEl, oldIndex, newIndex);
_dispatchEvent(this, rootEl, 'sort', dragEl, rootEl, oldIndex, newIndex);
}
}
}
if (Sortable.active) {
// Drag end event
_dispatchEvent(this, rootEl, 'end', dragEl, rootEl, oldIndex, newIndex);
// Save sorting
this.save();
}
}
// Nulling
rootEl =
dragEl =
parentEl =
ghostEl =
nextEl =
cloneEl =
scrollEl =
scrollParentEl =
tapEvt =
touchEvt =
moved =
newIndex =
lastEl =
lastCSS =
activeGroup =
Sortable.active = null;
}
},
handleEvent: function (/**Event*/evt) {
var type = evt.type;
if (type === 'dragover' || type === 'dragenter') {
if (dragEl) {
this._onDragOver(evt);
_globalDragOver(evt);
}
}
else if (type === 'drop' || type === 'dragend') {
this._onDrop(evt);
}
},
/**
* Serializes the item into an array of string.
* @returns {String[]}
*/
toArray: function () {
var order = [],
el,
children = this.el.children,
i = 0,
n = children.length,
options = this.options;
for (; i < n; i++) {
el = children[i];
if (_closest(el, options.draggable, this.el)) {
order.push(el.getAttribute(options.dataIdAttr) || _generateId(el));
}
}
return order;
},
/**
* Sorts the elements according to the array.
* @param {String[]} order order of the items
*/
sort: function (order) {
var items = {}, rootEl = this.el;
this.toArray().forEach(function (id, i) {
var el = rootEl.children[i];
if (_closest(el, this.options.draggable, rootEl)) {
items[id] = el;
}
}, this);
order.forEach(function (id) {
if (items[id]) {
rootEl.removeChild(items[id]);
rootEl.appendChild(items[id]);
}
});
},
/**
* Save the current sorting
*/
save: function () {
var store = this.options.store;
store && store.set(this);
},
/**
* For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.
* @param {HTMLElement} el
* @param {String} [selector] default: `options.draggable`
* @returns {HTMLElement|null}
*/
closest: function (el, selector) {
return _closest(el, selector || this.options.draggable, this.el);
},
/**
* Set/get option
* @param {string} name
* @param {*} [value]
* @returns {*}
*/
option: function (name, value) {
var options = this.options;
if (value === void 0) {
return options[name];
} else {
options[name] = value;
if (name === 'group') {
_prepareGroup(options);
}
}
},
/**
* Destroy
*/
destroy: function () {
var el = this.el;
el[expando] = null;
_off(el, 'mousedown', this._onTapStart);
_off(el, 'touchstart', this._onTapStart);
if (this.nativeDraggable) {
_off(el, 'dragover', this);
_off(el, 'dragenter', this);
}
// Remove draggable attributes
Array.prototype.forEach.call(el.querySelectorAll('[draggable]'), function (el) {
el.removeAttribute('draggable');
});
touchDragOverListeners.splice(touchDragOverListeners.indexOf(this._onDragOver), 1);
this._onDrop();
this.el = el = null;
}
};
function _cloneHide(state) {
if (cloneEl && (cloneEl.state !== state)) {
_css(cloneEl, 'display', state ? 'none' : '');
!state && cloneEl.state && rootEl.insertBefore(cloneEl, dragEl);
cloneEl.state = state;
}
}
function _closest(/**HTMLElement*/el, /**String*/selector, /**HTMLElement*/ctx) {
if (el) {
ctx = ctx || document;
selector = selector.split('.');
var tag = selector.shift().toUpperCase(),
re = new RegExp('\\s(' + selector.join('|') + ')(?=\\s)', 'g');
do {
if (
(tag === '>*' && el.parentNode === ctx) || (
(tag === '' || el.nodeName.toUpperCase() == tag) &&
(!selector.length || ((' ' + el.className + ' ').match(re) || []).length == selector.length)
)
) {
return el;
}
}
while (el !== ctx && (el = el.parentNode));
}
return null;
}
function _globalDragOver(/**Event*/evt) {
if (evt.dataTransfer) {
evt.dataTransfer.dropEffect = 'move';
}
evt.preventDefault();
}
function _on(el, event, fn) {
el.addEventListener(event, fn, false);
}
function _off(el, event, fn) {
el.removeEventListener(event, fn, false);
}
function _toggleClass(el, name, state) {
if (el) {
if (el.classList) {
el.classList[state ? 'add' : 'remove'](name);
}
else {
var className = (' ' + el.className + ' ').replace(RSPACE, ' ').replace(' ' + name + ' ', ' ');
el.className = (className + (state ? ' ' + name : '')).replace(RSPACE, ' ');
}
}
}
function _css(el, prop, val) {
var style = el && el.style;
if (style) {
if (val === void 0) {
if (document.defaultView && document.defaultView.getComputedStyle) {
val = document.defaultView.getComputedStyle(el, '');
}
else if (el.currentStyle) {
val = el.currentStyle;
}
return prop === void 0 ? val : val[prop];
}
else {
if (!(prop in style)) {
prop = '-webkit-' + prop;
}
style[prop] = val + (typeof val === 'string' ? '' : 'px');
}
}
}
function _find(ctx, tagName, iterator) {
if (ctx) {
var list = ctx.getElementsByTagName(tagName), i = 0, n = list.length;
if (iterator) {
for (; i < n; i++) {
iterator(list[i], i);
}
}
return list;
}
return [];
}
function _dispatchEvent(sortable, rootEl, name, targetEl, fromEl, startIndex, newIndex) {
var evt = document.createEvent('Event'),
options = (sortable || rootEl[expando]).options,
onName = 'on' + name.charAt(0).toUpperCase() + name.substr(1);
evt.initEvent(name, true, true);
evt.to = rootEl;
evt.from = fromEl || rootEl;
evt.item = targetEl || rootEl;
evt.clone = cloneEl;
evt.oldIndex = startIndex;
evt.newIndex = newIndex;
rootEl.dispatchEvent(evt);
if (options[onName]) {
options[onName].call(sortable, evt);
}
}
function _onMove(fromEl, toEl, dragEl, dragRect, targetEl, targetRect) {
var evt,
sortable = fromEl[expando],
onMoveFn = sortable.options.onMove,
retVal;
evt = document.createEvent('Event');
evt.initEvent('move', true, true);
evt.to = toEl;
evt.from = fromEl;
evt.dragged = dragEl;
evt.draggedRect = dragRect;
evt.related = targetEl || toEl;
evt.relatedRect = targetRect || toEl.getBoundingClientRect();
fromEl.dispatchEvent(evt);
if (onMoveFn) {
retVal = onMoveFn.call(sortable, evt);
}
return retVal;
}
function _disableDraggable(el) {
el.draggable = false;
}
function _unsilent() {
_silent = false;
}
/** @returns {HTMLElement|false} */
function _ghostIsLast(el, evt) {
var lastEl = el.lastElementChild,
rect = lastEl.getBoundingClientRect();
return ((evt.clientY - (rect.top + rect.height) > 5) || (evt.clientX - (rect.right + rect.width) > 5)) && lastEl; // min delta
}
/**
* Generate id
* @param {HTMLElement} el
* @returns {String}
* @private
*/
function _generateId(el) {
var str = el.tagName + el.className + el.src + el.href + el.textContent,
i = str.length,
sum = 0;
while (i--) {
sum += str.charCodeAt(i);
}
return sum.toString(36);
}
/**
* Returns the index of an element within its parent
* @param el
* @returns {number}
* @private
*/
function _index(/**HTMLElement*/el) {
if (!el || !el.parentNode) {
return -1;
}
var index = 0;
while (el && (el = el.previousElementSibling)) {
if (el.nodeName.toUpperCase() !== 'TEMPLATE') {
index++;
}
}
return index;
}
function _throttle(callback, ms) {
var args, _this;
return function () {
if (args === void 0) {
args = arguments;
_this = this;
setTimeout(function () {
if (args.length === 1) {
callback.call(_this, args[0]);
} else {
callback.apply(_this, args);
}
args = void 0;
}, ms);
}
};
}
function _extend(dst, src) {
if (dst && src) {
for (var key in src) {
if (src.hasOwnProperty(key)) {
dst[key] = src[key];
}
}
}
return dst;
}
// Export utils
Sortable.utils = {
on: _on,
off: _off,
css: _css,
find: _find,
is: function (el, selector) {
return !!_closest(el, selector, el);
},
extend: _extend,
throttle: _throttle,
closest: _closest,
toggleClass: _toggleClass,
index: _index
};
/**
* Create sortable instance
* @param {HTMLElement} el
* @param {Object} [options]
*/
Sortable.create = function (el, options) {
return new Sortable(el, options);
};
// Export
Sortable.version = '1.3.0-rc1';
return Sortable;
});
|
var yo = require('yo-yo');
module.exports = function landing(box) {
return yo`<div class="container landing">
<div class="row">
<div class="col s10 push-s1">
<div class="row">
<div class="col m5 hide-on-small-only">
<img class="iphone" src="iphone.png" />
</div>
${box}
</div>
</div>
</div>
</div>`
}
|
"use strict";
const get = require("./get");
const add = require("./add");
/**
* @typedef OperationResult
* @type Object
* @property {Any} doc - The patched document
* @property {Array} previous - The previous/replaced value if any
*/
/**
* Copy the value at the specified JSON Pointer location to an other location
* http://tools.ietf.org/html/rfc6902#section-4.5
*
* @param {Object|Array} doc - JSON document to copy the value from and to
* @param {String|Array} path - JSON Pointer string or tokens path
* @param {String} dest - JSON Pointer string destination of the value
* @return {OperationResult}
*/
module.exports = function copy(doc, path, dest) {
const obj = get(doc, path);
return add(doc, dest, obj);
};
|
"use strict";
angular.module('envConfig', [])
.constant('ENV', {name:'development',apiEndPoint:'http://localhost:3000'})
;
|
'use strict';
module.exports = angular.module('plugins.onedrive.service', []).factory('onedriveService', function($http, diNotify) {
var defaults, service;
defaults = {
files: []
};
service = {
fetched: {
fileName: "",
file: null
},
saveFile: function(title, body) {
var di;
di = diNotify({
message: "Saving File to One Drive...",
duration: 5000
});
return $http.post('save/onedrive', {
title: title,
content: body
}).then(function successCallback(data) {
if (di != null) {
di.$scope.$close();
}
if (data.error != null) {
return diNotify({
message: "An Error occured: " + data.error.message,
duration: 3000
});
} else {
if (window.ga) {
ga('send', 'event', 'click', 'Save To One Drive', 'Save To...')
}
return diNotify({
message: "Successfully saved File to One Drive",
duration: 5000
});
}
}, function errorCallback(err) {
return diNotify({
message: "An Error occured: " + err.message
});
});
},
fetchFile: function(fileId, fileName) {
return $http.get("fetch/onedrive?fileId=" + fileId).then(function successCallback(data) {
return service.fetched.file = data.data.content;
}, function errorCallback(err) {
return diNotify({
message: "An Error occured: " + err.message
});
});
},
fetchFiles: function() {
var di;
di = diNotify({
message: "Fetching Markdown related files from One Drive...",
duration: 5000
});
return $http.get('import/onedrive').then(function successCallback(data) {
if (data && data.data.error) {
if (di != null) {
di.$scope.$close();
}
return diNotify({
message: "An Error occured: " + data.data.error.message,
duration: 3000
});
}
if (di != null) {
di.$scope.$close();
}
return service.files = data.data.data || [];
}, function errorCallback(err) {
return diNotify({
message: "An Error occured: " + error.message
});
});
},
save: function() {
localStorage.setItem('onedrive', angular.toJson(service.fetched));
},
restore: function() {
service.fetched = angular.fromJson(localStorage.getItem('onedrive')) || defaults;
return service.fetched;
}
};
service.restore();
return service;
});
|
"use strict";
var exec = require("cordova/exec");
var GcmPushPlugin = {
register: function (successCB, errorCB, options) {
cordova.exec(
successCB,
errorCB,
"GCMPushPlugin",
"register",
[options]
);
},
unregister: function (successCB, errorCB) {
cordova.exec(
successCB,
errorCB,
"GCMPushPlugin",
"unregister",
[]
);
},
setApplicationIconBadgeNumber: function (options) {
cordova.exec(
function(resp){},
function(resp){},
"GCMPushPlugin",
"setApplicationIconBadgeNumber",
[options]
);
},
subscribeToTopic : function(successCB,errorCB, topic){
cordova.exec(
function(resp){},
function(err){},
"GCMPushPlugin",
"subscribeToTopic",
[topic])
},
unsubscribeToTopic :function(successCB,errorCB, topic){
cordova.exec(
function(resp){},
function(err){},
"GCMPushPlugin",
"unsubscribeToTopic",
[topic]
)
}
};
module.exports = GcmPushPlugin;
|
import React from 'react';
import LinearGradient from 'react-native-linear-gradient';
import styled from 'styled-components';
import { colors, fonts } from 'config';
import { InlineLabel } from 'components';
import { FlatList, View } from 'react-native';
type Props = {
title: string,
topics: Array,
};
const styles = {
contentContainerStyle: {
paddingLeft: 13,
paddingRight: 13,
},
scrollGradient: {
position: 'absolute',
width: 15,
height: 30,
},
};
const TopicsListContainer = styled.View`
margin-top: 30;
`;
const TopicsListLabel = styled.Text`
color: ${colors.black};
${{ ...fonts.fontPrimaryBold }};
margin-bottom: 10;
padding-left: 15;
`;
export const TopicsList = ({ title, topics }: Props) => (
<TopicsListContainer>
<TopicsListLabel>{title}</TopicsListLabel>
<View>
{topics.length > 0 && (
<FlatList
contentContainerStyle={styles.contentContainerStyle}
data={topics}
showsHorizontalScrollIndicator={false}
renderItem={({ item }) => (
<InlineLabel
label={{ name: item, color: colors.topicLightBlue.slice(1) }}
/>
)}
keyExtractor={item => item}
horizontal
/>
)}
<LinearGradient
style={[styles.scrollGradient, { left: 0 }]}
colors={['white', 'rgba(255, 255, 255, 0)']}
start={{ x: 0, y: 0.5 }}
end={{ x: 1, y: 0.5 }}
/>
<LinearGradient
style={[styles.scrollGradient, { right: 0 }]}
colors={['rgba(255, 255, 255, 0)', 'white']}
start={{ x: 0, y: 0.5 }}
end={{ x: 1, y: 0.5 }}
/>
</View>
</TopicsListContainer>
);
|
// System Objects
var path = require('path');
var cp = require('child_process');
var stream = require('stream');
var zlib = require('zlib');
var Transform = stream.Transform;
// Third Party Dependencies
var blocks = require('block-stream2');
var bz2 = require('unbzip2-stream');
var createHash = require('sha.js');
var fs = require('fs-extra');
var fsTemp = require('fs-temp');
var osenv = require('osenv');
var Progress = require('t2-progress');
var request = require('request');
var tags = require('common-tags');
var tar = require('tar-fs');
// Internal
var log = require('../log');
var remote = require('../remote');
const SDK_PATHS = {
sdk: path.join(osenv.home(), '.tessel/sdk'),
rustlib: path.join(osenv.home(), '.tessel/rust'),
};
const SDK_URLS = {
macos: `https://${remote.BUILDS_HOSTNAME}/t2/sdk/t2-sdk-macos-x86_64.tar.bz2`,
linux: `https://${remote.BUILDS_HOSTNAME}/t2/sdk/t2-sdk-linux-x86_64.tar.bz2`,
};
// Get the platform identifier. This actually conforms to the list of OSes
// Rust supports, not the value of process.platform, so we need to convert it.
// See: https://doc.rust-lang.org/std/env/consts/constant.OS.html
/* istanbul ignore next */
function getPlatform() {
switch (process.platform) {
case 'darwin':
return 'macos';
case 'linux':
return 'linux';
default:
throw new Error('Your platform is not yet supported for cross-compilation.');
}
}
/* istanbul ignore next */
function sha256stream() {
var sha256 = createHash('sha256');
var stream = new Transform();
stream._transform = function(chunk, encoding, callback) {
this.push(chunk);
sha256.update(chunk);
callback();
};
stream.on('finish', () => {
stream.emit('sha256', sha256.digest('hex'));
});
return stream;
}
/* istanbul ignore next */
function sha256file(hash, name) {
return `${hash} ${name}\n`;
}
/* istanbul ignore next */
function download(url) {
var req = request.get(url);
// When we receive the response
req.on('response', (res) => {
// Parse out the length of the incoming bundle
var contentLength = parseInt(res.headers['content-length'], 10);
// Create a new progress bar
var bar = new Progress(' [:bar] :percent :etas remaining', {
clear: true,
complete: '=',
incomplete: ' ',
width: 20,
total: contentLength
});
// When we get incoming data, update the progress bar
res.on('data', (chunk) => {
bar.tick(chunk.length);
});
});
return req;
}
/* istanbul ignore next */
function downloadString(url) {
return new Promise((resolve, reject) => {
request({
url,
// We want to force Cloudfront to serve us the latest file.
headers: {
'Accept-Encoding': 'gzip, deflate',
},
}, (error, response, body) => {
if (!error && response.statusCode === 200) {
resolve(body);
} else {
reject(error || response.statusCode);
}
});
});
}
// Creates a temp folder with a cleanup function. If anything goes wrong in
// unpacking data into a temp folder or moving it (fs.move may be non-atomic
// across disjoint filesystems) we want to delete the original temp folder,
// which could contain several hundred megabytes of now-useless data.
/* istanbul ignore next */
function tmpdir() {
return new Promise((resolve) => {
var dir = fsTemp.template('t2-sdk-%s').mkdirSync();
resolve({
path: dir,
cleanup: () => {
try {
fs.removeSync(dir);
} catch (e) {
// If the folder no longer exists, or if the remove operation throws
// some error, this is non-fatal to the user (the data will just
// exist until the temp folder is cleaned) and so we swallow any
// errors.
}
}
});
});
}
/* istanbul ignore next */
module.exports.toolchainPath = () => {
return new Promise((resolve, reject) => {
var sdkPlatformPath = path.join(SDK_PATHS.sdk, getPlatform());
var values = fs.readdirSync(sdkPlatformPath);
for (var i = 0; i < values.length; i++) {
if (values[i].startsWith('toolchain-mipsel')) {
return resolve(path.join(sdkPlatformPath, values[i]));
}
}
return reject(new Error('No toolchain found.'));
});
};
// Checks if CHECKSUM file in our SDK equals our expected checksum.
// This will resolve with checking that the SDK exists and matches the checksum.
/* istanbul ignore next */
module.exports.checkTools = (checksumVerify) => {
var dir = path.join(SDK_PATHS.sdk, getPlatform());
return new Promise((resolve) => {
var checksum = fs.readFileSync(path.join(dir, 'CHECKSUM'), 'utf-8');
resolve({
exists: true,
isVerified: checksumVerify === checksum,
path: dir,
});
}).catch(() => ({
exists: false,
isVerified: false,
path: dir,
}));
};
/* istanbul ignore next */
module.exports.checkRustlib = (rustv, checksumVerify) => {
var dir = path.join(SDK_PATHS.rustlib, rustv);
return new Promise((resolve) => {
var checksum = fs.readFileSync(path.join(dir, 'CHECKSUM'), 'utf-8');
resolve({
exists: true,
isVerified: checksumVerify === checksum,
path: dir,
});
}).catch(() => ({
exists: false,
isVerified: false,
path: dir,
}));
};
/* istanbul ignore next */
module.exports.installTools = () => {
var pkgname = 'Tessel build tools';
var url = SDK_URLS[getPlatform()];
var checksumVerify = null;
return remote.ifReachable(remote.BUILDS_HOSTNAME).then(() => {
return downloadString(`${url}.sha256`)
.then((checksum) => {
checksumVerify = checksum;
return exports.checkTools(checksumVerify);
})
.then((check) => {
if (check.exists && check.isVerified) {
log.info(`Latest ${pkgname} already installed.`);
return;
} else if (!check.exists) {
log.info(`Installing ${pkgname}...`);
} else {
log.info(`Updating ${pkgname}...`);
}
fs.mkdirpSync(path.join(osenv.home(), '.tessel/sdk'));
return extractTools(checksumVerify, path.basename(url), download(url));
});
});
};
/* istanbul ignore next */
module.exports.installRustlib = () => {
return exports.rustVersion()
.then((rustv) => {
var pkgname = `MIPS libstd v${rustv}`;
var url = `https://${remote.BUILDS_HOSTNAME}/t2/sdk/t2-rustlib-${rustv}.tar.gz`;
var checksumVerify;
return downloadString(url + '.sha256')
.catch(() => Promise.reject(`Could not find a MIPS libstd matching your current Rust version (${rustv}).`))
.then(checksum => {
checksumVerify = checksum;
return exports.checkRustlib(rustv, checksumVerify);
})
.then(check => {
if (check.exists && check.isVerified) {
log.info(`Latest ${pkgname} already installed.`);
return;
} else if (!check.exists) {
log.info(`Installing ${pkgname}...`);
} else {
log.info(`Updating ${pkgname}...`);
}
fs.mkdirpSync(SDK_PATHS.rustlib);
return extractRustlib(checksumVerify, path.basename(url), download(url), rustv);
});
});
};
/* istanbul ignore next */
function extract(checksumVerify, filename, sdkStream, root, strip, name, decompress) {
return tmpdir()
.then(destdir => {
// Exract tarball to destination.
var extract = tar.extract(destdir.path, {
strip: strip,
ignore: function(name) {
// Ignore self-directory.
return path.normalize(name + '/') === path.normalize(destdir.path + '/');
}
});
return new Promise((resolve, reject) => {
var checksum = '';
sdkStream
.pipe(sha256stream())
.on('sha256', function(sha256) {
checksum = sha256file(sha256, filename);
})
.pipe(decompress)
// tar-stream has a recursion issue when input chunks are too big.
// by splitting up the chunks, we never get too deeply nested in the
// stack.
.pipe(blocks({
size: 64 * 1024,
zeroPadding: false
}))
.pipe(extract)
.on('finish', () => {
// Check sum.
if (checksum !== checksumVerify) {
return reject(tags.stripIndent `
Please file an issue on https://github.com/tessel/t2-cli with the following:
The downloaded file ${name} is invalid (wrong checksum).
expected: ${checksumVerify}
got: ${checksum}`);
}
// Write out CHECKSUM file.
fs.writeFileSync(path.join(destdir.path, 'CHECKSUM'), checksum);
try {
// Remove the old SDK directory.
fs.removeSync(root);
// Move temporary directory to target destination.
fs.move(destdir.path, root, error => {
if (error) {
// Cleanup temp dir.
destdir.cleanup();
reject(error);
} else {
resolve();
}
});
} catch (error) {
// Cleanup temp dir.
destdir.cleanup();
reject(error);
}
})
.on('error', error => {
destdir.cleanup();
reject(error);
});
});
});
}
/* istanbul ignore next */
function extractTools(checksumVerify, filename, sdkStream) {
var root = path.join(SDK_PATHS.sdk, getPlatform());
return extract(checksumVerify, filename, sdkStream, root, 2, 'Tessel build tools', bz2());
}
/* istanbul ignore next */
function extractRustlib(checksumVerify, filename, sdkStream, rustVersion) {
var root = path.join(SDK_PATHS.rustlib, rustVersion);
return extract(checksumVerify, filename, sdkStream, root, 0, 'MIPS libstd', zlib.createGunzip());
}
/* istanbul ignore next */
module.exports.getBuildConfig = () => {
var config = {
rustv: null,
toolchainPath: null,
stagingDir: null,
rustlibPath: null,
name: null,
path: null,
};
return exports.rustVersion()
.then(rustv => {
config.rustv = rustv;
return exports.checkTools();
})
.then(check => {
if (!check.exists) {
throw new Error('Tessel cross-compilation tools are not installed.');
}
config.stagingDir = check.path;
return exports.checkRustlib(config.rustv);
})
.then(check => {
if (!check.exists) {
throw new Error(`MIPS libstd v${config.rustv} not installed.`);
}
config.rustlibPath = check.path;
return exports.toolchainPath();
})
.then(toolchainPath => {
config.toolchainPath = toolchainPath;
return config;
});
};
// Confirms that the user has a version of rustc and cargo installed. Resolves
// with the current rustc version, rejects if either executable is not found
// on the system.
/* istanbul ignore next */
module.exports.rustVersion = () => {
// Check that rustc exists and get its version.
return new Promise((resolve, reject) => {
var rustc = cp.spawn('rustc', ['-V']);
var rustcOut = [];
rustc.stdout.on('data', (data) => {
rustcOut.push(data);
});
rustc.on('error', reject);
rustc.on('close', (status) => {
var out = Buffer.concat(rustcOut).toString();
var matches = out.match(/^rustc\s+(\S+)/);
if (status !== 0 || !matches) {
return reject(new Error('Could not find a locally installed version of "rustc".'));
}
var version = matches[1];
// Check if cargo exists also.
var cargo = cp.spawn('cargo', ['-V']);
cargo.on('error', reject);
cargo.on('close', (status) => {
if (status !== 0) {
return reject(new Error('Could not find a locally installed version of "cargo".'));
}
resolve(version);
});
});
});
};
// Check the targets of a cargo crate.
/* istanbul ignore next */
module.exports.cargoMetadata = (destdir) => {
return new Promise((resolve, reject) => {
var cargo = cp.spawn('cargo', ['metadata', '--no-deps'], {
stdio: ['ignore', 'pipe', 'inherit'],
cwd: destdir || process.cwd(),
});
var stdout = [];
cargo.stdout.on('data', (data) => {
stdout.push(data);
});
cargo.on('error', reject);
cargo.on('close', (status) => {
if (status !== 0) {
reject(`Could not find a cargo project in ${destdir || 'this directory.'}.`);
} else {
resolve(JSON.parse(Buffer.concat(stdout).toString()));
}
});
});
};
/* istanbul ignore next */
module.exports.buildTessel = (config) => {
var env = Object.assign({}, process.env, {
STAGING_DIR: config.stagingDir,
RUST_TARGET_PATH: config.rustlibPath,
PATH: `${path.join(config.toolchainPath, 'bin')}:${process.env.PATH}`,
RUSTFLAGS: `-L ${config.rustlibPath}`,
});
return new Promise((resolve, reject) => {
var cargo = cp.spawn('cargo', ['build', '--target=tessel2', '--bin', config.name, '--release'], {
env: env,
pwd: config.path || process.cwd(),
stdio: ['ignore', 'inherit', 'inherit'],
});
cargo.on('error', (error) => {
reject(error);
});
cargo.on('close', (code) => {
if (code !== 0) {
reject(`"cargo build" exited with status code ${code}`);
} else {
resolve();
}
});
});
};
/* istanbul ignore next */
module.exports.bundleTessel = (config) => {
return new Promise((resolve) => {
var tarball = path.join(path.dirname(config.path), 'tessel-bundle.tar');
tar.pack(path.dirname(config.path), {
entries: [path.basename(config.path)]
})
.pipe(fs.createWriteStream(tarball))
.on('finish', function() {
resolve(tarball);
});
});
};
/* istanbul ignore next */
module.exports.cargo = {
install: () => {
exports.checkRust({
isCli: false
});
return exports.installTools()
.then(() => {
return exports.installRustlib()
.then(() => {
log.info('SDK installed.');
}, e => {
log.error(e.message);
log.error('Please switch to using a stable Rust version >= 1.11.0 and try again.');
log.warn('SDK toolchain is installed, but a libstd for your Rust version is not.');
});
});
},
uninstall: () => {
return new Promise((resolve) => {
fs.remove(path.join(osenv.home(), '.tessel/rust'), () => {
fs.remove(path.join(osenv.home(), '.tessel/sdk'), () => {
log.info('Tessel SDK uninstalled.');
resolve();
});
});
});
},
};
// Logging function that checks if all rust components are installed.
/* istanbul ignore next */
module.exports.checkSdk = () => {
return exports.getBuildConfig()
.catch(error => Promise.reject(tags.stripIndent `
Could not find all the components for cross-compiling Rust:
${error.message}
Please run "cargo tessel sdk install" and try again.
To instead use the remote Rust compiler, use "t2 run <target> --rustcc".`));
};
/* istanbul ignore next */
module.exports.checkRust = (opts) => {
return exports.rustVersion()
.catch(() => Promise.reject(tags.stripIndent `
"rustc" and "cargo" are required to cross-compile for Tessel.
Please install Rust on your machine: https://rustup.rs/
${opts.isCli ? 'To instead use the remote Rust compiler, use "t2 run <target> --rustcc".' : ''}`));
};
// Logging function that checks if rust is installed, then if the binary matches.
// opts matches { isCli: boolean, binary: String[, path: String] }
/* istanbul ignore next */
module.exports.checkBinaryName = (opts) => {
return exports.cargoMetadata(opts.path)
.then(metadata => {
return new Promise((resolve, reject) => {
// Get first package.
var pkg = metadata.packages.pop();
var bins = pkg.targets.filter(target => target.kind.indexOf('bin') > -1);
// Filter by --bin argument.
var validBins = bins.filter(bin => bin.name === opts.binary);
// Throw if multiple bins exist.
if (validBins.length === 0) {
var message;
if (!opts.binary) {
message = 'Please specify a valid binary target with --bin.';
} else {
message = tags.stripIndent `
No binary target "${opts.binary}" exists for this Rust crate.
Make sure you specify a valid binary using --bin.`;
}
if (bins.length > 0) {
message += '\nAvailable targets:';
bins.forEach(bin => {
if (opts.isCli) {
message += `\n t2 run ${bin.name}`;
} else {
message += `\n cargo tessel build --bin ${bin.name}`;
}
});
}
return reject(message);
}
var name = validBins[0].name;
var dest = path.join(path.dirname(pkg.manifest_path), 'target/tessel2/release', name);
resolve({
name,
path: dest,
});
});
});
};
// opts matches { isCli: boolean, binary: String[, path: String] }
/* istanbul ignore next */
module.exports.runBuild = (opts) => {
return exports.checkRust({
isCli: opts.isCli
})
.then(() => exports.checkBinaryName(opts))
.then(out => {
return module.exports.checkSdk()
.then(config => {
config.name = out.name;
config.path = out.path;
return exports.buildTessel(config)
.then(() => exports.bundleTessel(config));
});
});
};
|
//>>built
define({singleSort:"Jednokratno sortiranje",nestedSort:"Ugne\u017e\u0111eno sortiranje",ascending:"Kliknite da biste sortirali po rastu\u0107em redosledu",descending:"Kliknite da biste sortirali po opadaju\u0107em redosledu",sortingState:"${0} - ${1}",unsorted:"Ne sortiraj ovu kolonu",indirectSelectionRadio:"Red ${0}, jedinstven izbor, radio okvir",indirectSelectionCheckBox:"Red ${0}, vi\u0161estruki izbor, polje za potvrdu",selectAll:"Izaberi sve"});
|
import angular from 'angular';
class Controller {
isSelected(index) {
return this.wizardCtrl.currentStep === index + 1;
}
}
const component = {
bindings: {},
transclude: true,
require: {
wizardCtrl: '^imhereWizard',
},
controller: Controller,
controllerAs: 'vm',
template: require('./imhere-steps-dotted.html'),
};
export default angular
.module('imhere-angular-wizard.imhere-steps-dotted', [])
.component('imhereStepsDotted', component);
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
var __extends = (this && this.__extends) || (function () {
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 (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
import './decorations.css';
import { DynamicViewOverlay } from '../../view/dynamicViewOverlay.js';
import { Range } from '../../../common/core/range.js';
import { HorizontalRange } from '../../../common/view/renderingContext.js';
var DecorationsOverlay = /** @class */ (function (_super) {
__extends(DecorationsOverlay, _super);
function DecorationsOverlay(context) {
var _this = _super.call(this) || this;
_this._context = context;
_this._lineHeight = _this._context.configuration.editor.lineHeight;
_this._typicalHalfwidthCharacterWidth = _this._context.configuration.editor.fontInfo.typicalHalfwidthCharacterWidth;
_this._renderResult = null;
_this._context.addEventHandler(_this);
return _this;
}
DecorationsOverlay.prototype.dispose = function () {
this._context.removeEventHandler(this);
this._renderResult = null;
_super.prototype.dispose.call(this);
};
// --- begin event handlers
DecorationsOverlay.prototype.onConfigurationChanged = function (e) {
if (e.lineHeight) {
this._lineHeight = this._context.configuration.editor.lineHeight;
}
if (e.fontInfo) {
this._typicalHalfwidthCharacterWidth = this._context.configuration.editor.fontInfo.typicalHalfwidthCharacterWidth;
}
return true;
};
DecorationsOverlay.prototype.onDecorationsChanged = function (e) {
return true;
};
DecorationsOverlay.prototype.onFlushed = function (e) {
return true;
};
DecorationsOverlay.prototype.onLinesChanged = function (e) {
return true;
};
DecorationsOverlay.prototype.onLinesDeleted = function (e) {
return true;
};
DecorationsOverlay.prototype.onLinesInserted = function (e) {
return true;
};
DecorationsOverlay.prototype.onScrollChanged = function (e) {
return e.scrollTopChanged || e.scrollWidthChanged;
};
DecorationsOverlay.prototype.onZonesChanged = function (e) {
return true;
};
// --- end event handlers
DecorationsOverlay.prototype.prepareRender = function (ctx) {
var _decorations = ctx.getDecorationsInViewport();
// Keep only decorations with `className`
var decorations = [], decorationsLen = 0;
for (var i = 0, len = _decorations.length; i < len; i++) {
var d = _decorations[i];
if (d.options.className) {
decorations[decorationsLen++] = d;
}
}
// Sort decorations for consistent render output
decorations = decorations.sort(function (a, b) {
if (a.options.zIndex < b.options.zIndex) {
return -1;
}
if (a.options.zIndex > b.options.zIndex) {
return 1;
}
var aClassName = a.options.className;
var bClassName = b.options.className;
if (aClassName < bClassName) {
return -1;
}
if (aClassName > bClassName) {
return 1;
}
return Range.compareRangesUsingStarts(a.range, b.range);
});
var visibleStartLineNumber = ctx.visibleRange.startLineNumber;
var visibleEndLineNumber = ctx.visibleRange.endLineNumber;
var output = [];
for (var lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
var lineIndex = lineNumber - visibleStartLineNumber;
output[lineIndex] = '';
}
// Render first whole line decorations and then regular decorations
this._renderWholeLineDecorations(ctx, decorations, output);
this._renderNormalDecorations(ctx, decorations, output);
this._renderResult = output;
};
DecorationsOverlay.prototype._renderWholeLineDecorations = function (ctx, decorations, output) {
var lineHeight = String(this._lineHeight);
var visibleStartLineNumber = ctx.visibleRange.startLineNumber;
var visibleEndLineNumber = ctx.visibleRange.endLineNumber;
for (var i = 0, lenI = decorations.length; i < lenI; i++) {
var d = decorations[i];
if (!d.options.isWholeLine) {
continue;
}
var decorationOutput = ('<div class="cdr '
+ d.options.className
+ '" style="left:0;width:100%;height:'
+ lineHeight
+ 'px;"></div>');
var startLineNumber = Math.max(d.range.startLineNumber, visibleStartLineNumber);
var endLineNumber = Math.min(d.range.endLineNumber, visibleEndLineNumber);
for (var j = startLineNumber; j <= endLineNumber; j++) {
var lineIndex = j - visibleStartLineNumber;
output[lineIndex] += decorationOutput;
}
}
};
DecorationsOverlay.prototype._renderNormalDecorations = function (ctx, decorations, output) {
var lineHeight = String(this._lineHeight);
var visibleStartLineNumber = ctx.visibleRange.startLineNumber;
var prevClassName = null;
var prevShowIfCollapsed = false;
var prevRange = null;
for (var i = 0, lenI = decorations.length; i < lenI; i++) {
var d = decorations[i];
if (d.options.isWholeLine) {
continue;
}
var className = d.options.className;
var showIfCollapsed = Boolean(d.options.showIfCollapsed);
var range = d.range;
if (showIfCollapsed && range.endColumn === 1 && range.endLineNumber !== range.startLineNumber) {
range = new Range(range.startLineNumber, range.startColumn, range.endLineNumber - 1, this._context.model.getLineMaxColumn(range.endLineNumber - 1));
}
if (prevClassName === className && prevShowIfCollapsed === showIfCollapsed && Range.areIntersectingOrTouching(prevRange, range)) {
// merge into previous decoration
prevRange = Range.plusRange(prevRange, range);
continue;
}
// flush previous decoration
if (prevClassName !== null) {
this._renderNormalDecoration(ctx, prevRange, prevClassName, prevShowIfCollapsed, lineHeight, visibleStartLineNumber, output);
}
prevClassName = className;
prevShowIfCollapsed = showIfCollapsed;
prevRange = range;
}
if (prevClassName !== null) {
this._renderNormalDecoration(ctx, prevRange, prevClassName, prevShowIfCollapsed, lineHeight, visibleStartLineNumber, output);
}
};
DecorationsOverlay.prototype._renderNormalDecoration = function (ctx, range, className, showIfCollapsed, lineHeight, visibleStartLineNumber, output) {
var linesVisibleRanges = ctx.linesVisibleRangesForRange(range, /*TODO@Alex*/ className === 'findMatch');
if (!linesVisibleRanges) {
return;
}
for (var j = 0, lenJ = linesVisibleRanges.length; j < lenJ; j++) {
var lineVisibleRanges = linesVisibleRanges[j];
var lineIndex = lineVisibleRanges.lineNumber - visibleStartLineNumber;
if (showIfCollapsed && lineVisibleRanges.ranges.length === 1) {
var singleVisibleRange = lineVisibleRanges.ranges[0];
if (singleVisibleRange.width === 0) {
// collapsed range case => make the decoration visible by faking its width
lineVisibleRanges.ranges[0] = new HorizontalRange(singleVisibleRange.left, this._typicalHalfwidthCharacterWidth);
}
}
for (var k = 0, lenK = lineVisibleRanges.ranges.length; k < lenK; k++) {
var visibleRange = lineVisibleRanges.ranges[k];
var decorationOutput = ('<div class="cdr '
+ className
+ '" style="left:'
+ String(visibleRange.left)
+ 'px;width:'
+ String(visibleRange.width)
+ 'px;height:'
+ lineHeight
+ 'px;"></div>');
output[lineIndex] += decorationOutput;
}
}
};
DecorationsOverlay.prototype.render = function (startLineNumber, lineNumber) {
if (!this._renderResult) {
return '';
}
var lineIndex = lineNumber - startLineNumber;
if (lineIndex < 0 || lineIndex >= this._renderResult.length) {
return '';
}
return this._renderResult[lineIndex];
};
return DecorationsOverlay;
}(DynamicViewOverlay));
export { DecorationsOverlay };
|
"use strict";
_kangoLoader.add("kango/core", function(require, exports, module) {
var utils=require("kango/utils"),object=utils.object,array=utils.array,func=utils.func,EventTarget=utils.EventTarget,extensionInfo=require("kango/extension_info");function Core(){EventTarget.call(this);this._asyncModules=[];this._apiFactories={};this._moduleInitializedListener=func.bind(function(a){array.remove(this._asyncModules,a.data)},this);this.addEventListener("moduleinitialized",this._moduleInitializedListener)}
Core.prototype=object.extend(EventTarget,{init:function(){object.forEach(extensionInfo.modules,function(a){require(a)});var a=!1;this.addEventListener("moduleinitialized",func.bind(function(b){array.remove(this._asyncModules,b.data);a&&0==this._asyncModules.length&&this._fireReady()},this));this.removeEventListener("moduleinitialized",this._moduleInitializedListener);a=!0;0==this._asyncModules.length&&this._fireReady()},_fireReady:function(){this.fireEvent("ready")},dispose:function(){this.removeAllEventListeners()},
registerApiFactory:function(a,b){this._apiFactories[a]=b},createApiInstance:function(a){var b={},d={};object.forEach(this._apiFactories,function(f,e){var c=f(a);c&&(d[e]=c,b[e]=c.obj)});return{obj:b,clear:function(){object.forEach(d,function(a){a.clear()})}}},addAsyncModule:function(a){this._asyncModules.push(a)}});module.exports=new Core;
});
|
import { Meteor } from 'meteor/meteor';
import { openRoom } from '../../../ui-utils';
import { ChatRoom, ChatSubscription } from '../../../models';
import { settings } from '../../../settings';
import { hasAtLeastOnePermission } from '../../../authorization';
import { getUserPreference, RoomTypeConfig, RoomTypeRouteConfig, RoomSettingsEnum, UiTextContext } from '../../../utils';
import { getAvatarURL } from '../../../utils/lib/getAvatarURL';
export class PublicRoomRoute extends RoomTypeRouteConfig {
constructor() {
super({
name: 'channel',
path: '/channel/:name',
});
}
action(params) {
return openRoom('c', params.name);
}
}
export class PublicRoomType extends RoomTypeConfig {
constructor() {
super({
identifier: 'c',
order: 30,
icon: 'hashtag',
label: 'Channels',
route: new PublicRoomRoute(),
});
}
getIcon(roomData) {
if (roomData.prid) {
return 'discussion';
}
return this.icon;
}
findRoom(identifier) {
const query = {
t: 'c',
name: identifier,
};
return ChatRoom.findOne(query);
}
roomName(roomData) {
if (roomData.prid) {
return roomData.fname;
}
if (settings.get('UI_Allow_room_names_with_special_chars')) {
return roomData.fname || roomData.name;
}
return roomData.name;
}
condition() {
const groupByType = getUserPreference(Meteor.userId(), 'sidebarGroupByType');
return groupByType && (hasAtLeastOnePermission(['view-c-room', 'view-joined-room']) || settings.get('Accounts_AllowAnonymousRead') === true);
}
showJoinLink(roomId) {
return !!ChatRoom.findOne({ _id: roomId, t: 'c' });
}
includeInRoomSearch() {
return true;
}
isGroupChat() {
return true;
}
canAddUser(room) {
return hasAtLeastOnePermission(['add-user-to-any-c-room', 'add-user-to-joined-room'], room._id);
}
canSendMessage(roomId) {
const room = ChatRoom.findOne({ _id: roomId, t: 'c' }, { fields: { prid: 1 } });
if (room.prid) {
return true;
}
// TODO: remove duplicated code
return ChatSubscription.find({
rid: roomId,
}).count() > 0;
}
enableMembersListProfile() {
return true;
}
allowRoomSettingChange(room, setting) {
switch (setting) {
case RoomSettingsEnum.BROADCAST:
return room.broadcast;
case RoomSettingsEnum.READ_ONLY:
return !room.broadcast;
case RoomSettingsEnum.REACT_WHEN_READ_ONLY:
return !room.broadcast && room.ro;
case RoomSettingsEnum.E2E:
return false;
case RoomSettingsEnum.SYSTEM_MESSAGES:
default:
return true;
}
}
getUiText(context) {
switch (context) {
case UiTextContext.HIDE_WARNING:
return 'Hide_Room_Warning';
case UiTextContext.LEAVE_WARNING:
return 'Leave_Room_Warning';
default:
return '';
}
}
getAvatarPath(roomData) {
// TODO: change to always get avatar from _id when rooms have avatars
return getAvatarURL({ username: `@${ this.roomName(roomData) }` });
}
}
|
import React, { Component } from 'react';
import './ImportEpwing.css';
import SecondaryScreen from './SecondaryScreen.js';
import SystemBrowserLink from './SystemBrowserLink.js';
import Button from './Button.js';
import { importEpwing } from '../dictionary';
const { ipcRenderer } = window.require('electron'); // use window to avoid webpack
export default class ImportEpwing extends Component {
constructor(props) {
super(props);
this.state = {
epwingDirectory: undefined,
importing: false,
statusType: 'working',
statusText: '',
};
ipcRenderer.on('chose-directory', this.handleIpcChoseDirectory);
}
componentWillUnmount() {
ipcRenderer.removeListener('chose-directory', this.handleIpcChoseDirectory);
}
handleIpcChoseDirectory = (e, dir) => {
this.setState({epwingDirectory: dir});
};
handleClickChooseDirectory = (e) => {
e.preventDefault();
ipcRenderer.send('choose-directory', 'Choose EPWING folder');
};
handleImport = async () => {
this.setState({
importing: true,
statusType: 'working',
statusText: 'Importing ' + this.state.epwingDirectory + '... (may take a while)',
});
try {
await importEpwing(this.state.epwingDirectory);
await this.props.onReloadDictionaries(progressMsg => {
this.setState({
statusText: 'Reloading dictionaries: ' + progressMsg,
});
});
this.setState({
importing: false,
statusType: 'success',
statusText: 'EPWING imported successfully',
epwingDirectory: undefined,
});
} catch (e) {
console.log(e.message);
let statusText = 'Something went wrong';
if (e.message.includes('unrecognized dictionary format')) {
statusText = 'The folder you selected does not appear to be an EPWING dictionary';
} else if (e.message.includes('failed to find compatible extractor')) {
statusText = 'The EPWING you selected is not supported (see instructions above)';
}
this.setState({
importing: false,
statusType: 'error',
statusText: statusText,
});
}
};
render() {
const { onExit } = this.props;
return (
<SecondaryScreen title="Import EPWING Dictionary">
<div>If your EPWING dictionary is archived (e.g. a ZIP or RAR file), first unarchive it. Then choose its root folder, the one that contains the CATALOGS file. Note that Voracious relies on Yomichan Importer to import EPWINGS, and only certain specific dictionaries are supported (<SystemBrowserLink href="https://foosoft.net/projects/yomichan-import/">see the list here</SystemBrowserLink>).</div>
<br />
<div>Folder: {this.state.epwingDirectory || <span><i>None selected</i></span>} <button disabled={this.state.importing} onClick={this.handleClickChooseDirectory}>Choose Folder</button></div>
<br />
<div className={'ImportEpwing-status ImportEpwing-status-' + this.state.statusType}>{this.state.statusText} </div>
<br />
<div>
<Button disabled={!this.state.epwingDirectory || this.state.importing} onClick={this.handleImport}>Import Selected Folder</Button>
<Button disabled={this.state.importing} onClick={onExit}>Back</Button>
</div>
</SecondaryScreen>
);
}
}
|
import * as React from 'react';
import { expect } from 'chai';
function assertDOMNode(node) {
// duck typing a DOM node
expect(typeof node.nodeName).to.equal('string');
}
/**
* Utility method to make assertions about the ref on an element
* @param {React.ReactElement} element - The element should have a component wrapped
* in withStyles as the root
* @param {function} mount - Should be returnvalue of createMount
* @param {function} onRef - Callback, first arg is the ref.
* Assert that the ref is a DOM node by default
*/
export default function testRef(element, mount, onRef = assertDOMNode) {
const ref = React.createRef();
const wrapper = mount( /*#__PURE__*/React.createElement(React.Fragment, null, React.cloneElement(element, {
ref
})));
onRef(ref.current, wrapper);
}
|
var TurnServiceTests = (function () {
function TurnServiceTests(turnService) {
describe('TurnService', function () {
var game;
var turnResult;
beforeEach(function () {
game = new Game();
turnResult = TurnResult.NotSet;
});
function validMove(scenarioName, gameSetup, attempt) {
describe(scenarioName, function () {
var turnNumberAtStart;
var whosTurnIsItAtStart;
beforeEach(function () {
gameSetup(game);
turnNumberAtStart = game.currentTurn;
whosTurnIsItAtStart = game.whosTurnIsIt;
turnResult = turnService.tryTakeTurn(game, attempt);
});
it('is a valid move', function () {
expect(turnResult).toBe(TurnResult.Valid);
});
it('increases the turn', function () {
expect(game.currentTurn).toBe(turnNumberAtStart + 1);
});
it('adds the marker to the board at the correct square', function () {
expect(game.board[attempt.x][attempt.y]).toBe(whosTurnIsItAtStart);
});
it('changes the turn', function () {
expect(game.whosTurnIsIt).not.toBe(whosTurnIsItAtStart);
expect(game.whosTurnIsIt).not.toBe(Marker.Empty);
});
});
}
function invalidMove(scenarioName, gameSetup, attempt) {
describe(scenarioName, function () {
var turnNumberAtStart;
var whosTurnIsItAtStart;
beforeEach(function () {
gameSetup(game);
turnNumberAtStart = game.currentTurn;
whosTurnIsItAtStart = game.whosTurnIsIt;
turnResult = turnService.tryTakeTurn(game, attempt);
});
it('does not change the turn', function () {
expect(game.currentTurn).toBe(turnNumberAtStart);
});
it('is not a valid move', function () {
expect(turnResult).toBe(TurnResult.Invalid);
});
it('done not change whom\'s turn it is', function () {
expect(game.whosTurnIsIt).toBe(whosTurnIsItAtStart);
});
});
}
validMove('first move', function (g) {
}, new TurnAttempt(0, 0));
validMove('second turn picking empty space', function (g) {
g.board[0][0] = Marker.X;
g.currentTurn = 2;
g.whoGoesFirst = Marker.X;
g.whosTurnIsIt = Marker.O;
}, new TurnAttempt(0, 1));
validMove('winning move', function (g) {
g.board[0][0] = Marker.X;
g.board[0][1] = Marker.O;
g.board[1][1] = Marker.X;
g.board[0][2] = Marker.O;
g.whoGoesFirst = Marker.X;
g.currentTurn = 5;
g.whosTurnIsIt = Marker.X;
}, new TurnAttempt(2, 2));
invalidMove('second turn space taken', function (g) {
g.board[2][2] = Marker.X;
g.whoGoesFirst = Marker.X;
g.currentTurn = 2;
g.whosTurnIsIt = Marker.O;
}, new TurnAttempt(2, 2));
invalidMove('thrid turn space taken', function (g) {
g.board[2][2] = Marker.X;
g.board[0][0] = Marker.O;
g.whoGoesFirst = Marker.X;
g.currentTurn = 3;
g.whosTurnIsIt = Marker.X;
}, new TurnAttempt(0, 0));
});
}
return TurnServiceTests;
})();
//# sourceMappingURL=TurnServiceTests.js.map
|
"use strict";
/**
* Module dependencies
*/
var _ = require('lodash'),
utils = require('./utils'),
hop = utils.object.hop,
RID = require('orientjs').RID;
/**
* Query Constructor
*
* Normalizes Waterline queries to work with Oriento.
*
* @param {Object} options
* @api private
*/
var Query = module.exports = function Query(options, connection) {
// Sequel builder
this.sequel = connection.sequel;
// decode
this.decodeURIComponent = connection.config.options.decodeURIComponent;
// Normalize Criteria
this.criteria = this.normalizeCriteria(options);
return this;
};
/**
* Normalize Criteria
*
* Transforms a Waterline Query into a query that can be used
* with Oriento. For example it sets '>' to $gt, etc.
*
* @param {Object} options
* @return {Object}
* @api private
*/
Query.prototype.normalizeCriteria = function normalizeCriteria(options) {
var self = this;
return _.mapValues(options, function (original, key) {
if (key === 'where') return self.parseWhere(original);
return original;
});
};
/**
* Parse Where
*
* <where> ::= <clause>
*
* @api private
*
* @param original
* @returns {*}
*/
Query.prototype.parseWhere = function parseWhere(original) {
var self = this;
// Fix an issue with broken queries when where is null
//if(_.isNull(original)) return {};
if(_.isNull(original)) return null;
return self.parseClause(original);
};
/**
* Parse Clause
*
* <clause> ::= { <clause-pair>, ... }
*
* <clause-pair> ::= <field> : <expression>
* | or|$or: [<clause>, ...]
* | $or : [<clause>, ...]
* | $and : [<clause>, ...]
* | $nor : [<clause>, ...]
* | like : { <field>: <expression>, ... }
*
* @api private
*
* @param original
* @returns {*}
*/
Query.prototype.parseClause = function parseClause(original) {
var self = this;
return self.fixId(original);
};
/**
* Convert IDs into RIDs
*
* <clause> ::= { <clause-pair>, ... }
*
* <clause-pair> ::= <field> : <expression>
* | or|$or: [<clause>, ...]
* | $or : [<clause>, ...]
* | $and : [<clause>, ...]
* | $nor : [<clause>, ...]
* | like : { <field>: <expression>, ... }
*
* @api private
*
* @param original
* @returns {*}
*/
Query.prototype.fixId = function fixId(original) {
var self = this;
return _.reduce(original, function parseClausePair(obj, val, key) {
// handle Logical Operators
if (['or', 'and', 'nor'].indexOf(key) !== -1) {
// Value of or, and, nor require an array, else ignore
if (_.isArray(val)) {
val = _.map(val, function (clause) {
return self.parseClause(clause);
});
obj[key] = val;
}
}
// Default
else {
// Normalize `id` key into orientdb `@rid`
if (key === 'id' && !hop(this, '@rid')) {
key = '@rid';
obj[key] = self.decode(val);
} else if(key === '@rid') {
obj[key] = self.decode(val);
} else {
obj[key] = val;
}
}
return obj;
}, {}, original);
};
/**
* Decodes ID from encoded URI component
*
* @api private
*
* @param {Array|Object|String} idValue
* @returns {Array|String}
*/
Query.prototype.decode = function decode(idValue) {
var self = this;
if(! idValue || !self.decodeURIComponent) { return idValue; }
function decodeURI(id){
var res = id;
if(id.indexOf('%23') === 0){
res = res.replace('%23', '#');
res = res.replace('%3A', ':');
}
return res;
}
if(_.isString(idValue)){
return decodeURI(idValue);
}
if(_.isArray(idValue)){
return _.map(idValue, decodeURI);
}
if(_.isPlainObject(idValue)){
return _.reduce(idValue, function(result, val, key) {
result[key] = _.isString(val) ? decodeURI(val) :
_.isArray(val) ? _.map(val, decodeURI) :
val;
return result;
}, {});
}
return idValue;
};
/**
* Get Select Query
*
* @api public
* @param {String} collection
* @returns {Object}
*/
Query.prototype.getSelectQuery = function getSelectQuery(collection, attributes) {
var self = this;
var _query = self.sequel.find(collection, self.criteria);
_query.query[0] = _query.query[0].replace(collection.toUpperCase(), collection);
_query.params = _.reduce(_query.values[0], function(accumulator, value, index){
var key = _query.keys[0][index];
var attribute = utils.getAttributeAsObject(attributes, key) || {};
var foreignKeyOrId = key === '@rid' || key && key.indexOf('.@rid') !== -1 ||
attribute.foreignKey || attribute.model || false;
var paramValue = foreignKeyOrId && _.isString(value) && utils.matchRecordId(value) ? new RID(value) : value;
accumulator['param' + index] = paramValue;
return accumulator;
}, {});
return _query;
};
/**
* Get Where Query
*
* @api public
* @param {String} collection
* @returns {Object}
*/
Query.prototype.getWhereQuery = function getWhereQuery(collection) {
var self = this;
var _where = self.getSelectQuery(collection);
_where.query[0] = _where.query[0].split('WHERE')[1];
_where.query[0] = _where.query[0] && _where.query[0].trim() !== '' ? _where.query[0] : null;
return _where;
};
|
app.controller('UserController', ['$scope', function($scope) {
console.log('This is user controller');
}]);
|
/**
* TinyMCE version 6.0.0 (2020-03-03)
*/
(function () {
'use strict';
var global$3 = tinymce.util.Tools.resolve('tinymce.PluginManager');
const hasProto = (v, constructor, predicate) => {
var _a;
if (predicate(v, constructor.prototype)) {
return true;
} else {
return ((_a = v.constructor) === null || _a === void 0 ? void 0 : _a.name) === constructor.name;
}
};
const typeOf = x => {
const t = typeof x;
if (x === null) {
return 'null';
} else if (t === 'object' && Array.isArray(x)) {
return 'array';
} else if (t === 'object' && hasProto(x, String, (o, proto) => proto.isPrototypeOf(o))) {
return 'string';
} else {
return t;
}
};
const isType$1 = type => value => typeOf(value) === type;
const isSimpleType = type => value => typeof value === type;
const eq$1 = t => a => t === a;
const isString = isType$1('string');
const isArray = isType$1('array');
const isBoolean = isSimpleType('boolean');
const isUndefined = eq$1(undefined);
const isNullable = a => a === null || a === undefined;
const isNonNullable = a => !isNullable(a);
const isFunction = isSimpleType('function');
const isNumber = isSimpleType('number');
const noop = () => {
};
const compose1 = (fbc, fab) => a => fbc(fab(a));
const constant = value => {
return () => {
return value;
};
};
const identity = x => {
return x;
};
const tripleEquals = (a, b) => {
return a === b;
};
function curry(fn, ...initialArgs) {
return (...restArgs) => {
const all = initialArgs.concat(restArgs);
return fn.apply(null, all);
};
}
const never = constant(false);
const always = constant(true);
class Optional {
constructor(tag, value) {
this.tag = tag;
this.value = value;
}
static some(value) {
return new Optional(true, value);
}
static none() {
return Optional.singletonNone;
}
fold(onNone, onSome) {
if (this.tag) {
return onSome(this.value);
} else {
return onNone();
}
}
isSome() {
return this.tag;
}
isNone() {
return !this.tag;
}
map(mapper) {
if (this.tag) {
return Optional.some(mapper(this.value));
} else {
return Optional.none();
}
}
bind(binder) {
if (this.tag) {
return binder(this.value);
} else {
return Optional.none();
}
}
exists(predicate) {
return this.tag && predicate(this.value);
}
forall(predicate) {
return !this.tag || predicate(this.value);
}
filter(predicate) {
if (!this.tag || predicate(this.value)) {
return this;
} else {
return Optional.none();
}
}
getOr(replacement) {
return this.tag ? this.value : replacement;
}
or(replacement) {
return this.tag ? this : replacement;
}
getOrThunk(thunk) {
return this.tag ? this.value : thunk();
}
orThunk(thunk) {
return this.tag ? this : thunk();
}
getOrDie(message) {
if (!this.tag) {
throw new Error(message !== null && message !== void 0 ? message : 'Called getOrDie on None');
} else {
return this.value;
}
}
static from(value) {
return isNonNullable(value) ? Optional.some(value) : Optional.none();
}
getOrNull() {
return this.tag ? this.value : null;
}
getOrUndefined() {
return this.value;
}
each(worker) {
if (this.tag) {
worker(this.value);
}
}
toArray() {
return this.tag ? [this.value] : [];
}
toString() {
return this.tag ? `some(${ this.value })` : 'none()';
}
}
Optional.singletonNone = new Optional(false);
const keys = Object.keys;
const hasOwnProperty = Object.hasOwnProperty;
const each$1 = (obj, f) => {
const props = keys(obj);
for (let k = 0, len = props.length; k < len; k++) {
const i = props[k];
const x = obj[i];
f(x, i);
}
};
const objAcc = r => (x, i) => {
r[i] = x;
};
const internalFilter = (obj, pred, onTrue, onFalse) => {
const r = {};
each$1(obj, (x, i) => {
(pred(x, i) ? onTrue : onFalse)(x, i);
});
return r;
};
const filter$1 = (obj, pred) => {
const t = {};
internalFilter(obj, pred, objAcc(t), noop);
return t;
};
const mapToArray = (obj, f) => {
const r = [];
each$1(obj, (value, name) => {
r.push(f(value, name));
});
return r;
};
const values = obj => {
return mapToArray(obj, identity);
};
const size = obj => {
return keys(obj).length;
};
const get$4 = (obj, key) => {
return has(obj, key) ? Optional.from(obj[key]) : Optional.none();
};
const has = (obj, key) => hasOwnProperty.call(obj, key);
const hasNonNullableKey = (obj, key) => has(obj, key) && obj[key] !== undefined && obj[key] !== null;
const nativeIndexOf = Array.prototype.indexOf;
const nativePush = Array.prototype.push;
const rawIndexOf = (ts, t) => nativeIndexOf.call(ts, t);
const contains = (xs, x) => rawIndexOf(xs, x) > -1;
const exists = (xs, pred) => {
for (let i = 0, len = xs.length; i < len; i++) {
const x = xs[i];
if (pred(x, i)) {
return true;
}
}
return false;
};
const range = (num, f) => {
const r = [];
for (let i = 0; i < num; i++) {
r.push(f(i));
}
return r;
};
const map = (xs, f) => {
const len = xs.length;
const r = new Array(len);
for (let i = 0; i < len; i++) {
const x = xs[i];
r[i] = f(x, i);
}
return r;
};
const each = (xs, f) => {
for (let i = 0, len = xs.length; i < len; i++) {
const x = xs[i];
f(x, i);
}
};
const eachr = (xs, f) => {
for (let i = xs.length - 1; i >= 0; i--) {
const x = xs[i];
f(x, i);
}
};
const partition = (xs, pred) => {
const pass = [];
const fail = [];
for (let i = 0, len = xs.length; i < len; i++) {
const x = xs[i];
const arr = pred(x, i) ? pass : fail;
arr.push(x);
}
return {
pass,
fail
};
};
const filter = (xs, pred) => {
const r = [];
for (let i = 0, len = xs.length; i < len; i++) {
const x = xs[i];
if (pred(x, i)) {
r.push(x);
}
}
return r;
};
const foldr = (xs, f, acc) => {
eachr(xs, (x, i) => {
acc = f(acc, x, i);
});
return acc;
};
const foldl = (xs, f, acc) => {
each(xs, (x, i) => {
acc = f(acc, x, i);
});
return acc;
};
const findUntil = (xs, pred, until) => {
for (let i = 0, len = xs.length; i < len; i++) {
const x = xs[i];
if (pred(x, i)) {
return Optional.some(x);
} else if (until(x, i)) {
break;
}
}
return Optional.none();
};
const find = (xs, pred) => {
return findUntil(xs, pred, never);
};
const flatten$1 = xs => {
const r = [];
for (let i = 0, len = xs.length; i < len; ++i) {
if (!isArray(xs[i])) {
throw new Error('Arr.flatten item ' + i + ' was not an array, input: ' + xs);
}
nativePush.apply(r, xs[i]);
}
return r;
};
const bind = (xs, f) => flatten$1(map(xs, f));
const forall = (xs, pred) => {
for (let i = 0, len = xs.length; i < len; ++i) {
const x = xs[i];
if (pred(x, i) !== true) {
return false;
}
}
return true;
};
const mapToObject = (xs, f) => {
const r = {};
for (let i = 0, len = xs.length; i < len; i++) {
const x = xs[i];
r[String(x)] = f(x, i);
}
return r;
};
const get$3 = (xs, i) => i >= 0 && i < xs.length ? Optional.some(xs[i]) : Optional.none();
const head = xs => get$3(xs, 0);
const last = xs => get$3(xs, xs.length - 1);
const findMap = (arr, f) => {
for (let i = 0; i < arr.length; i++) {
const r = f(arr[i], i);
if (r.isSome()) {
return r;
}
}
return Optional.none();
};
const fromHtml = (html, scope) => {
const doc = scope || document;
const div = doc.createElement('div');
div.innerHTML = html;
if (!div.hasChildNodes() || div.childNodes.length > 1) {
const message = 'HTML does not have a single root node';
console.error(message, html);
throw new Error(message);
}
return fromDom$1(div.childNodes[0]);
};
const fromTag = (tag, scope) => {
const doc = scope || document;
const node = doc.createElement(tag);
return fromDom$1(node);
};
const fromText = (text, scope) => {
const doc = scope || document;
const node = doc.createTextNode(text);
return fromDom$1(node);
};
const fromDom$1 = node => {
if (node === null || node === undefined) {
throw new Error('Node cannot be null or undefined');
}
return { dom: node };
};
const fromPoint = (docElm, x, y) => Optional.from(docElm.dom.elementFromPoint(x, y)).map(fromDom$1);
const SugarElement = {
fromHtml,
fromTag,
fromText,
fromDom: fromDom$1,
fromPoint
};
typeof window !== 'undefined' ? window : Function('return this;')();
const COMMENT = 8;
const DOCUMENT = 9;
const DOCUMENT_FRAGMENT = 11;
const ELEMENT = 1;
const TEXT = 3;
const name = element => {
const r = element.dom.nodeName;
return r.toLowerCase();
};
const type = element => element.dom.nodeType;
const isType = t => element => type(element) === t;
const isComment = element => type(element) === COMMENT || name(element) === '#comment';
const isElement = isType(ELEMENT);
const isText = isType(TEXT);
const isDocument = isType(DOCUMENT);
const isDocumentFragment = isType(DOCUMENT_FRAGMENT);
const isTag = tag => e => isElement(e) && name(e) === tag;
const is$2 = (element, selector) => {
const dom = element.dom;
if (dom.nodeType !== ELEMENT) {
return false;
} else {
const elem = dom;
if (elem.matches !== undefined) {
return elem.matches(selector);
} else if (elem.msMatchesSelector !== undefined) {
return elem.msMatchesSelector(selector);
} else if (elem.webkitMatchesSelector !== undefined) {
return elem.webkitMatchesSelector(selector);
} else if (elem.mozMatchesSelector !== undefined) {
return elem.mozMatchesSelector(selector);
} else {
throw new Error('Browser lacks native selectors');
}
}
};
const bypassSelector = dom => dom.nodeType !== ELEMENT && dom.nodeType !== DOCUMENT && dom.nodeType !== DOCUMENT_FRAGMENT || dom.childElementCount === 0;
const all$1 = (selector, scope) => {
const base = scope === undefined ? document : scope.dom;
return bypassSelector(base) ? [] : map(base.querySelectorAll(selector), SugarElement.fromDom);
};
const one = (selector, scope) => {
const base = scope === undefined ? document : scope.dom;
return bypassSelector(base) ? Optional.none() : Optional.from(base.querySelector(selector)).map(SugarElement.fromDom);
};
const eq = (e1, e2) => e1.dom === e2.dom;
const is$1 = is$2;
const owner = element => SugarElement.fromDom(element.dom.ownerDocument);
const documentOrOwner = dos => isDocument(dos) ? dos : owner(dos);
const parent = element => Optional.from(element.dom.parentNode).map(SugarElement.fromDom);
const parents = (element, isRoot) => {
const stop = isFunction(isRoot) ? isRoot : never;
let dom = element.dom;
const ret = [];
while (dom.parentNode !== null && dom.parentNode !== undefined) {
const rawParent = dom.parentNode;
const p = SugarElement.fromDom(rawParent);
ret.push(p);
if (stop(p) === true) {
break;
} else {
dom = rawParent;
}
}
return ret;
};
const prevSibling = element => Optional.from(element.dom.previousSibling).map(SugarElement.fromDom);
const nextSibling = element => Optional.from(element.dom.nextSibling).map(SugarElement.fromDom);
const children$3 = element => map(element.dom.childNodes, SugarElement.fromDom);
const child$3 = (element, index) => {
const cs = element.dom.childNodes;
return Optional.from(cs[index]).map(SugarElement.fromDom);
};
const firstChild = element => child$3(element, 0);
const isShadowRoot = dos => isDocumentFragment(dos) && isNonNullable(dos.dom.host);
const supported = isFunction(Element.prototype.attachShadow) && isFunction(Node.prototype.getRootNode);
const getRootNode = supported ? e => SugarElement.fromDom(e.dom.getRootNode()) : documentOrOwner;
const getShadowRoot = e => {
const r = getRootNode(e);
return isShadowRoot(r) ? Optional.some(r) : Optional.none();
};
const getShadowHost = e => SugarElement.fromDom(e.dom.host);
const inBody = element => {
const dom = isText(element) ? element.dom.parentNode : element.dom;
if (dom === undefined || dom === null || dom.ownerDocument === null) {
return false;
}
const doc = dom.ownerDocument;
return getShadowRoot(SugarElement.fromDom(dom)).fold(() => doc.body.contains(dom), compose1(inBody, getShadowHost));
};
const children$2 = (scope, predicate) => filter(children$3(scope), predicate);
const descendants$1 = (scope, predicate) => {
let result = [];
each(children$3(scope), x => {
if (predicate(x)) {
result = result.concat([x]);
}
result = result.concat(descendants$1(x, predicate));
});
return result;
};
const children$1 = (scope, selector) => children$2(scope, e => is$2(e, selector));
const descendants = (scope, selector) => all$1(selector, scope);
var ClosestOrAncestor = (is, ancestor, scope, a, isRoot) => {
if (is(scope, a)) {
return Optional.some(scope);
} else if (isFunction(isRoot) && isRoot(scope)) {
return Optional.none();
} else {
return ancestor(scope, a, isRoot);
}
};
const ancestor$1 = (scope, predicate, isRoot) => {
let element = scope.dom;
const stop = isFunction(isRoot) ? isRoot : never;
while (element.parentNode) {
element = element.parentNode;
const el = SugarElement.fromDom(element);
if (predicate(el)) {
return Optional.some(el);
} else if (stop(el)) {
break;
}
}
return Optional.none();
};
const child$2 = (scope, predicate) => {
const pred = node => predicate(SugarElement.fromDom(node));
const result = find(scope.dom.childNodes, pred);
return result.map(SugarElement.fromDom);
};
const ancestor = (scope, selector, isRoot) => ancestor$1(scope, e => is$2(e, selector), isRoot);
const child$1 = (scope, selector) => child$2(scope, e => is$2(e, selector));
const descendant = (scope, selector) => one(selector, scope);
const closest = (scope, selector, isRoot) => {
const is = (element, selector) => is$2(element, selector);
return ClosestOrAncestor(is, ancestor, scope, selector, isRoot);
};
const rawSet = (dom, key, value) => {
if (isString(value) || isBoolean(value) || isNumber(value)) {
dom.setAttribute(key, value + '');
} else {
console.error('Invalid call to Attribute.set. Key ', key, ':: Value ', value, ':: Element ', dom);
throw new Error('Attribute value was not simple');
}
};
const set$2 = (element, key, value) => {
rawSet(element.dom, key, value);
};
const setAll = (element, attrs) => {
const dom = element.dom;
each$1(attrs, (v, k) => {
rawSet(dom, k, v);
});
};
const get$2 = (element, key) => {
const v = element.dom.getAttribute(key);
return v === null ? undefined : v;
};
const getOpt = (element, key) => Optional.from(get$2(element, key));
const remove$2 = (element, key) => {
element.dom.removeAttribute(key);
};
const clone = element => foldl(element.dom.attributes, (acc, attr) => {
acc[attr.name] = attr.value;
return acc;
}, {});
const is = (lhs, rhs, comparator = tripleEquals) => lhs.exists(left => comparator(left, rhs));
const cat = arr => {
const r = [];
const push = x => {
r.push(x);
};
for (let i = 0; i < arr.length; i++) {
arr[i].each(push);
}
return r;
};
const lift2 = (oa, ob, f) => oa.isSome() && ob.isSome() ? Optional.some(f(oa.getOrDie(), ob.getOrDie())) : Optional.none();
const flatten = oot => oot.bind(identity);
const someIf = (b, a) => b ? Optional.some(a) : Optional.none();
const removeFromStart = (str, numChars) => {
return str.substring(numChars);
};
const checkRange = (str, substr, start) => substr === '' || str.length >= substr.length && str.substr(start, start + substr.length) === substr;
const removeLeading = (str, prefix) => {
return startsWith(str, prefix) ? removeFromStart(str, prefix.length) : str;
};
const startsWith = (str, prefix) => {
return checkRange(str, prefix, 0);
};
const blank = r => s => s.replace(r, '');
const trim = blank(/^\s+|\s+$/g);
const isNotEmpty = s => s.length > 0;
const isEmpty = s => !isNotEmpty(s);
const toFloat = value => {
const num = parseFloat(value);
return isNaN(num) ? Optional.none() : Optional.some(num);
};
const isSupported = dom => dom.style !== undefined && isFunction(dom.style.getPropertyValue);
const internalSet = (dom, property, value) => {
if (!isString(value)) {
console.error('Invalid call to CSS.set. Property ', property, ':: Value ', value, ':: Element ', dom);
throw new Error('CSS value must be a string: ' + value);
}
if (isSupported(dom)) {
dom.style.setProperty(property, value);
}
};
const internalRemove = (dom, property) => {
if (isSupported(dom)) {
dom.style.removeProperty(property);
}
};
const set$1 = (element, property, value) => {
const dom = element.dom;
internalSet(dom, property, value);
};
const get$1 = (element, property) => {
const dom = element.dom;
const styles = window.getComputedStyle(dom);
const r = styles.getPropertyValue(property);
return r === '' && !inBody(element) ? getUnsafeProperty(dom, property) : r;
};
const getUnsafeProperty = (dom, property) => isSupported(dom) ? dom.style.getPropertyValue(property) : '';
const getRaw = (element, property) => {
const dom = element.dom;
const raw = getUnsafeProperty(dom, property);
return Optional.from(raw).filter(r => r.length > 0);
};
const remove$1 = (element, property) => {
const dom = element.dom;
internalRemove(dom, property);
if (is(getOpt(element, 'style').map(trim), '')) {
remove$2(element, 'style');
}
};
const getAttrValue = (cell, name, fallback = 0) => getOpt(cell, name).map(value => parseInt(value, 10)).getOr(fallback);
const firstLayer = (scope, selector) => {
return filterFirstLayer(scope, selector, always);
};
const filterFirstLayer = (scope, selector, predicate) => {
return bind(children$3(scope), x => {
if (is$2(x, selector)) {
return predicate(x) ? [x] : [];
} else {
return filterFirstLayer(x, selector, predicate);
}
});
};
const validSectionList = [
'tfoot',
'thead',
'tbody',
'colgroup'
];
const isValidSection = parentName => contains(validSectionList, parentName);
const grid = (rows, columns) => ({
rows,
columns
});
const detail = (element, rowspan, colspan) => ({
element,
rowspan,
colspan
});
const extended = (element, rowspan, colspan, row, column, isLocked) => ({
element,
rowspan,
colspan,
row,
column,
isLocked
});
const rowdetail = (element, cells, section) => ({
element,
cells,
section
});
const bounds = (startRow, startCol, finishRow, finishCol) => ({
startRow,
startCol,
finishRow,
finishCol
});
const columnext = (element, colspan, column) => ({
element,
colspan,
column
});
const colgroup = (element, columns) => ({
element,
columns
});
const lookup = (tags, element, isRoot = never) => {
if (isRoot(element)) {
return Optional.none();
}
if (contains(tags, name(element))) {
return Optional.some(element);
}
const isRootOrUpperTable = elm => is$2(elm, 'table') || isRoot(elm);
return ancestor(element, tags.join(','), isRootOrUpperTable);
};
const cell = (element, isRoot) => lookup([
'td',
'th'
], element, isRoot);
const cells = ancestor => firstLayer(ancestor, 'th,td');
const columns = ancestor => {
if (is$2(ancestor, 'colgroup')) {
return children$1(ancestor, 'col');
} else {
return bind(columnGroups(ancestor), columnGroup => children$1(columnGroup, 'col'));
}
};
const table = (element, isRoot) => closest(element, 'table', isRoot);
const rows = ancestor => firstLayer(ancestor, 'tr');
const columnGroups = ancestor => table(ancestor).fold(constant([]), table => children$1(table, 'colgroup'));
const fromRowsOrColGroups = (elems, getSection) => map(elems, row => {
if (name(row) === 'colgroup') {
const cells = map(columns(row), column => {
const colspan = getAttrValue(column, 'span', 1);
return detail(column, 1, colspan);
});
return rowdetail(row, cells, 'colgroup');
} else {
const cells$1 = map(cells(row), cell => {
const rowspan = getAttrValue(cell, 'rowspan', 1);
const colspan = getAttrValue(cell, 'colspan', 1);
return detail(cell, rowspan, colspan);
});
return rowdetail(row, cells$1, getSection(row));
}
});
const getParentSection = group => parent(group).map(parent => {
const parentName = name(parent);
return isValidSection(parentName) ? parentName : 'tbody';
}).getOr('tbody');
const fromTable$1 = table => {
const rows$1 = rows(table);
const columnGroups$1 = columnGroups(table);
const elems = [
...columnGroups$1,
...rows$1
];
return fromRowsOrColGroups(elems, getParentSection);
};
const LOCKED_COL_ATTR = 'data-snooker-locked-cols';
const getLockedColumnsFromTable = table => getOpt(table, LOCKED_COL_ATTR).bind(lockedColStr => Optional.from(lockedColStr.match(/\d+/g))).map(lockedCols => mapToObject(lockedCols, always));
const key = (row, column) => {
return row + ',' + column;
};
const getAt = (warehouse, row, column) => Optional.from(warehouse.access[key(row, column)]);
const findItem = (warehouse, item, comparator) => {
const filtered = filterItems(warehouse, detail => {
return comparator(item, detail.element);
});
return filtered.length > 0 ? Optional.some(filtered[0]) : Optional.none();
};
const filterItems = (warehouse, predicate) => {
const all = bind(warehouse.all, r => {
return r.cells;
});
return filter(all, predicate);
};
const generateColumns = rowData => {
const columnsGroup = {};
let index = 0;
each(rowData.cells, column => {
const colspan = column.colspan;
range(colspan, columnIndex => {
const colIndex = index + columnIndex;
columnsGroup[colIndex] = columnext(column.element, colspan, colIndex);
});
index += colspan;
});
return columnsGroup;
};
const generate$1 = list => {
const access = {};
const cells = [];
const tableOpt = head(list).map(rowData => rowData.element).bind(table);
const lockedColumns = tableOpt.bind(getLockedColumnsFromTable).getOr({});
let maxRows = 0;
let maxColumns = 0;
let rowCount = 0;
const {
pass: colgroupRows,
fail: rows
} = partition(list, rowData => rowData.section === 'colgroup');
each(rows, rowData => {
const currentRow = [];
each(rowData.cells, rowCell => {
let start = 0;
while (access[key(rowCount, start)] !== undefined) {
start++;
}
const isLocked = hasNonNullableKey(lockedColumns, start.toString());
const current = extended(rowCell.element, rowCell.rowspan, rowCell.colspan, rowCount, start, isLocked);
for (let occupiedColumnPosition = 0; occupiedColumnPosition < rowCell.colspan; occupiedColumnPosition++) {
for (let occupiedRowPosition = 0; occupiedRowPosition < rowCell.rowspan; occupiedRowPosition++) {
const rowPosition = rowCount + occupiedRowPosition;
const columnPosition = start + occupiedColumnPosition;
const newpos = key(rowPosition, columnPosition);
access[newpos] = current;
maxColumns = Math.max(maxColumns, columnPosition + 1);
}
}
currentRow.push(current);
});
maxRows++;
cells.push(rowdetail(rowData.element, currentRow, rowData.section));
rowCount++;
});
const {columns, colgroups} = last(colgroupRows).map(rowData => {
const columns = generateColumns(rowData);
const colgroup$1 = colgroup(rowData.element, values(columns));
return {
colgroups: [colgroup$1],
columns
};
}).getOrThunk(() => ({
colgroups: [],
columns: {}
}));
const grid$1 = grid(maxRows, maxColumns);
return {
grid: grid$1,
access,
all: cells,
columns,
colgroups
};
};
const fromTable = table => {
const list = fromTable$1(table);
return generate$1(list);
};
const justCells = warehouse => bind(warehouse.all, w => w.cells);
const justColumns = warehouse => values(warehouse.columns);
const hasColumns = warehouse => keys(warehouse.columns).length > 0;
const getColumnAt = (warehouse, columnIndex) => Optional.from(warehouse.columns[columnIndex]);
const Warehouse = {
fromTable,
generate: generate$1,
getAt,
findItem,
filterItems,
justCells,
justColumns,
hasColumns,
getColumnAt
};
var global$2 = tinymce.util.Tools.resolve('tinymce.util.Tools');
const getTDTHOverallStyle = (dom, elm, name) => {
const cells = dom.select('td,th', elm);
let firstChildStyle;
const checkChildren = (firstChildStyle, elms) => {
for (let i = 0; i < elms.length; i++) {
const currentStyle = dom.getStyle(elms[i], name);
if (typeof firstChildStyle === 'undefined') {
firstChildStyle = currentStyle;
}
if (firstChildStyle !== currentStyle) {
return '';
}
}
return firstChildStyle;
};
return checkChildren(firstChildStyle, cells);
};
const applyAlign = (editor, elm, name) => {
if (name) {
editor.formatter.apply('align' + name, {}, elm);
}
};
const applyVAlign = (editor, elm, name) => {
if (name) {
editor.formatter.apply('valign' + name, {}, elm);
}
};
const unApplyAlign = (editor, elm) => {
global$2.each('left center right'.split(' '), name => {
editor.formatter.remove('align' + name, {}, elm);
});
};
const unApplyVAlign = (editor, elm) => {
global$2.each('top middle bottom'.split(' '), name => {
editor.formatter.remove('valign' + name, {}, elm);
});
};
const fireTableModified = (editor, table, data) => {
editor.dispatch('TableModified', {
...data,
table
});
};
const toNumber = (px, fallback) => toFloat(px).getOr(fallback);
const getProp = (element, name, fallback) => toNumber(get$1(element, name), fallback);
const calcContentBoxSize = (element, size, upper, lower) => {
const paddingUpper = getProp(element, `padding-${ upper }`, 0);
const paddingLower = getProp(element, `padding-${ lower }`, 0);
const borderUpper = getProp(element, `border-${ upper }-width`, 0);
const borderLower = getProp(element, `border-${ lower }-width`, 0);
return size - paddingUpper - paddingLower - borderUpper - borderLower;
};
const getCalculatedWidth = (element, boxSizing) => {
const dom = element.dom;
const width = dom.getBoundingClientRect().width || dom.offsetWidth;
return boxSizing === 'border-box' ? width : calcContentBoxSize(element, width, 'left', 'right');
};
const getInnerWidth = element => getCalculatedWidth(element, 'content-box');
const getInner = getInnerWidth;
var global$1 = tinymce.util.Tools.resolve('tinymce.Env');
const defaultTableToolbar = 'tableprops tabledelete | tableinsertrowbefore tableinsertrowafter tabledeleterow | tableinsertcolbefore tableinsertcolafter tabledeletecol';
const defaultCellBorderWidths = range(5, i => {
const size = `${ i + 1 }px`;
return {
title: size,
value: size
};
});
const defaultCellBorderStyles = map([
'Solid',
'Dotted',
'Dashed',
'Double',
'Groove',
'Ridge',
'Inset',
'Outset',
'None',
'Hidden'
], type => {
return {
title: type,
value: type.toLowerCase()
};
});
const determineDefaultStyles = (editor, defaultStyles) => {
var _a;
if (isPixelsForced(editor)) {
const dom = editor.dom;
const parentBlock = (_a = dom.getParent(editor.selection.getStart(), dom.isBlock)) !== null && _a !== void 0 ? _a : editor.getBody();
const contentWidth = getInner(SugarElement.fromDom(parentBlock));
return {
...defaultStyles,
width: contentWidth + 'px'
};
} else if (isResponsiveForced(editor)) {
return filter$1(defaultStyles, (_value, key) => key !== 'width');
} else {
return defaultStyles;
}
};
const option = name => editor => editor.options.get(name);
const register = editor => {
const registerOption = editor.options.register;
registerOption('table_border_widths', {
processor: 'object[]',
default: defaultCellBorderWidths
});
registerOption('table_border_styles', {
processor: 'object[]',
default: defaultCellBorderStyles
});
registerOption('table_cell_advtab', {
processor: 'boolean',
default: true
});
registerOption('table_row_advtab', {
processor: 'boolean',
default: true
});
registerOption('table_advtab', {
processor: 'boolean',
default: true
});
registerOption('table_appearance_options', {
processor: 'boolean',
default: true
});
registerOption('table_grid', {
processor: 'boolean',
default: !global$1.deviceType.isTouch()
});
registerOption('table_style_by_css', {
processor: 'boolean',
default: true
});
registerOption('table_cell_class_list', {
processor: 'object[]',
default: []
});
registerOption('table_row_class_list', {
processor: 'object[]',
default: []
});
registerOption('table_class_list', {
processor: 'object[]',
default: []
});
registerOption('table_toolbar', {
processor: 'string',
default: defaultTableToolbar
});
registerOption('table_background_color_map', {
processor: 'object[]',
default: []
});
registerOption('table_border_color_map', {
processor: 'object[]',
default: []
});
};
const getTableSizingMode = option('table_sizing_mode');
const getTableBorderWidths = option('table_border_widths');
const getTableBorderStyles = option('table_border_styles');
const getDefaultAttributes = option('table_default_attributes');
const hasAdvancedCellTab = option('table_cell_advtab');
const hasAdvancedRowTab = option('table_row_advtab');
const hasAdvancedTableTab = option('table_advtab');
const hasAppearanceOptions = option('table_appearance_options');
const hasTableGrid = option('table_grid');
const shouldStyleWithCss = option('table_style_by_css');
const getCellClassList = option('table_cell_class_list');
const getRowClassList = option('table_row_class_list');
const getTableClassList = option('table_class_list');
const getToolbar = option('table_toolbar');
const getTableBackgroundColorMap = option('table_background_color_map');
const getTableBorderColorMap = option('table_border_color_map');
const isPixelsForced = editor => getTableSizingMode(editor) === 'fixed';
const isResponsiveForced = editor => getTableSizingMode(editor) === 'responsive';
const getDefaultStyles = editor => {
const options = editor.options;
const defaultStyles = options.get('table_default_styles');
return options.isSet('table_default_styles') ? defaultStyles : determineDefaultStyles(editor, defaultStyles);
};
const getNodeName = elm => elm.nodeName.toLowerCase();
const getBody = editor => SugarElement.fromDom(editor.getBody());
const getIsRoot = editor => element => eq(element, getBody(editor));
const removePxSuffix = size => size ? size.replace(/px$/, '') : '';
const addPxSuffix = size => /^\d+(\.\d+)?$/.test(size) ? size + 'px' : size;
const getSelectionStart = editor => SugarElement.fromDom(editor.selection.getStart());
const getSelectionEnd = editor => SugarElement.fromDom(editor.selection.getEnd());
const isWithin = (bounds, detail) => {
return detail.column >= bounds.startCol && detail.column + detail.colspan - 1 <= bounds.finishCol && detail.row >= bounds.startRow && detail.row + detail.rowspan - 1 <= bounds.finishRow;
};
const isRectangular = (warehouse, bounds) => {
let isRect = true;
const detailIsWithin = curry(isWithin, bounds);
for (let i = bounds.startRow; i <= bounds.finishRow; i++) {
for (let j = bounds.startCol; j <= bounds.finishCol; j++) {
isRect = isRect && Warehouse.getAt(warehouse, i, j).exists(detailIsWithin);
}
}
return isRect ? Optional.some(bounds) : Optional.none();
};
const getBounds = (detailA, detailB) => {
return bounds(Math.min(detailA.row, detailB.row), Math.min(detailA.column, detailB.column), Math.max(detailA.row + detailA.rowspan - 1, detailB.row + detailB.rowspan - 1), Math.max(detailA.column + detailA.colspan - 1, detailB.column + detailB.colspan - 1));
};
const getAnyBox = (warehouse, startCell, finishCell) => {
const startCoords = Warehouse.findItem(warehouse, startCell, eq);
const finishCoords = Warehouse.findItem(warehouse, finishCell, eq);
return startCoords.bind(sc => {
return finishCoords.map(fc => {
return getBounds(sc, fc);
});
});
};
const getBox$1 = (warehouse, startCell, finishCell) => {
return getAnyBox(warehouse, startCell, finishCell).bind(bounds => {
return isRectangular(warehouse, bounds);
});
};
const getBox = (table, first, last) => {
const warehouse = getWarehouse(table);
return getBox$1(warehouse, first, last);
};
const getWarehouse = Warehouse.fromTable;
const before = (marker, element) => {
const parent$1 = parent(marker);
parent$1.each(v => {
v.dom.insertBefore(element.dom, marker.dom);
});
};
const after$1 = (marker, element) => {
const sibling = nextSibling(marker);
sibling.fold(() => {
const parent$1 = parent(marker);
parent$1.each(v => {
append$1(v, element);
});
}, v => {
before(v, element);
});
};
const prepend = (parent, element) => {
const firstChild$1 = firstChild(parent);
firstChild$1.fold(() => {
append$1(parent, element);
}, v => {
parent.dom.insertBefore(element.dom, v.dom);
});
};
const append$1 = (parent, element) => {
parent.dom.appendChild(element.dom);
};
const wrap = (element, wrapper) => {
before(element, wrapper);
append$1(wrapper, element);
};
const after = (marker, elements) => {
each(elements, (x, i) => {
const e = i === 0 ? marker : elements[i - 1];
after$1(e, x);
});
};
const append = (parent, elements) => {
each(elements, x => {
append$1(parent, x);
});
};
const remove = element => {
const dom = element.dom;
if (dom.parentNode !== null) {
dom.parentNode.removeChild(dom);
}
};
const unwrap = wrapper => {
const children = children$3(wrapper);
if (children.length > 0) {
after(wrapper, children);
}
remove(wrapper);
};
const NodeValue = (is, name) => {
const get = element => {
if (!is(element)) {
throw new Error('Can only get ' + name + ' value of a ' + name + ' node');
}
return getOption(element).getOr('');
};
const getOption = element => is(element) ? Optional.from(element.dom.nodeValue) : Optional.none();
const set = (element, value) => {
if (!is(element)) {
throw new Error('Can only set raw ' + name + ' value of a ' + name + ' node');
}
element.dom.nodeValue = value;
};
return {
get,
getOption,
set
};
};
const api = NodeValue(isText, 'text');
const get = element => api.get(element);
const set = (element, value) => api.set(element, value);
var TagBoundaries = [
'body',
'p',
'div',
'article',
'aside',
'figcaption',
'figure',
'footer',
'header',
'nav',
'section',
'ol',
'ul',
'li',
'table',
'thead',
'tbody',
'tfoot',
'caption',
'tr',
'td',
'th',
'h1',
'h2',
'h3',
'h4',
'h5',
'h6',
'blockquote',
'pre',
'address'
];
var DomUniverse = () => {
const clone$1 = element => {
return SugarElement.fromDom(element.dom.cloneNode(false));
};
const document = element => documentOrOwner(element).dom;
const isBoundary = element => {
if (!isElement(element)) {
return false;
}
if (name(element) === 'body') {
return true;
}
return contains(TagBoundaries, name(element));
};
const isEmptyTag = element => {
if (!isElement(element)) {
return false;
}
return contains([
'br',
'img',
'hr',
'input'
], name(element));
};
const isNonEditable = element => isElement(element) && get$2(element, 'contenteditable') === 'false';
const comparePosition = (element, other) => {
return element.dom.compareDocumentPosition(other.dom);
};
const copyAttributesTo = (source, destination) => {
const as = clone(source);
setAll(destination, as);
};
const isSpecial = element => {
const tag = name(element);
return contains([
'script',
'noscript',
'iframe',
'noframes',
'noembed',
'title',
'style',
'textarea',
'xmp'
], tag);
};
const getLanguage = element => isElement(element) ? getOpt(element, 'lang') : Optional.none();
return {
up: constant({
selector: ancestor,
closest: closest,
predicate: ancestor$1,
all: parents
}),
down: constant({
selector: descendants,
predicate: descendants$1
}),
styles: constant({
get: get$1,
getRaw: getRaw,
set: set$1,
remove: remove$1
}),
attrs: constant({
get: get$2,
set: set$2,
remove: remove$2,
copyTo: copyAttributesTo
}),
insert: constant({
before: before,
after: after$1,
afterAll: after,
append: append$1,
appendAll: append,
prepend: prepend,
wrap: wrap
}),
remove: constant({
unwrap: unwrap,
remove: remove
}),
create: constant({
nu: SugarElement.fromTag,
clone: clone$1,
text: SugarElement.fromText
}),
query: constant({
comparePosition,
prevSibling: prevSibling,
nextSibling: nextSibling
}),
property: constant({
children: children$3,
name: name,
parent: parent,
document,
isText: isText,
isComment: isComment,
isElement: isElement,
isSpecial,
getLanguage,
getText: get,
setText: set,
isBoundary,
isEmptyTag,
isNonEditable
}),
eq: eq,
is: is$1
};
};
const all = (universe, look, elements, f) => {
const head = elements[0];
const tail = elements.slice(1);
return f(universe, look, head, tail);
};
const oneAll = (universe, look, elements) => {
return elements.length > 0 ? all(universe, look, elements, unsafeOne) : Optional.none();
};
const unsafeOne = (universe, look, head, tail) => {
const start = look(universe, head);
return foldr(tail, (b, a) => {
const current = look(universe, a);
return commonElement(universe, b, current);
}, start);
};
const commonElement = (universe, start, end) => {
return start.bind(s => {
return end.filter(curry(universe.eq, s));
});
};
const sharedOne$1 = oneAll;
const universe = DomUniverse();
const sharedOne = (look, elements) => {
return sharedOne$1(universe, (_universe, element) => {
return look(element);
}, elements);
};
const lookupTable = container => {
return ancestor(container, 'table');
};
const retrieve$1 = (container, selector) => {
const sels = descendants(container, selector);
return sels.length > 0 ? Optional.some(sels) : Optional.none();
};
const getEdges = (container, firstSelectedSelector, lastSelectedSelector) => {
return descendant(container, firstSelectedSelector).bind(first => {
return descendant(container, lastSelectedSelector).bind(last => {
return sharedOne(lookupTable, [
first,
last
]).map(table => {
return {
first,
last,
table
};
});
});
});
};
const retrieve = (container, selector) => {
return retrieve$1(container, selector);
};
const retrieveBox = (container, firstSelectedSelector, lastSelectedSelector) => {
return getEdges(container, firstSelectedSelector, lastSelectedSelector).bind(edges => {
const isRoot = ancestor => {
return eq(container, ancestor);
};
const sectionSelector = 'thead,tfoot,tbody,table';
const firstAncestor = ancestor(edges.first, sectionSelector, isRoot);
const lastAncestor = ancestor(edges.last, sectionSelector, isRoot);
return firstAncestor.bind(fA => {
return lastAncestor.bind(lA => {
return eq(fA, lA) ? getBox(edges.table, edges.first, edges.last) : Optional.none();
});
});
});
};
const fromDom = nodes => map(nodes, SugarElement.fromDom);
const strSelected = 'data-mce-selected';
const strSelectedSelector = 'td[' + strSelected + '],th[' + strSelected + ']';
const strFirstSelected = 'data-mce-first-selected';
const strFirstSelectedSelector = 'td[' + strFirstSelected + '],th[' + strFirstSelected + ']';
const strLastSelected = 'data-mce-last-selected';
const strLastSelectedSelector = 'td[' + strLastSelected + '],th[' + strLastSelected + ']';
const ephemera = {
selected: strSelected,
selectedSelector: strSelectedSelector,
firstSelected: strFirstSelected,
firstSelectedSelector: strFirstSelectedSelector,
lastSelected: strLastSelected,
lastSelectedSelector: strLastSelectedSelector
};
const getSelectionCellFallback = element => table(element).bind(table => retrieve(table, ephemera.firstSelectedSelector)).fold(constant(element), cells => cells[0]);
const getSelectionFromSelector = selector => (initCell, isRoot) => {
const cellName = name(initCell);
const cell = cellName === 'col' || cellName === 'colgroup' ? getSelectionCellFallback(initCell) : initCell;
return closest(cell, selector, isRoot);
};
const getSelectionCellOrCaption = getSelectionFromSelector('th,td,caption');
const getSelectionCell = getSelectionFromSelector('th,td');
const getCellsFromSelection = editor => fromDom(editor.model.table.getSelectedCells());
const getRowsFromSelection = (selected, selector) => {
const cellOpt = getSelectionCell(selected);
const rowsOpt = cellOpt.bind(cell => table(cell)).map(table => rows(table));
return lift2(cellOpt, rowsOpt, (cell, rows) => filter(rows, row => exists(fromDom(row.dom.cells), rowCell => get$2(rowCell, selector) === '1' || eq(rowCell, cell)))).getOr([]);
};
const verticalAlignValues = [
{
text: 'None',
value: ''
},
{
text: 'Top',
value: 'top'
},
{
text: 'Middle',
value: 'middle'
},
{
text: 'Bottom',
value: 'bottom'
}
];
const hexColour = value => ({ value });
const shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
const longformRegex = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i;
const isHexString = hex => shorthandRegex.test(hex) || longformRegex.test(hex);
const normalizeHex = hex => removeLeading(hex, '#').toUpperCase();
const fromString$1 = hex => isHexString(hex) ? Optional.some({ value: normalizeHex(hex) }) : Optional.none();
const toHex = component => {
const hex = component.toString(16);
return (hex.length === 1 ? '0' + hex : hex).toUpperCase();
};
const fromRgba = rgbaColour => {
const value = toHex(rgbaColour.red) + toHex(rgbaColour.green) + toHex(rgbaColour.blue);
return hexColour(value);
};
const rgbRegex = /^\s*rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)\s*$/i;
const rgbaRegex = /^\s*rgba\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d?(?:\.\d+)?)\s*\)\s*$/i;
const rgbaColour = (red, green, blue, alpha) => ({
red,
green,
blue,
alpha
});
const fromStringValues = (red, green, blue, alpha) => {
const r = parseInt(red, 10);
const g = parseInt(green, 10);
const b = parseInt(blue, 10);
const a = parseFloat(alpha);
return rgbaColour(r, g, b, a);
};
const fromString = rgbaString => {
if (rgbaString === 'transparent') {
return Optional.some(rgbaColour(0, 0, 0, 0));
}
const rgbMatch = rgbRegex.exec(rgbaString);
if (rgbMatch !== null) {
return Optional.some(fromStringValues(rgbMatch[1], rgbMatch[2], rgbMatch[3], '1'));
}
const rgbaMatch = rgbaRegex.exec(rgbaString);
if (rgbaMatch !== null) {
return Optional.some(fromStringValues(rgbaMatch[1], rgbaMatch[2], rgbaMatch[3], rgbaMatch[4]));
}
return Optional.none();
};
const anyToHex = color => fromString$1(color).orThunk(() => fromString(color).map(fromRgba)).getOrThunk(() => {
const canvas = document.createElement('canvas');
canvas.height = 1;
canvas.width = 1;
const canvasContext = canvas.getContext('2d');
canvasContext.clearRect(0, 0, canvas.width, canvas.height);
canvasContext.fillStyle = '#FFFFFF';
canvasContext.fillStyle = color;
canvasContext.fillRect(0, 0, 1, 1);
const rgba = canvasContext.getImageData(0, 0, 1, 1).data;
const r = rgba[0];
const g = rgba[1];
const b = rgba[2];
const a = rgba[3];
return fromRgba(rgbaColour(r, g, b, a));
});
const rgbaToHexString = color => fromString(color).map(fromRgba).map(h => '#' + h.value).getOr(color);
const Cell = initial => {
let value = initial;
const get = () => {
return value;
};
const set = v => {
value = v;
};
return {
get,
set
};
};
const singleton = doRevoke => {
const subject = Cell(Optional.none());
const revoke = () => subject.get().each(doRevoke);
const clear = () => {
revoke();
subject.set(Optional.none());
};
const isSet = () => subject.get().isSome();
const get = () => subject.get();
const set = s => {
revoke();
subject.set(Optional.some(s));
};
return {
clear,
isSet,
get,
set
};
};
const unbindable = () => singleton(s => s.unbind());
const onSetupToggle = (editor, formatName, formatValue) => {
return api => {
const boundCallback = unbindable();
const isNone = isEmpty(formatValue);
const init = () => {
const selectedCells = getCellsFromSelection(editor);
const checkNode = cell => editor.formatter.match(formatName, { value: formatValue }, cell.dom, isNone);
if (isNone) {
api.setActive(!exists(selectedCells, checkNode));
boundCallback.set(editor.formatter.formatChanged(formatName, match => api.setActive(!match), true));
} else {
api.setActive(forall(selectedCells, checkNode));
boundCallback.set(editor.formatter.formatChanged(formatName, api.setActive, false, { value: formatValue }));
}
};
editor.initialized ? init() : editor.on('init', init);
return boundCallback.clear;
};
};
const isListGroup = item => hasNonNullableKey(item, 'menu');
const buildListItems = items => map(items, item => {
const text = item.text || item.title;
if (isListGroup(item)) {
return {
text,
items: buildListItems(item.menu)
};
} else {
return {
text,
value: item.value
};
}
});
const buildMenuItems = (editor, items, format, onAction) => map(items, item => {
const text = item.text || item.title;
if (isListGroup(item)) {
return {
type: 'nestedmenuitem',
text,
getSubmenuItems: () => buildMenuItems(editor, item.menu, format, onAction)
};
} else {
return {
text,
type: 'togglemenuitem',
onAction: () => onAction(item.value),
onSetup: onSetupToggle(editor, format, item.value)
};
}
});
const applyTableCellStyle = (editor, style) => value => {
editor.execCommand('mceTableApplyCellStyle', false, { [style]: value });
};
const filterNoneItem = list => bind(list, item => {
if (isListGroup(item)) {
return [{
...item,
menu: filterNoneItem(item.menu)
}];
} else {
return isNotEmpty(item.value) ? [item] : [];
}
});
const generateMenuItemsCallback = (editor, items, format, onAction) => callback => callback(buildMenuItems(editor, items, format, onAction));
const buildColorMenu = (editor, colorList, style) => {
const colorMap = map(colorList, entry => ({
text: entry.title,
value: '#' + anyToHex(entry.value).value,
type: 'choiceitem'
}));
return [{
type: 'fancymenuitem',
fancytype: 'colorswatch',
initData: {
colors: colorMap.length > 0 ? colorMap : undefined,
allowCustomColors: false
},
onAction: data => {
const value = data.value === 'remove' ? '' : data.value;
editor.execCommand('mceTableApplyCellStyle', false, { [style]: value });
}
}];
};
const changeRowHeader = editor => () => {
const currentType = editor.queryCommandValue('mceTableRowType');
const newType = currentType === 'header' ? 'body' : 'header';
editor.execCommand('mceTableRowType', false, { type: newType });
};
const changeColumnHeader = editor => () => {
const currentType = editor.queryCommandValue('mceTableColType');
const newType = currentType === 'th' ? 'td' : 'th';
editor.execCommand('mceTableColType', false, { type: newType });
};
const getClassList$1 = editor => {
const classes = buildListItems(getCellClassList(editor));
if (classes.length > 0) {
return Optional.some({
name: 'class',
type: 'listbox',
label: 'Class',
items: classes
});
}
return Optional.none();
};
const children = [
{
name: 'width',
type: 'input',
label: 'Width'
},
{
name: 'height',
type: 'input',
label: 'Height'
},
{
name: 'celltype',
type: 'listbox',
label: 'Cell type',
items: [
{
text: 'Cell',
value: 'td'
},
{
text: 'Header cell',
value: 'th'
}
]
},
{
name: 'scope',
type: 'listbox',
label: 'Scope',
items: [
{
text: 'None',
value: ''
},
{
text: 'Row',
value: 'row'
},
{
text: 'Column',
value: 'col'
},
{
text: 'Row group',
value: 'rowgroup'
},
{
text: 'Column group',
value: 'colgroup'
}
]
},
{
name: 'halign',
type: 'listbox',
label: 'Horizontal align',
items: [
{
text: 'None',
value: ''
},
{
text: 'Left',
value: 'left'
},
{
text: 'Center',
value: 'center'
},
{
text: 'Right',
value: 'right'
}
]
},
{
name: 'valign',
type: 'listbox',
label: 'Vertical align',
items: verticalAlignValues
}
];
const getItems$2 = editor => children.concat(getClassList$1(editor).toArray());
const getAdvancedTab = (editor, dialogName) => {
const emptyBorderStyle = [{
text: 'Select...',
value: ''
}];
const advTabItems = [
{
name: 'borderstyle',
type: 'listbox',
label: 'Border style',
items: emptyBorderStyle.concat(buildListItems(getTableBorderStyles(editor)))
},
{
name: 'bordercolor',
type: 'colorinput',
label: 'Border color'
},
{
name: 'backgroundcolor',
type: 'colorinput',
label: 'Background color'
}
];
const borderWidth = {
name: 'borderwidth',
type: 'input',
label: 'Border width'
};
const items = dialogName === 'cell' ? [borderWidth].concat(advTabItems) : advTabItems;
return {
title: 'Advanced',
name: 'advanced',
items
};
};
const modifiers = testTruthy => (editor, element) => {
const dom = editor.dom;
const setAttrib = (attr, value) => {
if (!testTruthy || value) {
dom.setAttrib(element, attr, value);
}
};
const setStyle = (prop, value) => {
if (!testTruthy || value) {
dom.setStyle(element, prop, value);
}
};
const setFormat = (formatName, value) => {
if (!testTruthy || value) {
if (value === '') {
editor.formatter.remove(formatName, { value: null }, element, true);
} else {
editor.formatter.apply(formatName, { value }, element);
}
}
};
return {
setAttrib,
setStyle,
setFormat
};
};
const DomModifier = {
normal: modifiers(false),
ifTruthy: modifiers(true)
};
const isHeaderCell = isTag('th');
const getRowHeaderType = (isHeaderRow, isHeaderCells) => {
if (isHeaderRow && isHeaderCells) {
return 'sectionCells';
} else if (isHeaderRow) {
return 'section';
} else {
return 'cells';
}
};
const getRowType$1 = row => {
const isHeaderRow = row.section === 'thead';
const isHeaderCells = is(findCommonCellType(row.cells), 'th');
if (row.section === 'tfoot') {
return { type: 'footer' };
} else if (isHeaderRow || isHeaderCells) {
return {
type: 'header',
subType: getRowHeaderType(isHeaderRow, isHeaderCells)
};
} else {
return { type: 'body' };
}
};
const findCommonCellType = cells => {
const headerCells = filter(cells, cell => isHeaderCell(cell.element));
if (headerCells.length === 0) {
return Optional.some('td');
} else if (headerCells.length === cells.length) {
return Optional.some('th');
} else {
return Optional.none();
}
};
const findCommonRowType = rows => {
const rowTypes = map(rows, row => getRowType$1(row).type);
const hasHeader = contains(rowTypes, 'header');
const hasFooter = contains(rowTypes, 'footer');
if (!hasHeader && !hasFooter) {
return Optional.some('body');
} else {
const hasBody = contains(rowTypes, 'body');
if (hasHeader && !hasBody && !hasFooter) {
return Optional.some('header');
} else if (!hasHeader && !hasBody && hasFooter) {
return Optional.some('footer');
} else {
return Optional.none();
}
}
};
const cached = f => {
let called = false;
let r;
return (...args) => {
if (!called) {
called = true;
r = f.apply(null, args);
}
return r;
};
};
const findInWarehouse = (warehouse, element) => findMap(warehouse.all, r => find(r.cells, e => eq(element, e.element)));
const extractCells = (warehouse, target, predicate) => {
const details = map(target.selection, cell$1 => {
return cell(cell$1).bind(lc => findInWarehouse(warehouse, lc)).filter(predicate);
});
const cells = cat(details);
return someIf(cells.length > 0, cells);
};
const onMergable = (_warehouse, target) => target.mergable;
const onUnmergable = (_warehouse, target) => target.unmergable;
const onCells = (warehouse, target) => extractCells(warehouse, target, always);
const isUnlockedTableCell = (warehouse, cell) => findInWarehouse(warehouse, cell).exists(detail => !detail.isLocked);
const allUnlocked = (warehouse, cells) => forall(cells, cell => isUnlockedTableCell(warehouse, cell));
const onUnlockedMergable = (warehouse, target) => onMergable(warehouse, target).filter(mergeable => allUnlocked(warehouse, mergeable.cells));
const onUnlockedUnmergable = (warehouse, target) => onUnmergable(warehouse, target).filter(cells => allUnlocked(warehouse, cells));
const generate = cases => {
if (!isArray(cases)) {
throw new Error('cases must be an array');
}
if (cases.length === 0) {
throw new Error('there must be at least one case');
}
const constructors = [];
const adt = {};
each(cases, (acase, count) => {
const keys$1 = keys(acase);
if (keys$1.length !== 1) {
throw new Error('one and only one name per case');
}
const key = keys$1[0];
const value = acase[key];
if (adt[key] !== undefined) {
throw new Error('duplicate key detected:' + key);
} else if (key === 'cata') {
throw new Error('cannot have a case named cata (sorry)');
} else if (!isArray(value)) {
throw new Error('case arguments must be an array');
}
constructors.push(key);
adt[key] = (...args) => {
const argLength = args.length;
if (argLength !== value.length) {
throw new Error('Wrong number of arguments to case ' + key + '. Expected ' + value.length + ' (' + value + '), got ' + argLength);
}
const match = branches => {
const branchKeys = keys(branches);
if (constructors.length !== branchKeys.length) {
throw new Error('Wrong number of arguments to match. Expected: ' + constructors.join(',') + '\nActual: ' + branchKeys.join(','));
}
const allReqd = forall(constructors, reqKey => {
return contains(branchKeys, reqKey);
});
if (!allReqd) {
throw new Error('Not all branches were specified when using match. Specified: ' + branchKeys.join(', ') + '\nRequired: ' + constructors.join(', '));
}
return branches[key].apply(null, args);
};
return {
fold: (...foldArgs) => {
if (foldArgs.length !== cases.length) {
throw new Error('Wrong number of arguments to fold. Expected ' + cases.length + ', got ' + foldArgs.length);
}
const target = foldArgs[count];
return target.apply(null, args);
},
match,
log: label => {
console.log(label, {
constructors,
constructor: key,
params: args
});
}
};
};
});
return adt;
};
const Adt = { generate };
const adt = Adt.generate([
{ none: [] },
{ only: ['index'] },
{
left: [
'index',
'next'
]
},
{
middle: [
'prev',
'index',
'next'
]
},
{
right: [
'prev',
'index'
]
}
]);
({ ...adt });
const opGetRowsType = (table, target) => {
const house = Warehouse.fromTable(table);
const details = onCells(house, target);
return details.bind(selectedCells => {
const lastSelectedCell = selectedCells[selectedCells.length - 1];
const minRowRange = selectedCells[0].row;
const maxRowRange = lastSelectedCell.row + lastSelectedCell.rowspan;
const selectedRows = house.all.slice(minRowRange, maxRowRange);
return findCommonRowType(selectedRows);
}).getOr('');
};
const getRowsType = opGetRowsType;
const rgbToHex = value => startsWith(value, 'rgb') ? rgbaToHexString(value) : value;
const extractAdvancedStyles = elm => {
const element = SugarElement.fromDom(elm);
return {
borderwidth: getRaw(element, 'border-width').getOr(''),
borderstyle: getRaw(element, 'border-style').getOr(''),
bordercolor: getRaw(element, 'border-color').map(rgbToHex).getOr(''),
backgroundcolor: getRaw(element, 'background-color').map(rgbToHex).getOr('')
};
};
const getSharedValues = data => {
const baseData = data[0];
const comparisonData = data.slice(1);
each(comparisonData, items => {
each(keys(baseData), key => {
each$1(items, (itemValue, itemKey) => {
const comparisonValue = baseData[key];
if (comparisonValue !== '' && key === itemKey) {
if (comparisonValue !== itemValue) {
baseData[key] = '';
}
}
});
});
});
return baseData;
};
const getAlignment = (formats, formatName, editor, elm) => find(formats, name => !isUndefined(editor.formatter.matchNode(elm, formatName + name))).getOr('');
const getHAlignment = curry(getAlignment, [
'left',
'center',
'right'
], 'align');
const getVAlignment = curry(getAlignment, [
'top',
'middle',
'bottom'
], 'valign');
const extractDataFromSettings = (editor, hasAdvTableTab) => {
const style = getDefaultStyles(editor);
const attrs = getDefaultAttributes(editor);
const extractAdvancedStyleData = () => ({
borderstyle: get$4(style, 'border-style').getOr(''),
bordercolor: rgbToHex(get$4(style, 'border-color').getOr('')),
backgroundcolor: rgbToHex(get$4(style, 'background-color').getOr(''))
});
const defaultData = {
height: '',
width: '100%',
cellspacing: '',
cellpadding: '',
caption: false,
class: '',
align: '',
border: ''
};
const getBorder = () => {
const borderWidth = style['border-width'];
if (shouldStyleWithCss(editor) && borderWidth) {
return { border: borderWidth };
}
return get$4(attrs, 'border').fold(() => ({}), border => ({ border }));
};
const advStyle = hasAdvTableTab ? extractAdvancedStyleData() : {};
const getCellPaddingCellSpacing = () => {
const spacing = get$4(style, 'border-spacing').or(get$4(attrs, 'cellspacing')).fold(() => ({}), cellspacing => ({ cellspacing }));
const padding = get$4(style, 'border-padding').or(get$4(attrs, 'cellpadding')).fold(() => ({}), cellpadding => ({ cellpadding }));
return {
...spacing,
...padding
};
};
const data = {
...defaultData,
...style,
...attrs,
...advStyle,
...getBorder(),
...getCellPaddingCellSpacing()
};
return data;
};
const getRowType = elm => table(SugarElement.fromDom(elm)).map(table => {
const target = { selection: fromDom(elm.cells) };
return getRowsType(table, target);
}).getOr('');
const extractDataFromTableElement = (editor, elm, hasAdvTableTab) => {
const getBorder = (dom, elm) => {
const optBorderWidth = getRaw(SugarElement.fromDom(elm), 'border-width');
if (shouldStyleWithCss(editor) && optBorderWidth.isSome()) {
return optBorderWidth.getOr('');
}
return dom.getAttrib(elm, 'border') || getTDTHOverallStyle(editor.dom, elm, 'border-width') || getTDTHOverallStyle(editor.dom, elm, 'border');
};
const dom = editor.dom;
const cellspacing = shouldStyleWithCss(editor) ? dom.getStyle(elm, 'border-spacing') || dom.getAttrib(elm, 'cellspacing') : dom.getAttrib(elm, 'cellspacing') || dom.getStyle(elm, 'border-spacing');
const cellpadding = shouldStyleWithCss(editor) ? getTDTHOverallStyle(dom, elm, 'padding') || dom.getAttrib(elm, 'cellpadding') : dom.getAttrib(elm, 'cellpadding') || getTDTHOverallStyle(dom, elm, 'padding');
return {
width: dom.getStyle(elm, 'width') || dom.getAttrib(elm, 'width'),
height: dom.getStyle(elm, 'height') || dom.getAttrib(elm, 'height'),
cellspacing,
cellpadding,
border: getBorder(dom, elm),
caption: !!dom.select('caption', elm)[0],
class: dom.getAttrib(elm, 'class', ''),
align: getHAlignment(editor, elm),
...hasAdvTableTab ? extractAdvancedStyles(elm) : {}
};
};
const extractDataFromRowElement = (editor, elm, hasAdvancedRowTab) => {
const dom = editor.dom;
return {
height: dom.getStyle(elm, 'height') || dom.getAttrib(elm, 'height'),
class: dom.getAttrib(elm, 'class', ''),
type: getRowType(elm),
align: getHAlignment(editor, elm),
...hasAdvancedRowTab ? extractAdvancedStyles(elm) : {}
};
};
const extractDataFromCellElement = (editor, cell, hasAdvancedCellTab, column) => {
const dom = editor.dom;
const colElm = column.getOr(cell);
const getStyle = (element, style) => dom.getStyle(element, style) || dom.getAttrib(element, style);
return {
width: getStyle(colElm, 'width'),
height: getStyle(cell, 'height'),
scope: dom.getAttrib(cell, 'scope'),
celltype: getNodeName(cell),
class: dom.getAttrib(cell, 'class', ''),
halign: getHAlignment(editor, cell),
valign: getVAlignment(editor, cell),
...hasAdvancedCellTab ? extractAdvancedStyles(cell) : {}
};
};
const getSelectedCells = (table, cells) => {
const warehouse = Warehouse.fromTable(table);
const allCells = Warehouse.justCells(warehouse);
const filtered = filter(allCells, cellA => exists(cells, cellB => eq(cellA.element, cellB)));
return map(filtered, cell => ({
element: cell.element.dom,
column: Warehouse.getColumnAt(warehouse, cell.column).map(col => col.element.dom)
}));
};
const updateSimpleProps$1 = (modifier, colModifier, data) => {
modifier.setAttrib('scope', data.scope);
modifier.setAttrib('class', data.class);
modifier.setStyle('height', addPxSuffix(data.height));
colModifier.setStyle('width', addPxSuffix(data.width));
};
const updateAdvancedProps$1 = (modifier, data) => {
modifier.setFormat('tablecellbackgroundcolor', data.backgroundcolor);
modifier.setFormat('tablecellbordercolor', data.bordercolor);
modifier.setFormat('tablecellborderstyle', data.borderstyle);
modifier.setFormat('tablecellborderwidth', addPxSuffix(data.borderwidth));
};
const applyStyleData$1 = (editor, cells, data) => {
const isSingleCell = cells.length === 1;
each(cells, item => {
const cellElm = item.element;
const modifier = isSingleCell ? DomModifier.normal(editor, cellElm) : DomModifier.ifTruthy(editor, cellElm);
const colModifier = item.column.map(col => isSingleCell ? DomModifier.normal(editor, col) : DomModifier.ifTruthy(editor, col)).getOr(modifier);
updateSimpleProps$1(modifier, colModifier, data);
if (hasAdvancedCellTab(editor)) {
updateAdvancedProps$1(modifier, data);
}
if (isSingleCell) {
unApplyAlign(editor, cellElm);
unApplyVAlign(editor, cellElm);
}
if (data.halign) {
applyAlign(editor, cellElm, data.halign);
}
if (data.valign) {
applyVAlign(editor, cellElm, data.valign);
}
});
};
const applyStructureData$1 = (editor, data) => {
editor.execCommand('mceTableCellType', false, {
type: data.celltype,
no_events: true
});
};
const applyCellData = (editor, cells, oldData, data) => {
const modifiedData = filter$1(data, (value, key) => oldData[key] !== value);
if (size(modifiedData) > 0 && cells.length >= 1) {
table(cells[0]).each(table => {
const selectedCells = getSelectedCells(table, cells);
const styleModified = size(filter$1(modifiedData, (_value, key) => key !== 'scope' && key !== 'celltype')) > 0;
const structureModified = has(modifiedData, 'celltype');
if (styleModified || has(modifiedData, 'scope')) {
applyStyleData$1(editor, selectedCells, data);
}
if (structureModified) {
applyStructureData$1(editor, data);
}
fireTableModified(editor, table.dom, {
structure: structureModified,
style: styleModified
});
});
}
};
const onSubmitCellForm = (editor, cells, oldData, api) => {
const data = api.getData();
api.close();
editor.undoManager.transact(() => {
applyCellData(editor, cells, oldData, data);
editor.focus();
});
};
const getData$1 = (editor, cells) => {
const cellsData = table(cells[0]).map(table => map(getSelectedCells(table, cells), item => extractDataFromCellElement(editor, item.element, hasAdvancedCellTab(editor), item.column)));
return getSharedValues(cellsData.getOrDie());
};
const open$2 = editor => {
const cells = getCellsFromSelection(editor);
if (cells.length === 0) {
return;
}
const data = getData$1(editor, cells);
const dialogTabPanel = {
type: 'tabpanel',
tabs: [
{
title: 'General',
name: 'general',
items: getItems$2(editor)
},
getAdvancedTab(editor, 'cell')
]
};
const dialogPanel = {
type: 'panel',
items: [{
type: 'grid',
columns: 2,
items: getItems$2(editor)
}]
};
editor.windowManager.open({
title: 'Cell Properties',
size: 'normal',
body: hasAdvancedCellTab(editor) ? dialogTabPanel : dialogPanel,
buttons: [
{
type: 'cancel',
name: 'cancel',
text: 'Cancel'
},
{
type: 'submit',
name: 'save',
text: 'Save',
primary: true
}
],
initialData: data,
onSubmit: curry(onSubmitCellForm, editor, cells, data)
});
};
const getClassList = editor => {
const classes = buildListItems(getRowClassList(editor));
if (classes.length > 0) {
return Optional.some({
name: 'class',
type: 'listbox',
label: 'Class',
items: classes
});
}
return Optional.none();
};
const formChildren = [
{
type: 'listbox',
name: 'type',
label: 'Row type',
items: [
{
text: 'Header',
value: 'header'
},
{
text: 'Body',
value: 'body'
},
{
text: 'Footer',
value: 'footer'
}
]
},
{
type: 'listbox',
name: 'align',
label: 'Alignment',
items: [
{
text: 'None',
value: ''
},
{
text: 'Left',
value: 'left'
},
{
text: 'Center',
value: 'center'
},
{
text: 'Right',
value: 'right'
}
]
},
{
label: 'Height',
name: 'height',
type: 'input'
}
];
const getItems$1 = editor => formChildren.concat(getClassList(editor).toArray());
const updateSimpleProps = (modifier, data) => {
modifier.setAttrib('class', data.class);
modifier.setStyle('height', addPxSuffix(data.height));
};
const updateAdvancedProps = (modifier, data) => {
modifier.setStyle('background-color', data.backgroundcolor);
modifier.setStyle('border-color', data.bordercolor);
modifier.setStyle('border-style', data.borderstyle);
};
const applyStyleData = (editor, rows, data, oldData) => {
const isSingleRow = rows.length === 1;
each(rows, rowElm => {
const modifier = isSingleRow ? DomModifier.normal(editor, rowElm) : DomModifier.ifTruthy(editor, rowElm);
updateSimpleProps(modifier, data);
if (hasAdvancedRowTab(editor)) {
updateAdvancedProps(modifier, data);
}
if (data.align !== oldData.align) {
unApplyAlign(editor, rowElm);
applyAlign(editor, rowElm, data.align);
}
});
};
const applyStructureData = (editor, data) => {
editor.execCommand('mceTableRowType', false, {
type: data.type,
no_events: true
});
};
const applyRowData = (editor, rows, oldData, data) => {
const modifiedData = filter$1(data, (value, key) => oldData[key] !== value);
if (size(modifiedData) > 0) {
const typeModified = has(modifiedData, 'type');
const styleModified = typeModified ? size(modifiedData) > 1 : true;
if (styleModified) {
applyStyleData(editor, rows, data, oldData);
}
if (typeModified) {
applyStructureData(editor, data);
}
table(SugarElement.fromDom(rows[0])).each(table => fireTableModified(editor, table.dom, {
structure: typeModified,
style: styleModified
}));
}
};
const onSubmitRowForm = (editor, rows, oldData, api) => {
const data = api.getData();
api.close();
editor.undoManager.transact(() => {
applyRowData(editor, rows, oldData, data);
editor.focus();
});
};
const open$1 = editor => {
const rows = getRowsFromSelection(getSelectionStart(editor), ephemera.selected);
if (rows.length === 0) {
return;
}
const rowsData = map(rows, rowElm => extractDataFromRowElement(editor, rowElm.dom, hasAdvancedRowTab(editor)));
const data = getSharedValues(rowsData);
const dialogTabPanel = {
type: 'tabpanel',
tabs: [
{
title: 'General',
name: 'general',
items: getItems$1(editor)
},
getAdvancedTab(editor, 'row')
]
};
const dialogPanel = {
type: 'panel',
items: [{
type: 'grid',
columns: 2,
items: getItems$1(editor)
}]
};
editor.windowManager.open({
title: 'Row Properties',
size: 'normal',
body: hasAdvancedRowTab(editor) ? dialogTabPanel : dialogPanel,
buttons: [
{
type: 'cancel',
name: 'cancel',
text: 'Cancel'
},
{
type: 'submit',
name: 'save',
text: 'Save',
primary: true
}
],
initialData: data,
onSubmit: curry(onSubmitRowForm, editor, map(rows, r => r.dom), data)
});
};
const getItems = (editor, classes, insertNewTable) => {
const rowColCountItems = !insertNewTable ? [] : [
{
type: 'input',
name: 'cols',
label: 'Cols',
inputMode: 'numeric'
},
{
type: 'input',
name: 'rows',
label: 'Rows',
inputMode: 'numeric'
}
];
const alwaysItems = [
{
type: 'input',
name: 'width',
label: 'Width'
},
{
type: 'input',
name: 'height',
label: 'Height'
}
];
const appearanceItems = hasAppearanceOptions(editor) ? [
{
type: 'input',
name: 'cellspacing',
label: 'Cell spacing',
inputMode: 'numeric'
},
{
type: 'input',
name: 'cellpadding',
label: 'Cell padding',
inputMode: 'numeric'
},
{
type: 'input',
name: 'border',
label: 'Border width'
},
{
type: 'label',
label: 'Caption',
items: [{
type: 'checkbox',
name: 'caption',
label: 'Show caption'
}]
}
] : [];
const alignmentItem = [{
type: 'listbox',
name: 'align',
label: 'Alignment',
items: [
{
text: 'None',
value: ''
},
{
text: 'Left',
value: 'left'
},
{
text: 'Center',
value: 'center'
},
{
text: 'Right',
value: 'right'
}
]
}];
const classListItem = classes.length > 0 ? [{
type: 'listbox',
name: 'class',
label: 'Class',
items: classes
}] : [];
return rowColCountItems.concat(alwaysItems).concat(appearanceItems).concat(alignmentItem).concat(classListItem);
};
const styleTDTH = (dom, elm, name, value) => {
if (elm.tagName === 'TD' || elm.tagName === 'TH') {
if (isString(name)) {
dom.setStyle(elm, name, value);
} else {
dom.setStyles(elm, name);
}
} else {
if (elm.children) {
for (let i = 0; i < elm.children.length; i++) {
styleTDTH(dom, elm.children[i], name, value);
}
}
}
};
const applyDataToElement = (editor, tableElm, data) => {
const dom = editor.dom;
const attrs = {};
const styles = {};
attrs.class = data.class;
styles.height = addPxSuffix(data.height);
if (dom.getAttrib(tableElm, 'width') && !shouldStyleWithCss(editor)) {
attrs.width = removePxSuffix(data.width);
} else {
styles.width = addPxSuffix(data.width);
}
if (shouldStyleWithCss(editor)) {
styles['border-width'] = addPxSuffix(data.border);
styles['border-spacing'] = addPxSuffix(data.cellspacing);
} else {
attrs.border = data.border;
attrs.cellpadding = data.cellpadding;
attrs.cellspacing = data.cellspacing;
}
if (shouldStyleWithCss(editor) && tableElm.children) {
for (let i = 0; i < tableElm.children.length; i++) {
styleTDTH(dom, tableElm.children[i], {
'border-width': addPxSuffix(data.border),
'padding': addPxSuffix(data.cellpadding)
});
if (hasAdvancedTableTab(editor)) {
styleTDTH(dom, tableElm.children[i], { 'border-color': data.bordercolor });
}
}
}
if (hasAdvancedTableTab(editor)) {
styles['background-color'] = data.backgroundcolor;
styles['border-color'] = data.bordercolor;
styles['border-style'] = data.borderstyle;
}
attrs.style = dom.serializeStyle({
...getDefaultStyles(editor),
...styles
});
dom.setAttribs(tableElm, {
...getDefaultAttributes(editor),
...attrs
});
};
const onSubmitTableForm = (editor, tableElm, oldData, api) => {
const dom = editor.dom;
const data = api.getData();
const modifiedData = filter$1(data, (value, key) => oldData[key] !== value);
api.close();
if (data.class === '') {
delete data.class;
}
editor.undoManager.transact(() => {
if (!tableElm) {
const cols = parseInt(data.cols, 10) || 1;
const rows = parseInt(data.rows, 10) || 1;
editor.execCommand('mceInsertTable', false, {
rows,
columns: cols
});
tableElm = getSelectionCell(getSelectionStart(editor), getIsRoot(editor)).bind(cell => table(cell, getIsRoot(editor))).map(table => table.dom).getOrUndefined();
}
if (size(modifiedData) > 0) {
applyDataToElement(editor, tableElm, data);
const captionElm = dom.select('caption', tableElm)[0];
if (captionElm && !data.caption || !captionElm && data.caption) {
editor.execCommand('mceTableToggleCaption');
}
if (data.align === '') {
unApplyAlign(editor, tableElm);
} else {
applyAlign(editor, tableElm, data.align);
}
}
editor.focus();
editor.addVisual();
if (size(modifiedData) > 0) {
const captionModified = has(modifiedData, 'caption');
const styleModified = captionModified ? size(modifiedData) > 1 : true;
fireTableModified(editor, tableElm, {
structure: captionModified,
style: styleModified
});
}
});
};
const open = (editor, insertNewTable) => {
const dom = editor.dom;
let tableElm;
let data = extractDataFromSettings(editor, hasAdvancedTableTab(editor));
if (insertNewTable === false) {
tableElm = dom.getParent(editor.selection.getStart(), 'table', editor.getBody());
if (tableElm) {
data = extractDataFromTableElement(editor, tableElm, hasAdvancedTableTab(editor));
} else {
if (hasAdvancedTableTab(editor)) {
data.borderstyle = '';
data.bordercolor = '';
data.backgroundcolor = '';
}
}
} else {
data.cols = '1';
data.rows = '1';
if (hasAdvancedTableTab(editor)) {
data.borderstyle = '';
data.bordercolor = '';
data.backgroundcolor = '';
}
}
const classes = buildListItems(getTableClassList(editor));
if (classes.length > 0) {
if (data.class) {
data.class = data.class.replace(/\s*mce\-item\-table\s*/g, '');
}
}
const generalPanel = {
type: 'grid',
columns: 2,
items: getItems(editor, classes, insertNewTable)
};
const nonAdvancedForm = () => ({
type: 'panel',
items: [generalPanel]
});
const advancedForm = () => ({
type: 'tabpanel',
tabs: [
{
title: 'General',
name: 'general',
items: [generalPanel]
},
getAdvancedTab(editor, 'table')
]
});
const dialogBody = hasAdvancedTableTab(editor) ? advancedForm() : nonAdvancedForm();
editor.windowManager.open({
title: 'Table Properties',
size: 'normal',
body: dialogBody,
onSubmit: curry(onSubmitTableForm, editor, tableElm, data),
buttons: [
{
type: 'cancel',
name: 'cancel',
text: 'Cancel'
},
{
type: 'submit',
name: 'save',
text: 'Save',
primary: true
}
],
initialData: data
});
};
const registerCommands = editor => {
each$1({
mceTableProps: curry(open, editor, false),
mceTableRowProps: curry(open$1, editor),
mceTableCellProps: curry(open$2, editor)
}, (func, name) => editor.addCommand(name, () => func()));
editor.addCommand('mceInsertTableDialog', _ui => {
open(editor, true);
});
};
const child = (scope, selector) => child$1(scope, selector).isSome();
const selection = identity;
const unmergable = selectedCells => {
const hasSpan = (elem, type) => getOpt(elem, type).exists(span => parseInt(span, 10) > 1);
const hasRowOrColSpan = elem => hasSpan(elem, 'rowspan') || hasSpan(elem, 'colspan');
return selectedCells.length > 0 && forall(selectedCells, hasRowOrColSpan) ? Optional.some(selectedCells) : Optional.none();
};
const mergable = (table, selectedCells, ephemera) => {
if (selectedCells.length <= 1) {
return Optional.none();
} else {
return retrieveBox(table, ephemera.firstSelectedSelector, ephemera.lastSelectedSelector).map(bounds => ({
bounds,
cells: selectedCells
}));
}
};
const noMenu = cell => ({
element: cell,
mergable: Optional.none(),
unmergable: Optional.none(),
selection: [cell]
});
const forMenu = (selectedCells, table, cell) => ({
element: cell,
mergable: mergable(table, selectedCells, ephemera),
unmergable: unmergable(selectedCells),
selection: selection(selectedCells)
});
const getSelectionTargets = editor => {
const targets = Cell(Optional.none());
const changeHandlers = Cell([]);
let selectionDetails = Optional.none();
const isCaption = isTag('caption');
const isDisabledForSelection = key => selectionDetails.forall(details => !details[key]);
const getStart = () => getSelectionCellOrCaption(getSelectionStart(editor), getIsRoot(editor));
const getEnd = () => getSelectionCellOrCaption(getSelectionEnd(editor), getIsRoot(editor));
const findTargets = () => getStart().bind(startCellOrCaption => flatten(lift2(table(startCellOrCaption), getEnd().bind(table), (startTable, endTable) => {
if (eq(startTable, endTable)) {
if (isCaption(startCellOrCaption)) {
return Optional.some(noMenu(startCellOrCaption));
} else {
return Optional.some(forMenu(getCellsFromSelection(editor), startTable, startCellOrCaption));
}
}
return Optional.none();
})));
const getExtractedDetails = targets => {
const tableOpt = table(targets.element);
return tableOpt.map(table => {
const warehouse = Warehouse.fromTable(table);
const selectedCells = onCells(warehouse, targets).getOr([]);
const locked = foldl(selectedCells, (acc, cell) => {
if (cell.isLocked) {
acc.onAny = true;
if (cell.column === 0) {
acc.onFirst = true;
} else if (cell.column + cell.colspan >= warehouse.grid.columns) {
acc.onLast = true;
}
}
return acc;
}, {
onAny: false,
onFirst: false,
onLast: false
});
return {
mergeable: onUnlockedMergable(warehouse, targets).isSome(),
unmergeable: onUnlockedUnmergable(warehouse, targets).isSome(),
locked
};
});
};
const resetTargets = () => {
targets.set(cached(findTargets)());
selectionDetails = targets.get().bind(getExtractedDetails);
each(changeHandlers.get(), handler => handler());
};
const setupHandler = handler => {
handler();
changeHandlers.set(changeHandlers.get().concat([handler]));
return () => {
changeHandlers.set(filter(changeHandlers.get(), h => h !== handler));
};
};
const onSetup = (api, isDisabled) => setupHandler(() => targets.get().fold(() => {
api.setEnabled(false);
}, targets => {
api.setEnabled(!isDisabled(targets));
}));
const onSetupWithToggle = (api, isDisabled, isActive) => setupHandler(() => targets.get().fold(() => {
api.setEnabled(false);
api.setActive(false);
}, targets => {
api.setEnabled(!isDisabled(targets));
api.setActive(isActive(targets));
}));
const isDisabledFromLocked = lockedDisable => selectionDetails.exists(details => details.locked[lockedDisable]);
const onSetupTable = api => onSetup(api, _ => false);
const onSetupCellOrRow = api => onSetup(api, targets => isCaption(targets.element));
const onSetupColumn = lockedDisable => api => onSetup(api, targets => isCaption(targets.element) || isDisabledFromLocked(lockedDisable));
const onSetupPasteable = getClipboardData => api => onSetup(api, targets => isCaption(targets.element) || getClipboardData().isNone());
const onSetupPasteableColumn = (getClipboardData, lockedDisable) => api => onSetup(api, targets => isCaption(targets.element) || getClipboardData().isNone() || isDisabledFromLocked(lockedDisable));
const onSetupMergeable = api => onSetup(api, _targets => isDisabledForSelection('mergeable'));
const onSetupUnmergeable = api => onSetup(api, _targets => isDisabledForSelection('unmergeable'));
const onSetupTableWithCaption = api => {
return onSetupWithToggle(api, never, targets => {
const tableOpt = table(targets.element, getIsRoot(editor));
return tableOpt.exists(table => child(table, 'caption'));
});
};
const onSetupTableHeaders = (command, headerType) => api => {
return onSetupWithToggle(api, targets => isCaption(targets.element), () => editor.queryCommandValue(command) === headerType);
};
const onSetupTableRowHeaders = onSetupTableHeaders('mceTableRowType', 'header');
const onSetupTableColumnHeaders = onSetupTableHeaders('mceTableColType', 'th');
editor.on('NodeChange ExecCommand TableSelectorChange', resetTargets);
return {
onSetupTable,
onSetupCellOrRow,
onSetupColumn,
onSetupPasteable,
onSetupPasteableColumn,
onSetupMergeable,
onSetupUnmergeable,
resetTargets,
onSetupTableWithCaption,
onSetupTableRowHeaders,
onSetupTableColumnHeaders,
targets: targets.get
};
};
var global = tinymce.util.Tools.resolve('tinymce.FakeClipboard');
const tableTypeBase = 'x-tinymce/dom-table-';
const tableTypeRow = tableTypeBase + 'rows';
const tableTypeColumn = tableTypeBase + 'columns';
const getData = type => {
var _a;
const items = (_a = global.read()) !== null && _a !== void 0 ? _a : [];
return findMap(items, item => Optional.from(item.getType(type)));
};
const getRows = () => getData(tableTypeRow);
const getColumns = () => getData(tableTypeColumn);
const addButtons = (editor, selectionTargets) => {
editor.ui.registry.addMenuButton('table', {
tooltip: 'Table',
icon: 'table',
fetch: callback => callback('inserttable | cell row column | advtablesort | tableprops deletetable')
});
const cmd = command => () => editor.execCommand(command);
const addButtonIfRegistered = (name, spec) => {
if (editor.queryCommandSupported(spec.command)) {
editor.ui.registry.addButton(name, {
...spec,
onAction: isFunction(spec.onAction) ? spec.onAction : cmd(spec.command)
});
}
};
const addToggleButtonIfRegistered = (name, spec) => {
if (editor.queryCommandSupported(spec.command)) {
editor.ui.registry.addToggleButton(name, {
...spec,
onAction: isFunction(spec.onAction) ? spec.onAction : cmd(spec.command)
});
}
};
addButtonIfRegistered('tableprops', {
tooltip: 'Table properties',
command: 'mceTableProps',
icon: 'table',
onSetup: selectionTargets.onSetupTable
});
addButtonIfRegistered('tabledelete', {
tooltip: 'Delete table',
command: 'mceTableDelete',
icon: 'table-delete-table',
onSetup: selectionTargets.onSetupTable
});
addButtonIfRegistered('tablecellprops', {
tooltip: 'Cell properties',
command: 'mceTableCellProps',
icon: 'table-cell-properties',
onSetup: selectionTargets.onSetupCellOrRow
});
addButtonIfRegistered('tablemergecells', {
tooltip: 'Merge cells',
command: 'mceTableMergeCells',
icon: 'table-merge-cells',
onSetup: selectionTargets.onSetupMergeable
});
addButtonIfRegistered('tablesplitcells', {
tooltip: 'Split cell',
command: 'mceTableSplitCells',
icon: 'table-split-cells',
onSetup: selectionTargets.onSetupUnmergeable
});
addButtonIfRegistered('tableinsertrowbefore', {
tooltip: 'Insert row before',
command: 'mceTableInsertRowBefore',
icon: 'table-insert-row-above',
onSetup: selectionTargets.onSetupCellOrRow
});
addButtonIfRegistered('tableinsertrowafter', {
tooltip: 'Insert row after',
command: 'mceTableInsertRowAfter',
icon: 'table-insert-row-after',
onSetup: selectionTargets.onSetupCellOrRow
});
addButtonIfRegistered('tabledeleterow', {
tooltip: 'Delete row',
command: 'mceTableDeleteRow',
icon: 'table-delete-row',
onSetup: selectionTargets.onSetupCellOrRow
});
addButtonIfRegistered('tablerowprops', {
tooltip: 'Row properties',
command: 'mceTableRowProps',
icon: 'table-row-properties',
onSetup: selectionTargets.onSetupCellOrRow
});
addButtonIfRegistered('tableinsertcolbefore', {
tooltip: 'Insert column before',
command: 'mceTableInsertColBefore',
icon: 'table-insert-column-before',
onSetup: selectionTargets.onSetupColumn('onFirst')
});
addButtonIfRegistered('tableinsertcolafter', {
tooltip: 'Insert column after',
command: 'mceTableInsertColAfter',
icon: 'table-insert-column-after',
onSetup: selectionTargets.onSetupColumn('onLast')
});
addButtonIfRegistered('tabledeletecol', {
tooltip: 'Delete column',
command: 'mceTableDeleteCol',
icon: 'table-delete-column',
onSetup: selectionTargets.onSetupColumn('onAny')
});
addButtonIfRegistered('tablecutrow', {
tooltip: 'Cut row',
command: 'mceTableCutRow',
icon: 'cut-row',
onSetup: selectionTargets.onSetupCellOrRow
});
addButtonIfRegistered('tablecopyrow', {
tooltip: 'Copy row',
command: 'mceTableCopyRow',
icon: 'duplicate-row',
onSetup: selectionTargets.onSetupCellOrRow
});
addButtonIfRegistered('tablepasterowbefore', {
tooltip: 'Paste row before',
command: 'mceTablePasteRowBefore',
icon: 'paste-row-before',
onSetup: selectionTargets.onSetupPasteable(getRows)
});
addButtonIfRegistered('tablepasterowafter', {
tooltip: 'Paste row after',
command: 'mceTablePasteRowAfter',
icon: 'paste-row-after',
onSetup: selectionTargets.onSetupPasteable(getRows)
});
addButtonIfRegistered('tablecutcol', {
tooltip: 'Cut column',
command: 'mceTableCutCol',
icon: 'cut-column',
onSetup: selectionTargets.onSetupColumn('onAny')
});
addButtonIfRegistered('tablecopycol', {
tooltip: 'Copy column',
command: 'mceTableCopyCol',
icon: 'duplicate-column',
onSetup: selectionTargets.onSetupColumn('onAny')
});
addButtonIfRegistered('tablepastecolbefore', {
tooltip: 'Paste column before',
command: 'mceTablePasteColBefore',
icon: 'paste-column-before',
onSetup: selectionTargets.onSetupPasteableColumn(getColumns, 'onFirst')
});
addButtonIfRegistered('tablepastecolafter', {
tooltip: 'Paste column after',
command: 'mceTablePasteColAfter',
icon: 'paste-column-after',
onSetup: selectionTargets.onSetupPasteableColumn(getColumns, 'onLast')
});
addButtonIfRegistered('tableinsertdialog', {
tooltip: 'Insert table',
command: 'mceInsertTableDialog',
icon: 'table'
});
const tableClassList = filterNoneItem(getTableClassList(editor));
if (tableClassList.length !== 0 && editor.queryCommandSupported('mceTableToggleClass')) {
editor.ui.registry.addMenuButton('tableclass', {
icon: 'table-classes',
tooltip: 'Table styles',
fetch: generateMenuItemsCallback(editor, tableClassList, 'tableclass', value => editor.execCommand('mceTableToggleClass', false, value)),
onSetup: selectionTargets.onSetupTable
});
}
const tableCellClassList = filterNoneItem(getCellClassList(editor));
if (tableCellClassList.length !== 0 && editor.queryCommandSupported('mceTableCellToggleClass')) {
editor.ui.registry.addMenuButton('tablecellclass', {
icon: 'table-cell-classes',
tooltip: 'Cell styles',
fetch: generateMenuItemsCallback(editor, tableCellClassList, 'tablecellclass', value => editor.execCommand('mceTableCellToggleClass', false, value)),
onSetup: selectionTargets.onSetupCellOrRow
});
}
if (editor.queryCommandSupported('mceTableApplyCellStyle')) {
editor.ui.registry.addMenuButton('tablecellvalign', {
icon: 'vertical-align',
tooltip: 'Vertical align',
fetch: generateMenuItemsCallback(editor, verticalAlignValues, 'tablecellverticalalign', applyTableCellStyle(editor, 'vertical-align')),
onSetup: selectionTargets.onSetupCellOrRow
});
editor.ui.registry.addMenuButton('tablecellborderwidth', {
icon: 'border-width',
tooltip: 'Border width',
fetch: generateMenuItemsCallback(editor, getTableBorderWidths(editor), 'tablecellborderwidth', applyTableCellStyle(editor, 'border-width')),
onSetup: selectionTargets.onSetupCellOrRow
});
editor.ui.registry.addMenuButton('tablecellborderstyle', {
icon: 'border-style',
tooltip: 'Border style',
fetch: generateMenuItemsCallback(editor, getTableBorderStyles(editor), 'tablecellborderstyle', applyTableCellStyle(editor, 'border-style')),
onSetup: selectionTargets.onSetupCellOrRow
});
editor.ui.registry.addMenuButton('tablecellbackgroundcolor', {
icon: 'cell-background-color',
tooltip: 'Background color',
fetch: callback => callback(buildColorMenu(editor, getTableBackgroundColorMap(editor), 'background-color')),
onSetup: selectionTargets.onSetupCellOrRow
});
editor.ui.registry.addMenuButton('tablecellbordercolor', {
icon: 'cell-border-color',
tooltip: 'Border color',
fetch: callback => callback(buildColorMenu(editor, getTableBorderColorMap(editor), 'border-color')),
onSetup: selectionTargets.onSetupCellOrRow
});
}
addToggleButtonIfRegistered('tablecaption', {
tooltip: 'Table caption',
icon: 'table-caption',
command: 'mceTableToggleCaption',
onSetup: selectionTargets.onSetupTableWithCaption
});
addToggleButtonIfRegistered('tablerowheader', {
tooltip: 'Row header',
icon: 'table-top-header',
command: 'mceTableRowType',
onAction: changeRowHeader(editor),
onSetup: selectionTargets.onSetupTableRowHeaders
});
addToggleButtonIfRegistered('tablecolheader', {
tooltip: 'Column header',
icon: 'table-left-header',
command: 'mceTableColType',
onAction: changeColumnHeader(editor),
onSetup: selectionTargets.onSetupTableColumnHeaders
});
};
const addToolbars = editor => {
const isTable = table => editor.dom.is(table, 'table') && editor.getBody().contains(table);
const toolbar = getToolbar(editor);
if (toolbar.length > 0) {
editor.ui.registry.addContextToolbar('table', {
predicate: isTable,
items: toolbar,
scope: 'node',
position: 'node'
});
}
};
const addMenuItems = (editor, selectionTargets) => {
const cmd = command => () => editor.execCommand(command);
const addMenuIfRegistered = (name, spec) => {
if (editor.queryCommandSupported(spec.command)) {
editor.ui.registry.addMenuItem(name, {
...spec,
onAction: isFunction(spec.onAction) ? spec.onAction : cmd(spec.command)
});
return true;
} else {
return false;
}
};
const addToggleMenuIfRegistered = (name, spec) => {
if (editor.queryCommandSupported(spec.command)) {
editor.ui.registry.addToggleMenuItem(name, {
...spec,
onAction: isFunction(spec.onAction) ? spec.onAction : cmd(spec.command)
});
}
};
const insertTableAction = data => {
editor.execCommand('mceInsertTable', false, {
rows: data.numRows,
columns: data.numColumns
});
};
const hasRowMenuItems = [
addMenuIfRegistered('tableinsertrowbefore', {
text: 'Insert row before',
icon: 'table-insert-row-above',
command: 'mceTableInsertRowBefore',
onSetup: selectionTargets.onSetupCellOrRow
}),
addMenuIfRegistered('tableinsertrowafter', {
text: 'Insert row after',
icon: 'table-insert-row-after',
command: 'mceTableInsertRowAfter',
onSetup: selectionTargets.onSetupCellOrRow
}),
addMenuIfRegistered('tabledeleterow', {
text: 'Delete row',
icon: 'table-delete-row',
command: 'mceTableDeleteRow',
onSetup: selectionTargets.onSetupCellOrRow
}),
addMenuIfRegistered('tablerowprops', {
text: 'Row properties',
icon: 'table-row-properties',
command: 'mceTableRowProps',
onSetup: selectionTargets.onSetupCellOrRow
}),
addMenuIfRegistered('tablecutrow', {
text: 'Cut row',
icon: 'cut-row',
command: 'mceTableCutRow',
onSetup: selectionTargets.onSetupCellOrRow
}),
addMenuIfRegistered('tablecopyrow', {
text: 'Copy row',
icon: 'duplicate-row',
command: 'mceTableCopyRow',
onSetup: selectionTargets.onSetupCellOrRow
}),
addMenuIfRegistered('tablepasterowbefore', {
text: 'Paste row before',
icon: 'paste-row-before',
command: 'mceTablePasteRowBefore',
onSetup: selectionTargets.onSetupPasteable(getRows)
}),
addMenuIfRegistered('tablepasterowafter', {
text: 'Paste row after',
icon: 'paste-row-after',
command: 'mceTablePasteRowAfter',
onSetup: selectionTargets.onSetupPasteable(getRows)
})
];
const hasColumnMenuItems = [
addMenuIfRegistered('tableinsertcolumnbefore', {
text: 'Insert column before',
icon: 'table-insert-column-before',
command: 'mceTableInsertColBefore',
onSetup: selectionTargets.onSetupColumn('onFirst')
}),
addMenuIfRegistered('tableinsertcolumnafter', {
text: 'Insert column after',
icon: 'table-insert-column-after',
command: 'mceTableInsertColAfter',
onSetup: selectionTargets.onSetupColumn('onLast')
}),
addMenuIfRegistered('tabledeletecolumn', {
text: 'Delete column',
icon: 'table-delete-column',
command: 'mceTableDeleteCol',
onSetup: selectionTargets.onSetupColumn('onAny')
}),
addMenuIfRegistered('tablecutcolumn', {
text: 'Cut column',
icon: 'cut-column',
command: 'mceTableCutCol',
onSetup: selectionTargets.onSetupColumn('onAny')
}),
addMenuIfRegistered('tablecopycolumn', {
text: 'Copy column',
icon: 'duplicate-column',
command: 'mceTableCopyCol',
onSetup: selectionTargets.onSetupColumn('onAny')
}),
addMenuIfRegistered('tablepastecolumnbefore', {
text: 'Paste column before',
icon: 'paste-column-before',
command: 'mceTablePasteColBefore',
onSetup: selectionTargets.onSetupPasteableColumn(getColumns, 'onFirst')
}),
addMenuIfRegistered('tablepastecolumnafter', {
text: 'Paste column after',
icon: 'paste-column-after',
command: 'mceTablePasteColAfter',
onSetup: selectionTargets.onSetupPasteableColumn(getColumns, 'onLast')
})
];
const hasCellMenuItems = [
addMenuIfRegistered('tablecellprops', {
text: 'Cell properties',
icon: 'table-cell-properties',
command: 'mceTableCellProps',
onSetup: selectionTargets.onSetupCellOrRow
}),
addMenuIfRegistered('tablemergecells', {
text: 'Merge cells',
icon: 'table-merge-cells',
command: 'mceTableMergeCells',
onSetup: selectionTargets.onSetupMergeable
}),
addMenuIfRegistered('tablesplitcells', {
text: 'Split cell',
icon: 'table-split-cells',
command: 'mceTableSplitCells',
onSetup: selectionTargets.onSetupUnmergeable
})
];
if (!hasTableGrid(editor)) {
editor.ui.registry.addMenuItem('inserttable', {
text: 'Table',
icon: 'table',
onAction: cmd('mceInsertTableDialog')
});
} else {
editor.ui.registry.addNestedMenuItem('inserttable', {
text: 'Table',
icon: 'table',
getSubmenuItems: () => [{
type: 'fancymenuitem',
fancytype: 'inserttable',
onAction: insertTableAction
}]
});
}
editor.ui.registry.addMenuItem('inserttabledialog', {
text: 'Insert table',
icon: 'table',
onAction: cmd('mceInsertTableDialog')
});
addMenuIfRegistered('tableprops', {
text: 'Table properties',
onSetup: selectionTargets.onSetupTable,
command: 'mceTableProps'
});
addMenuIfRegistered('deletetable', {
text: 'Delete table',
icon: 'table-delete-table',
onSetup: selectionTargets.onSetupTable,
command: 'mceTableDelete'
});
if (contains(hasRowMenuItems, true)) {
editor.ui.registry.addNestedMenuItem('row', {
type: 'nestedmenuitem',
text: 'Row',
getSubmenuItems: constant('tableinsertrowbefore tableinsertrowafter tabledeleterow tablerowprops | tablecutrow tablecopyrow tablepasterowbefore tablepasterowafter')
});
}
if (contains(hasColumnMenuItems, true)) {
editor.ui.registry.addNestedMenuItem('column', {
type: 'nestedmenuitem',
text: 'Column',
getSubmenuItems: constant('tableinsertcolumnbefore tableinsertcolumnafter tabledeletecolumn | tablecutcolumn tablecopycolumn tablepastecolumnbefore tablepastecolumnafter')
});
}
if (contains(hasCellMenuItems, true)) {
editor.ui.registry.addNestedMenuItem('cell', {
type: 'nestedmenuitem',
text: 'Cell',
getSubmenuItems: constant('tablecellprops tablemergecells tablesplitcells')
});
}
editor.ui.registry.addContextMenu('table', {
update: () => {
selectionTargets.resetTargets();
return selectionTargets.targets().fold(constant(''), targets => {
if (name(targets.element) === 'caption') {
return 'tableprops deletetable';
} else {
return 'cell row column | advtablesort | tableprops deletetable';
}
});
}
});
const tableClassList = filterNoneItem(getTableClassList(editor));
if (tableClassList.length !== 0 && editor.queryCommandSupported('mceTableToggleClass')) {
editor.ui.registry.addNestedMenuItem('tableclass', {
icon: 'table-classes',
text: 'Table styles',
getSubmenuItems: () => buildMenuItems(editor, tableClassList, 'tableclass', value => editor.execCommand('mceTableToggleClass', false, value)),
onSetup: selectionTargets.onSetupTable
});
}
const tableCellClassList = filterNoneItem(getCellClassList(editor));
if (tableCellClassList.length !== 0 && editor.queryCommandSupported('mceTableCellToggleClass')) {
editor.ui.registry.addNestedMenuItem('tablecellclass', {
icon: 'table-cell-classes',
text: 'Cell styles',
getSubmenuItems: () => buildMenuItems(editor, tableCellClassList, 'tablecellclass', value => editor.execCommand('mceTableCellToggleClass', false, value)),
onSetup: selectionTargets.onSetupCellOrRow
});
}
if (editor.queryCommandSupported('mceTableApplyCellStyle')) {
editor.ui.registry.addNestedMenuItem('tablecellvalign', {
icon: 'vertical-align',
text: 'Vertical align',
getSubmenuItems: () => buildMenuItems(editor, verticalAlignValues, 'tablecellverticalalign', applyTableCellStyle(editor, 'vertical-align')),
onSetup: selectionTargets.onSetupCellOrRow
});
editor.ui.registry.addNestedMenuItem('tablecellborderwidth', {
icon: 'border-width',
text: 'Border width',
getSubmenuItems: () => buildMenuItems(editor, getTableBorderWidths(editor), 'tablecellborderwidth', applyTableCellStyle(editor, 'border-width')),
onSetup: selectionTargets.onSetupCellOrRow
});
editor.ui.registry.addNestedMenuItem('tablecellborderstyle', {
icon: 'border-style',
text: 'Border style',
getSubmenuItems: () => buildMenuItems(editor, getTableBorderStyles(editor), 'tablecellborderstyle', applyTableCellStyle(editor, 'border-style')),
onSetup: selectionTargets.onSetupCellOrRow
});
editor.ui.registry.addNestedMenuItem('tablecellbackgroundcolor', {
icon: 'cell-background-color',
text: 'Background color',
getSubmenuItems: () => buildColorMenu(editor, getTableBackgroundColorMap(editor), 'background-color'),
onSetup: selectionTargets.onSetupCellOrRow
});
editor.ui.registry.addNestedMenuItem('tablecellbordercolor', {
icon: 'cell-border-color',
text: 'Border color',
getSubmenuItems: () => buildColorMenu(editor, getTableBorderColorMap(editor), 'border-color'),
onSetup: selectionTargets.onSetupCellOrRow
});
}
addToggleMenuIfRegistered('tablecaption', {
icon: 'table-caption',
text: 'Table caption',
command: 'mceTableToggleCaption',
onSetup: selectionTargets.onSetupTableWithCaption
});
addToggleMenuIfRegistered('tablerowheader', {
text: 'Row header',
icon: 'table-top-header',
command: 'mceTableRowType',
onAction: changeRowHeader(editor),
onSetup: selectionTargets.onSetupTableRowHeaders
});
addToggleMenuIfRegistered('tablecolheader', {
text: 'Column header',
icon: 'table-left-header',
command: 'mceTableColType',
onAction: changeColumnHeader(editor),
onSetup: selectionTargets.onSetupTableRowHeaders
});
};
const Plugin = editor => {
const selectionTargets = getSelectionTargets(editor);
register(editor);
registerCommands(editor);
addMenuItems(editor, selectionTargets);
addButtons(editor, selectionTargets);
addToolbars(editor);
};
var Plugin$1 = () => {
global$3.add('table', Plugin);
};
Plugin$1();
})();
|
(function(){
jQuery.support = {};
var root = document.documentElement,
script = document.createElement("script"),
div = document.createElement("div"),
id = "script" + (new Date).getTime();
div.style.display = "none";
div.innerHTML = ' <link/><table></table><a href="/a" style="color:red;float:left;opacity:.5;">a</a><select><option>text</option></select><object><param/></object>';
var all = div.getElementsByTagName("*"),
a = div.getElementsByTagName("a")[0];
// Can't get basic test support
if ( !all || !all.length || !a ) {
return;
}
jQuery.support = {
// IE strips leading whitespace when .innerHTML is used
leadingWhitespace: div.firstChild.nodeType == 3,
// Make sure that tbody elements aren't automatically inserted
// IE will insert them into empty tables
tbody: !div.getElementsByTagName("tbody").length,
// Make sure that you can get all elements in an <object> element
// IE 7 always returns no results
objectAll: !!div.getElementsByTagName("object")[0]
.getElementsByTagName("*").length,
// Make sure that link elements get serialized correctly by innerHTML
// This requires a wrapper element in IE
htmlSerialize: !!div.getElementsByTagName("link").length,
// Get the style information from getAttribute
// (IE uses .cssText insted)
style: /red/.test( a.getAttribute("style") ),
// Make sure that URLs aren't manipulated
// (IE normalizes it by default)
hrefNormalized: a.getAttribute("href") === "/a",
// Make sure that element opacity exists
// (IE uses filter instead)
opacity: a.style.opacity === "0.5",
// Verify style float existence
// (IE uses styleFloat instead of cssFloat)
cssFloat: !!a.style.cssFloat,
// Will be defined later
scriptEval: false,
noCloneEvent: true,
boxModel: null
};
script.type = "text/javascript";
try {
script.appendChild( document.createTextNode( "window." + id + "=1;" ) );
} catch(e){}
root.insertBefore( script, root.firstChild );
// Make sure that the execution of code works by injecting a script
// tag with appendChild/createTextNode
// (IE doesn't support this, fails, and uses .text instead)
if ( window[ id ] ) {
jQuery.support.scriptEval = true;
delete window[ id ];
}
root.removeChild( script );
if ( div.attachEvent && div.fireEvent ) {
div.attachEvent("onclick", function(){
// Cloning a node shouldn't copy over any
// bound event handlers (IE does this)
jQuery.support.noCloneEvent = false;
div.detachEvent("onclick", arguments.callee);
});
div.cloneNode(true).fireEvent("onclick");
}
// Figure out if the W3C box model works as expected
// document.body must exist before we can do this
jQuery(function(){
var div = document.createElement("div");
div.style.width = div.style.paddingLeft = "1px";
document.body.appendChild( div );
jQuery.boxModel = jQuery.support.boxModel = div.offsetWidth === 2;
document.body.removeChild( div ).style.display = 'none';
});
})();
var styleFloat = jQuery.support.cssFloat ? "cssFloat" : "styleFloat";
jQuery.props = {
"for": "htmlFor",
"class": "className",
"float": styleFloat,
cssFloat: styleFloat,
styleFloat: styleFloat,
readonly: "readOnly",
maxlength: "maxLength",
cellspacing: "cellSpacing",
rowspan: "rowSpan",
tabindex: "tabIndex"
};
|
const PARTS = [{
name: 'milliseconds',
div: 1000,
}, {
name: 'seconds',
div: 60,
}, {
name: 'minutes',
div: 60,
}, {
name: 'hours',
div: 24,
}, {
name: 'days',
div: 365,
}]
export default class TimeDelta {
constructor(data) {
if (isNaN(data)) {
this.setByObject(data);
} else {
this.setByNumber(data);
}
}
addDelta(num) {
this.setByNumber(this.getNumber() + num);
}
setByObject(data) {
if (typeof data != 'object')
throw new Error('Unknown data!');
PARTS.forEach((part) => {
this[part.name] = part.name in data ? data[part.name] : 0;
})
}
setByNumber(num) {
let prevDiv = 1;
PARTS.forEach((part) => {
num /= prevDiv;
this[part.name] = parseInt(num) % part.div;
prevDiv = part.div;
});
}
getNumber(data) {
let res = 0;
let prevDiv = 1;
PARTS.forEach((part) => {
res += this[part.name] * prevDiv;
prevDiv *= part.div;
})
return res;
}
}
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.ModalRootDesktop = void 0;
var _jsxRuntime = require("../../lib/jsxRuntime");
var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));
var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
var _assertThisInitialized2 = _interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized"));
var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));
var _createSuper2 = _interopRequireDefault(require("@babel/runtime/helpers/createSuper"));
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var React = _interopRequireWildcard(require("react"));
var _classNames = require("../../lib/classNames");
var _utils = require("../../lib/utils");
var _supportEvents = require("../../lib/supportEvents");
var _withPlatform = require("../../hoc/withPlatform");
var _withContext = require("../../hoc/withContext");
var _ModalRootContext = _interopRequireDefault(require("./ModalRootContext"));
var _ConfigProviderContext = require("../ConfigProvider/ConfigProviderContext");
var _types = require("./types");
var _platform = require("../../lib/platform");
var _getClassName = require("../../helpers/getClassName");
var _dom = require("../../lib/dom");
var _getNavId = require("../../lib/getNavId");
var _warnOnce = require("../../lib/warnOnce");
var _excluded = ["id"];
var warn = (0, _warnOnce.warnOnce)('ModalRoot');
var IS_DEV = process.env.NODE_ENV === 'development';
var ModalRootDesktopComponent = /*#__PURE__*/function (_React$Component) {
(0, _inherits2.default)(ModalRootDesktopComponent, _React$Component);
var _super = (0, _createSuper2.default)(ModalRootDesktopComponent);
function ModalRootDesktopComponent(props) {
var _this;
(0, _classCallCheck2.default)(this, ModalRootDesktopComponent);
_this = _super.call(this, props);
(0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "modalsState", void 0);
(0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "maskElementRef", void 0);
(0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "maskAnimationFrame", void 0);
(0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "modalRootContext", void 0);
(0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "activeTransitions", void 0);
(0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "handleKeyDownEsc", function (e) {
if (e.key === 'Escape') {
_this.triggerActiveModalClose();
}
});
(0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "componentWillUnmount", function () {
_this.props.document.removeEventListener('keydown', _this.handleKeyDownEsc);
});
(0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "prevNextSwitchEndHandler", function () {
_this.activeTransitions = Math.max(0, _this.activeTransitions - 1);
if (_this.activeTransitions > 0) {
return;
}
var activeModal = _this.state.nextModal;
var newState = {
prevModal: null,
nextModal: null,
visibleModals: [activeModal],
activeModal: activeModal,
animated: false,
switching: false
};
if (!activeModal) {
newState.history = [];
}
_this.setState(newState);
});
(0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "triggerActiveModalClose", function () {
var activeModalState = _this.modalsState[_this.state.activeModal];
if (activeModalState) {
_this.doCloseModal(activeModalState);
}
});
(0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "doCloseModal", function (modalState) {
if ((0, _utils.isFunction)(modalState.onClose)) {
modalState.onClose();
} else if ((0, _utils.isFunction)(_this.props.onClose)) {
_this.props.onClose(modalState.id);
} else if (IS_DEV) {
warn('onClose is undefined');
}
});
var _activeModal = props.activeModal;
_this.state = {
activeModal: null,
prevModal: null,
nextModal: _activeModal,
visibleModals: _activeModal ? [_activeModal] : [],
animated: !!_activeModal,
switching: false,
history: _activeModal ? [_activeModal] : [],
isBack: false,
inited: false
};
_this.maskElementRef = /*#__PURE__*/React.createRef();
_this.activeTransitions = 0;
_this.initModalsState();
_this.modalRootContext = {
updateModalHeight: function updateModalHeight() {
return undefined;
},
registerModal: function registerModal(_ref) {
var id = _ref.id,
data = (0, _objectWithoutProperties2.default)(_ref, _excluded);
return Object.assign(_this.modalsState[id], data);
},
onClose: _this.triggerActiveModalClose,
isInsideModal: true
};
return _this;
}
(0, _createClass2.default)(ModalRootDesktopComponent, [{
key: "modals",
get: function get() {
return React.Children.toArray(this.props.children);
}
}, {
key: "initModalsState",
value: function initModalsState() {
this.modalsState = this.modals.reduce(function (acc, Modal) {
var modalProps = Modal.props;
var state = {
id: (0, _getNavId.getNavId)(Modal.props, warn),
onClose: Modal.props.onClose,
dynamicContentHeight: !!modalProps.dynamicContentHeight
}; // ModalPage props
if (typeof modalProps.settlingHeight === 'number') {
state.settlingHeight = modalProps.settlingHeight;
}
acc[state.id] = state;
return acc;
}, {});
}
}, {
key: "componentDidMount",
value: function componentDidMount() {
this.initActiveModal();
this.props.document.addEventListener('keydown', this.handleKeyDownEsc);
}
}, {
key: "componentDidUpdate",
value: function componentDidUpdate(prevProps, prevState) {
var _this2 = this;
if (this.props.activeModal !== prevProps.activeModal) {
var nextModal = this.props.activeModal;
var prevModal = prevProps.activeModal;
if (IS_DEV && nextModal !== null && !this.modalsState[nextModal]) {
return warn("[ModalRoot.componentDidUpdate] nextModal ".concat(nextModal, " not found"));
}
var history = (0, _toConsumableArray2.default)(this.state.history);
var isBack = false;
if (nextModal === null) {
history = [];
} else if (history.includes(nextModal)) {
history = history.splice(0, history.indexOf(nextModal) + 1);
isBack = true;
} else {
history.push(nextModal);
}
return this.setState({
activeModal: null,
nextModal: nextModal,
prevModal: prevModal,
visibleModals: [nextModal, prevModal],
history: history,
isBack: isBack,
animated: true,
inited: false,
switching: false
}, function () {
if (nextModal === null) {
_this2.closeActiveModal();
} else {
_this2.initActiveModal();
}
});
}
if (this.state.switching && !prevState.switching) {
requestAnimationFrame(function () {
return _this2.switchPrevNext();
});
}
}
/**
* Инициализирует модалку перед анимацией открытия
*/
}, {
key: "initActiveModal",
value: function initActiveModal() {
var activeModal = this.state.activeModal || this.state.nextModal;
if (!activeModal) {
return;
}
var modalState = this.modalsState[activeModal];
switch (modalState.type) {
case _types.ModalType.PAGE:
modalState.settlingHeight = modalState.settlingHeight || 75;
break;
case _types.ModalType.CARD:
break;
default:
if (IS_DEV) {
warn('[initActiveModal] modalState.type is unknown');
}
}
this.setState({
inited: true,
switching: true
});
}
}, {
key: "closeActiveModal",
value: function closeActiveModal() {
var prevModal = this.state.prevModal;
if (IS_DEV && !prevModal) {
return warn("[closeActiveModal] prevModal is ".concat(prevModal));
}
var prevModalState = this.modalsState[prevModal];
this.waitTransitionFinish(prevModalState, this.prevNextSwitchEndHandler);
this.animateModalOpacity(prevModalState, false);
this.setMaskOpacity(prevModalState, 0);
}
}, {
key: "waitTransitionFinish",
value: function waitTransitionFinish(modalState, eventHandler) {
if (_supportEvents.transitionEvent.supported) {
var onceHandler = function onceHandler() {
modalState.innerElement.removeEventListener(_supportEvents.transitionEvent.name, onceHandler);
eventHandler();
};
modalState.innerElement.addEventListener(_supportEvents.transitionEvent.name, onceHandler);
} else {
setTimeout(eventHandler, this.props.platform === _platform.ANDROID || this.props.platform === _platform.VKCOM ? 320 : 400);
}
}
}, {
key: "switchPrevNext",
value: function switchPrevNext() {
var _this3 = this;
var _this$state = this.state,
prevModal = _this$state.prevModal,
nextModal = _this$state.nextModal;
var prevModalState = this.modalsState[prevModal];
var nextModalState = this.modalsState[nextModal];
if (IS_DEV && !prevModalState && !nextModalState) {
return warn("[switchPrevNext] prevModal is ".concat(prevModal, ", nextModal is ").concat(nextModal));
}
var prevIsCard = !!prevModalState && prevModalState.type === _types.ModalType.CARD;
var nextIsPage = !!nextModalState && nextModalState.type === _types.ModalType.PAGE;
var nextIsCard = !!nextModalState && nextModalState.type === _types.ModalType.CARD; // Ждём полного скрытия предыдущей модалки
if (prevModalState && (nextIsCard || prevIsCard && nextIsPage)) {
this.activeTransitions += 1;
this.waitTransitionFinish(prevModalState, function () {
_this3.waitTransitionFinish(nextModalState, _this3.prevNextSwitchEndHandler);
_this3.animateModalOpacity(nextModalState, true);
});
requestAnimationFrame(function () {
_this3.animateModalOpacity(prevModalState, false);
});
return;
}
if (prevModalState && nextIsPage) {
this.activeTransitions += 1;
this.waitTransitionFinish(prevModalState, this.prevNextSwitchEndHandler);
requestAnimationFrame(function () {
_this3.animateModalOpacity(prevModalState, false);
});
}
this.activeTransitions += 1;
this.waitTransitionFinish(nextModalState, this.prevNextSwitchEndHandler);
requestAnimationFrame(function () {
_this3.animateModalOpacity(nextModalState, true);
});
}
}, {
key: "animateModalOpacity",
value:
/* Анимирует сдивг модалки */
function animateModalOpacity(modalState, display) {
modalState.innerElement.style.opacity = display ? '1' : '0';
}
/* Устанавливает прозрачность для полупрозрачной подложки */
}, {
key: "setMaskOpacity",
value: function setMaskOpacity(modalState) {
var _this4 = this;
var forceOpacity = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
if (forceOpacity === null && this.state.history[0] !== modalState.id) {
return;
}
cancelAnimationFrame(this.maskAnimationFrame);
this.maskAnimationFrame = requestAnimationFrame(function () {
if (_this4.maskElementRef.current) {
var translateY = modalState.translateY,
translateYCurrent = modalState.translateYCurrent;
var opacity = forceOpacity === null ? 1 - (translateYCurrent - translateY) / (100 - translateY) || 0 : forceOpacity;
_this4.maskElementRef.current.style.opacity = Math.max(0, Math.min(100, opacity)).toString();
}
});
}
/**
* Закрывает текущую модалку
*/
}, {
key: "render",
value: function render() {
var _this$state2 = this.state,
prevModal = _this$state2.prevModal,
activeModal = _this$state2.activeModal,
nextModal = _this$state2.nextModal,
visibleModals = _this$state2.visibleModals,
animated = _this$state2.animated;
if (!activeModal && !prevModal && !nextModal && !animated) {
return null;
}
return (0, _jsxRuntime.createScopedElement)(_ModalRootContext.default.Provider, {
value: this.modalRootContext
}, (0, _jsxRuntime.createScopedElement)("div", {
vkuiClass: (0, _classNames.classNames)((0, _getClassName.getClassName)('ModalRoot', this.props.platform), {
'ModalRoot--vkapps': this.props.configProvider.webviewType === _ConfigProviderContext.WebviewType.VKAPPS
}, 'ModalRoot--desktop')
}, (0, _jsxRuntime.createScopedElement)("div", {
vkuiClass: "ModalRoot__mask",
onClick: this.triggerActiveModalClose,
ref: this.maskElementRef
}), (0, _jsxRuntime.createScopedElement)("div", {
vkuiClass: "ModalRoot__viewport"
}, this.modals.map(function (Modal) {
var modalId = (0, _getNavId.getNavId)(Modal.props, warn);
if (!visibleModals.includes(modalId)) {
return null;
}
var key = "modal-".concat(modalId);
return (0, _jsxRuntime.createScopedElement)("div", {
key: key,
vkuiClass: (0, _classNames.classNames)('ModalRoot__modal', {
'ModalRoot__modal--active': modalId === activeModal,
'ModalRoot__modal--prev': modalId === prevModal,
'ModalRoot__modal--next': modalId === nextModal
})
}, Modal);
}))));
}
}]);
return ModalRootDesktopComponent;
}(React.Component);
var ModalRootDesktop = (0, _withContext.withContext)((0, _withPlatform.withPlatform)((0, _dom.withDOM)(ModalRootDesktopComponent)), _ConfigProviderContext.ConfigProviderContext, 'configProvider');
exports.ModalRootDesktop = ModalRootDesktop;
//# sourceMappingURL=ModalRootDesktop.js.map
|
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function _typeof(obj) {
return typeof obj;
};
} else {
_typeof = function _typeof(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["exports", "flatpickr", "../../globals/js/settings", "../../globals/js/misc/mixin", "../../globals/js/mixins/create-component", "../../globals/js/mixins/init-component-by-search", "../../globals/js/mixins/handles", "../../globals/js/misc/on"], factory);
} else if (typeof exports !== "undefined") {
factory(exports, require("flatpickr"), require("../../globals/js/settings"), require("../../globals/js/misc/mixin"), require("../../globals/js/mixins/create-component"), require("../../globals/js/mixins/init-component-by-search"), require("../../globals/js/mixins/handles"), require("../../globals/js/misc/on"));
} else {
var mod = {
exports: {}
};
factory(mod.exports, global.flatpickr, global.settings, global.mixin, global.createComponent, global.initComponentBySearch, global.handles, global.on);
global.datePicker = mod.exports;
}
})(typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : this, function (_exports, _flatpickr, _settings, _mixin2, _createComponent, _initComponentBySearch, _handles, _on) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = void 0;
_flatpickr = _interopRequireDefault(_flatpickr);
_settings = _interopRequireDefault(_settings);
_mixin2 = _interopRequireDefault(_mixin2);
_createComponent = _interopRequireDefault(_createComponent);
_initComponentBySearch = _interopRequireDefault(_initComponentBySearch);
_handles = _interopRequireDefault(_handles);
_on = _interopRequireDefault(_on);
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 _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 _get(target, property, receiver) {
if (typeof Reflect !== "undefined" && Reflect.get) {
_get = Reflect.get;
} else {
_get = function _get(target, property, receiver) {
var base = _superPropBase(target, property);
if (!base) return;
var desc = Object.getOwnPropertyDescriptor(base, property);
if (desc.get) {
return desc.get.call(receiver);
}
return desc.value;
};
}
return _get(target, property, receiver || target);
}
function _superPropBase(object, property) {
while (!Object.prototype.hasOwnProperty.call(object, property)) {
object = _getPrototypeOf(object);
if (object === null) break;
}
return object;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _createSuper(Derived) {
var hasNativeReflectConstruct = _isNativeReflectConstruct();
return function _createSuperInternal() {
var Super = _getPrototypeOf(Derived),
result;
if (hasNativeReflectConstruct) {
var NewTarget = _getPrototypeOf(this).constructor;
result = Reflect.construct(Super, arguments, NewTarget);
} else {
result = Super.apply(this, arguments);
}
return _possibleConstructorReturn(this, result);
};
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
}
return _assertThisInitialized(self);
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _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 _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _toConsumableArray(arr) {
return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
}
function _nonIterableSpread() {
throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(o);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
}
function _iterableToArray(iter) {
if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter);
}
function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) return _arrayLikeToArray(arr);
}
function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) {
arr2[i] = arr[i];
}
return arr2;
}
/* eslint no-underscore-dangle: [2, { "allow": ["_input", "_updateClassNames", "_updateInputFields"], "allowAfterThis": true }] */
// `this.options` create-component mix-in creates prototype chain
// so that `options` given in constructor argument wins over the one defined in static `options` property
// 'Flatpickr' wants flat structure of object instead
function flattenOptions(options) {
var o = {}; // eslint-disable-next-line guard-for-in, no-restricted-syntax
for (var key in options) {
o[key] = options[key];
}
return o;
} // Weekdays shorthand for english locale
_flatpickr.default.l10ns.en.weekdays.shorthand.forEach(function (day, index) {
var currentDay = _flatpickr.default.l10ns.en.weekdays.shorthand;
if (currentDay[index] === 'Thu' || currentDay[index] === 'Th') {
currentDay[index] = 'Th';
} else {
currentDay[index] = currentDay[index].charAt(0);
}
});
var toArray = function toArray(arrayLike) {
return Array.prototype.slice.call(arrayLike);
};
/**
* @param {number} monthNumber The month number.
* @param {boolean} shorthand `true` to use shorthand month.
* @param {Locale} locale The Flatpickr locale data.
* @returns {string} The month string.
*/
var monthToStr = function monthToStr(monthNumber, shorthand, locale) {
return locale.months[shorthand ? 'shorthand' : 'longhand'][monthNumber];
};
/**
* @param {object} config Plugin configuration.
* @param {boolean} [config.shorthand] `true` to use shorthand month.
* @param {string} config.selectorFlatpickrMonthYearContainer The CSS selector for the container of month/year selection UI.
* @param {string} config.selectorFlatpickrYearContainer The CSS selector for the container of year selection UI.
* @param {string} config.selectorFlatpickrCurrentMonth The CSS selector for the text-based month selection UI.
* @param {string} config.classFlatpickrCurrentMonth The CSS class for the text-based month selection UI.
* @returns {Plugin} A Flatpickr plugin to use text instead of `<select>` for month picker.
*/
var carbonFlatpickrMonthSelectPlugin = function carbonFlatpickrMonthSelectPlugin(config) {
return function (fp) {
var setupElements = function setupElements() {
var _fp$monthElements;
if (!fp.monthElements) {
return;
}
fp.monthElements.forEach(function (elem) {
if (!elem.parentNode) return;
elem.parentNode.removeChild(elem);
});
(_fp$monthElements = fp.monthElements).splice.apply(_fp$monthElements, [0, fp.monthElements.length].concat(_toConsumableArray(fp.monthElements.map(function () {
// eslint-disable-next-line no-underscore-dangle
var monthElement = fp._createElement('span', config.classFlatpickrCurrentMonth);
monthElement.textContent = monthToStr(fp.currentMonth, config.shorthand === true, fp.l10n);
fp.yearElements[0].closest(config.selectorFlatpickrMonthYearContainer).insertBefore(monthElement, fp.yearElements[0].closest(config.selectorFlatpickrYearContainer));
return monthElement;
}))));
};
var updateCurrentMonth = function updateCurrentMonth() {
var monthStr = monthToStr(fp.currentMonth, config.shorthand === true, fp.l10n);
fp.yearElements.forEach(function (elem) {
var currentMonthContainer = elem.closest(config.selectorFlatpickrMonthYearContainer);
Array.prototype.forEach.call(currentMonthContainer.querySelectorAll('.cur-month'), function (monthElement) {
monthElement.textContent = monthStr;
});
});
};
var register = function register() {
fp.loadedPlugins.push('carbonFlatpickrMonthSelectPlugin');
};
return {
onMonthChange: updateCurrentMonth,
onValueUpdate: updateCurrentMonth,
onOpen: updateCurrentMonth,
onReady: [setupElements, updateCurrentMonth, register]
};
};
};
var DatePicker = /*#__PURE__*/function (_mixin) {
_inherits(DatePicker, _mixin);
var _super = _createSuper(DatePicker);
/**
* DatePicker.
* @extends CreateComponent
* @extends InitComponentBySearch
* @extends Handles
* @param {HTMLElement} element The element working as an date picker.
*/
function DatePicker(element, options) {
var _this;
_classCallCheck(this, DatePicker);
_this = _super.call(this, element, options);
_this._handleFocus = function () {
if (_this.calendar) {
_this.calendar.open();
}
};
_this._handleBlur = function (event) {
if (_this.calendar) {
var focusTo = event.relatedTarget;
if (!focusTo || !_this.element.contains(focusTo) && (!_this.calendar.calendarContainer || !_this.calendar.calendarContainer.contains(focusTo))) {
_this.calendar.close();
}
}
};
_this._initDatePicker = function (type) {
if (type === 'range') {
// Given FlatPickr assumes one `<input>` even in range mode,
// use a hidden `<input>` for such purpose, separate from our from/to `<input>`s
var doc = _this.element.ownerDocument;
var rangeInput = doc.createElement('input');
rangeInput.className = _this.options.classVisuallyHidden;
rangeInput.setAttribute('aria-hidden', 'true');
_this.element.appendChild(rangeInput);
_this._rangeInput = rangeInput; // An attempt to open the date picker dropdown when this component gets focus,
// and close the date picker dropdown when this component loses focus
var w = doc.defaultView;
var hasFocusin = ('onfocusin' in w);
var hasFocusout = ('onfocusout' in w);
var focusinEventName = hasFocusin ? 'focusin' : 'focus';
var focusoutEventName = hasFocusout ? 'focusout' : 'blur';
_this.manage((0, _on.default)(_this.element, focusinEventName, _this._handleFocus, !hasFocusin));
_this.manage((0, _on.default)(_this.element, focusoutEventName, _this._handleBlur, !hasFocusout));
_this.manage((0, _on.default)(_this.element.querySelector(_this.options.selectorDatePickerIcon), focusoutEventName, _this._handleBlur, !hasFocusout));
}
var self = _assertThisInitialized(_this);
var date = type === 'range' ? _this._rangeInput : _this.element.querySelector(_this.options.selectorDatePickerInput);
var _this$options = _this.options,
_onClose = _this$options.onClose,
_onChange = _this$options.onChange,
_onMonthChange = _this$options.onMonthChange,
_onYearChange = _this$options.onYearChange,
_onOpen = _this$options.onOpen,
_onValueUpdate = _this$options.onValueUpdate;
var calendar = new _flatpickr.default(date, Object.assign(flattenOptions(_this.options), {
allowInput: true,
mode: type,
disableMobile: true,
positionElement: type === 'range' && _this.element.querySelector(_this.options.selectorDatePickerInputFrom),
onClose: function onClose(selectedDates) {
// An attempt to disable Flatpickr's focus tracking system,
// which has adverse effect with our old set up with two `<input>`s or our latest setup with a hidden `<input>`
if (self.shouldForceOpen) {
if (self.calendar.calendarContainer) {
self.calendar.calendarContainer.classList.add('open');
}
self.calendar.isOpen = true;
}
for (var _len = arguments.length, remainder = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
remainder[_key - 1] = arguments[_key];
}
if (!_onClose || _onClose.call.apply(_onClose, [this, selectedDates].concat(remainder)) !== false) {
self._updateClassNames(calendar);
self._updateInputFields(selectedDates, type);
}
},
onChange: function onChange() {
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
if (!_onChange || _onChange.call.apply(_onChange, [this].concat(args)) !== false) {
self._updateClassNames(calendar);
if (type === 'range') {
if (calendar.selectedDates.length === 1 && calendar.isOpen) {
self.element.querySelector(self.options.selectorDatePickerInputTo).classList.add(self.options.classFocused);
} else {
self.element.querySelector(self.options.selectorDatePickerInputTo).classList.remove(self.options.classFocused);
}
}
}
},
onMonthChange: function onMonthChange() {
for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
args[_key3] = arguments[_key3];
}
if (!_onMonthChange || _onMonthChange.call.apply(_onMonthChange, [this].concat(args)) !== false) {
self._updateClassNames(calendar);
}
},
onYearChange: function onYearChange() {
for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
args[_key4] = arguments[_key4];
}
if (!_onYearChange || _onYearChange.call.apply(_onYearChange, [this].concat(args)) !== false) {
self._updateClassNames(calendar);
}
},
onOpen: function onOpen() {
// An attempt to disable Flatpickr's focus tracking system,
// which has adverse effect with our old set up with two `<input>`s or our latest setup with a hidden `<input>`
self.shouldForceOpen = true;
setTimeout(function () {
self.shouldForceOpen = false;
}, 0);
for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
args[_key5] = arguments[_key5];
}
if (!_onOpen || _onOpen.call.apply(_onOpen, [this].concat(args)) !== false) {
self._updateClassNames(calendar);
}
},
onValueUpdate: function onValueUpdate() {
for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) {
args[_key6] = arguments[_key6];
}
if ((!_onValueUpdate || _onValueUpdate.call.apply(_onValueUpdate, [this].concat(args)) !== false) && type === 'range') {
self._updateInputFields(self.calendar.selectedDates, type);
}
},
nextArrow: _this._rightArrowHTML(),
prevArrow: _this._leftArrowHTML(),
plugins: [].concat(_toConsumableArray(_this.options.plugins || []), [carbonFlatpickrMonthSelectPlugin(_this.options)])
}));
if (type === 'range') {
_this._addInputLogic(_this.element.querySelector(_this.options.selectorDatePickerInputFrom), 0);
_this._addInputLogic(_this.element.querySelector(_this.options.selectorDatePickerInputTo), 1);
}
_this.manage((0, _on.default)(_this.element.querySelector(_this.options.selectorDatePickerIcon), 'click', function () {
calendar.open();
}));
_this._updateClassNames(calendar);
if (type !== 'range') {
_this._addInputLogic(date);
}
return calendar;
};
_this._addInputLogic = function (input, index) {
if (!isNaN(index) && (index < 0 || index > 1)) {
throw new RangeError("The index of <input> (".concat(index, ") is out of range."));
}
var inputField = input;
_this.manage((0, _on.default)(inputField, 'change', function (evt) {
if (evt.isTrusted || evt.detail && evt.detail.isNotFromFlatpickr) {
var inputDate = _this.calendar.parseDate(inputField.value);
if (inputDate && !isNaN(inputDate.valueOf())) {
if (isNaN(index)) {
_this.calendar.setDate(inputDate);
} else {
var selectedDates = _this.calendar.selectedDates;
selectedDates[index] = inputDate;
_this.calendar.setDate(selectedDates);
}
}
}
_this._updateClassNames(_this.calendar);
})); // An attempt to temporarily set the `<input>` being edited as the one FlatPicker manages,
// as FlatPicker attempts to take over `keydown` event handler on `document` to run on the date picker dropdown.
_this.manage((0, _on.default)(inputField, 'keydown', function (evt) {
var origInput = _this.calendar._input;
_this.calendar._input = evt.target;
setTimeout(function () {
_this.calendar._input = origInput;
});
}));
};
_this._updateClassNames = function (_ref) {
var calendarContainer = _ref.calendarContainer,
selectedDates = _ref.selectedDates;
if (calendarContainer) {
calendarContainer.classList.add(_this.options.classCalendarContainer);
calendarContainer.querySelector('.flatpickr-month').classList.add(_this.options.classMonth);
calendarContainer.querySelector('.flatpickr-weekdays').classList.add(_this.options.classWeekdays);
calendarContainer.querySelector('.flatpickr-days').classList.add(_this.options.classDays);
toArray(calendarContainer.querySelectorAll('.flatpickr-weekday')).forEach(function (item) {
var currentItem = item;
currentItem.innerHTML = currentItem.innerHTML.replace(/\s+/g, '');
currentItem.classList.add(_this.options.classWeekday);
});
toArray(calendarContainer.querySelectorAll('.flatpickr-day')).forEach(function (item) {
item.classList.add(_this.options.classDay);
if (item.classList.contains('today') && selectedDates.length > 0) {
item.classList.add('no-border');
} else if (item.classList.contains('today') && selectedDates.length === 0) {
item.classList.remove('no-border');
}
});
}
};
_this._updateInputFields = function (selectedDates, type) {
if (type === 'range') {
if (selectedDates.length === 2) {
_this.element.querySelector(_this.options.selectorDatePickerInputFrom).value = _this._formatDate(selectedDates[0]);
_this.element.querySelector(_this.options.selectorDatePickerInputTo).value = _this._formatDate(selectedDates[1]);
} else if (selectedDates.length === 1) {
_this.element.querySelector(_this.options.selectorDatePickerInputFrom).value = _this._formatDate(selectedDates[0]);
}
} else if (selectedDates.length === 1) {
_this.element.querySelector(_this.options.selectorDatePickerInput).value = _this._formatDate(selectedDates[0]);
}
_this._updateClassNames(_this.calendar);
};
_this._formatDate = function (date) {
return _this.calendar.formatDate(date, _this.calendar.config.dateFormat);
};
var _type = _this.element.getAttribute(_this.options.attribType);
_this.calendar = _this._initDatePicker(_type);
if (_this.calendar.calendarContainer) {
_this.manage((0, _on.default)(_this.element, 'keydown', function (e) {
if (e.which === 40) {
e.preventDefault();
(_this.calendar.selectedDateElem || _this.calendar.todayDateElem || _this.calendar.calendarContainer).focus();
}
}));
_this.manage((0, _on.default)(_this.calendar.calendarContainer, 'keydown', function (e) {
if (e.which === 9 && _type === 'range') {
_this._updateClassNames(_this.calendar);
_this.element.querySelector(_this.options.selectorDatePickerInputFrom).focus();
}
}));
}
return _this;
}
/**
* Opens the date picker dropdown when this component gets focus.
* Used only for range mode for now.
* @private
*/
_createClass(DatePicker, [{
key: "_rightArrowHTML",
value: function _rightArrowHTML() {
return "\n <svg\n focusable=\"false\"\n preserveAspectRatio=\"xMidYMid meet\"\n style=\"will-change: transform;\"\n xmlns=\"http://www.w3.org/2000/svg\"\n width=\"16\"\n height=\"16\"\n viewBox=\"0 0 16 16\"\n aria-hidden=\"true\">\n <path d=\"M11 8l-5 5-.7-.7L9.6 8 5.3 3.7 6 3z\"></path>\n </svg>";
}
}, {
key: "_leftArrowHTML",
value: function _leftArrowHTML() {
return "\n <svg\n focusable=\"false\"\n preserveAspectRatio=\"xMidYMid meet\"\n style=\"will-change: transform;\"\n xmlns=\"http://www.w3.org/2000/svg\"\n width=\"16\"\n height=\"16\"\n viewBox=\"0 0 16 16\"\n aria-hidden=\"true\"\n >\n <path d=\"M5 8l5-5 .7.7L6.4 8l4.3 4.3-.7.7z\"></path>\n </svg>";
}
}, {
key: "release",
value: function release() {
if (this._rangeInput && this._rangeInput.parentNode) {
this._rangeInput.parentNode.removeChild(this._rangeInput);
}
if (this.calendar) {
try {
this.calendar.destroy();
} catch (err) {} // eslint-disable-line no-empty
this.calendar = null;
}
return _get(_getPrototypeOf(DatePicker.prototype), "release", this).call(this);
}
/**
* The component options.
* If `options` is specified in the constructor,
* {@linkcode DatePicker.create .create()}, or {@linkcode DatePicker.init .init()},
* properties in this object are overriden for the instance being create and how {@linkcode DatePicker.init .init()} works.
* @property {string} selectorInit The CSS selector to find date picker UIs.
*/
}], [{
key: "options",
get: function get() {
var prefix = _settings.default.prefix;
return {
selectorInit: '[data-date-picker]',
selectorDatePickerInput: '[data-date-picker-input]',
selectorDatePickerInputFrom: '[data-date-picker-input-from]',
selectorDatePickerInputTo: '[data-date-picker-input-to]',
selectorDatePickerIcon: '[data-date-picker-icon]',
selectorFlatpickrMonthYearContainer: '.flatpickr-current-month',
selectorFlatpickrYearContainer: '.numInputWrapper',
selectorFlatpickrCurrentMonth: '.cur-month',
classCalendarContainer: "".concat(prefix, "--date-picker__calendar"),
classMonth: "".concat(prefix, "--date-picker__month"),
classWeekdays: "".concat(prefix, "--date-picker__weekdays"),
classDays: "".concat(prefix, "--date-picker__days"),
classWeekday: "".concat(prefix, "--date-picker__weekday"),
classDay: "".concat(prefix, "--date-picker__day"),
classFocused: "".concat(prefix, "--focused"),
classVisuallyHidden: "".concat(prefix, "--visually-hidden"),
classFlatpickrCurrentMonth: 'cur-month',
attribType: 'data-date-picker-type',
dateFormat: 'm/d/Y'
};
}
/**
* The map associating DOM element and date picker UI instance.
* @type {WeakMap}
*/
}]);
DatePicker.components = new WeakMap();
return DatePicker;
}((0, _mixin2.default)(_createComponent.default, _initComponentBySearch.default, _handles.default));
var _default = DatePicker;
_exports.default = _default;
});
|
"use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = exports.styles = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"));
var React = _interopRequireWildcard(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _clsx = _interopRequireDefault(require("clsx"));
var _utils = require("@material-ui/utils");
var _withStyles = _interopRequireDefault(require("../styles/withStyles"));
var _Paper = _interopRequireDefault(require("../Paper"));
var _capitalize = _interopRequireDefault(require("../utils/capitalize"));
var _LinearProgress = _interopRequireDefault(require("../LinearProgress"));
var _jsxRuntime = require("react/jsx-runtime");
const styles = theme => ({
/* Styles applied to the root element. */
root: {
display: 'flex',
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
background: theme.palette.background.default,
padding: 8
},
/* Styles applied to the root element if `position="bottom"`. */
positionBottom: {
position: 'fixed',
bottom: 0,
left: 0,
right: 0,
zIndex: theme.zIndex.mobileStepper
},
/* Styles applied to the root element if `position="top"`. */
positionTop: {
position: 'fixed',
top: 0,
left: 0,
right: 0,
zIndex: theme.zIndex.mobileStepper
},
/* Styles applied to the root element if `position="static"`. */
positionStatic: {},
/* Styles applied to the dots container if `variant="dots"`. */
dots: {
display: 'flex',
flexDirection: 'row'
},
/* Styles applied to each dot if `variant="dots"`. */
dot: {
transition: theme.transitions.create('background-color', {
duration: theme.transitions.duration.shortest
}),
backgroundColor: theme.palette.action.disabled,
borderRadius: '50%',
width: 8,
height: 8,
margin: '0 2px'
},
/* Styles applied to a dot if `variant="dots"` and this is the active step. */
dotActive: {
backgroundColor: theme.palette.primary.main
},
/* Styles applied to the Linear Progress component if `variant="progress"`. */
progress: {
width: '50%'
}
});
exports.styles = styles;
const MobileStepper = /*#__PURE__*/React.forwardRef(function MobileStepper(props, ref) {
const {
activeStep = 0,
backButton,
classes,
className,
LinearProgressProps,
nextButton,
position = 'bottom',
steps,
variant = 'dots'
} = props,
other = (0, _objectWithoutPropertiesLoose2.default)(props, ["activeStep", "backButton", "classes", "className", "LinearProgressProps", "nextButton", "position", "steps", "variant"]);
return /*#__PURE__*/(0, _jsxRuntime.jsxs)(_Paper.default, (0, _extends2.default)({
square: true,
elevation: 0,
className: (0, _clsx.default)(classes.root, classes[`position${(0, _capitalize.default)(position)}`], className),
ref: ref
}, other, {
children: [backButton, variant === 'text' && /*#__PURE__*/(0, _jsxRuntime.jsxs)(React.Fragment, {
children: [activeStep + 1, " / ", steps]
}), variant === 'dots' && /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
className: classes.dots,
children: [...new Array(steps)].map((_, index) => /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
className: (0, _clsx.default)(classes.dot, index === activeStep && classes.dotActive)
}, index))
}), variant === 'progress' && /*#__PURE__*/(0, _jsxRuntime.jsx)(_LinearProgress.default, (0, _extends2.default)({
className: classes.progress,
variant: "determinate",
value: Math.ceil(activeStep / (steps - 1) * 100)
}, LinearProgressProps)), nextButton]
}));
});
process.env.NODE_ENV !== "production" ? MobileStepper.propTypes
/* remove-proptypes */
= {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit the d.ts file and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* Set the active step (zero based index).
* Defines which dot is highlighted when the variant is 'dots'.
* @default 0
*/
activeStep: _utils.integerPropType,
/**
* A back button element. For instance, it can be a `Button` or an `IconButton`.
*/
backButton: _propTypes.default.node,
/**
* Override or extend the styles applied to the component.
*/
classes: _propTypes.default.object,
/**
* @ignore
*/
className: _propTypes.default.string,
/**
* Props applied to the `LinearProgress` element.
*/
LinearProgressProps: _propTypes.default.object,
/**
* A next button element. For instance, it can be a `Button` or an `IconButton`.
*/
nextButton: _propTypes.default.node,
/**
* Set the positioning type.
* @default 'bottom'
*/
position: _propTypes.default.oneOf(['bottom', 'static', 'top']),
/**
* The total steps.
*/
steps: _utils.integerPropType.isRequired,
/**
* The variant to use.
* @default 'dots'
*/
variant: _propTypes.default.oneOf(['dots', 'progress', 'text'])
} : void 0;
var _default = (0, _withStyles.default)(styles, {
name: 'MuiMobileStepper'
})(MobileStepper);
exports.default = _default;
|
'use strict'
var duplex = require('duplexer')
var through = require('through')
module.exports = function (counter) {
var counts = {}
return duplex(through(record_count, set_count), counter)
// Shifting the declaration of |counts| after the |return|
// statement triggers a "huh what |counts|?" error in record_count:
//
// TypeError: Cannot read property 'MX' of undefined
// Also note this "declare functions after return" trick relies on
// function declarations getting picked up during parsing,
// unlike function expressions, which only execute when the line
// executes. See http://stackoverflow.com/a/336868/72508.
function record_count(obj) {
var country = obj.country
var count = counts[country] || 0
counts[country] = count + 1
}
function set_count() {
counter.setCounts(counts)
counts = {}
}
}
|
( function( $ ) {
"use strict";
$.fn.hoverfold = function( args ) {
this.each( function() {
$( this ).children( '.view' ).each( function() {
var $item = $( this ),
img = $item.children( 'img' ).attr( 'src' ),
struct = '<div class="slice s1">';
struct +='<div class="slice s2">';
struct +='<div class="slice s3">';
struct +='<div class="slice s4">';
struct +='<div class="slice s5">';
struct +='</div>';
struct +='</div>';
struct +='</div>';
struct +='</div>';
struct +='</div>';
var $struct = $( struct );
$item.find( 'img' ).remove().end().append( $struct ).find( 'div.slice' ).css( 'background-image', 'url(' + img + ')' ).prepend( $( '<span class="overlay" ></span>' ) );
} );
});
};
} )( jQuery );
|
// Pos.js
function Pos (x,y) {
this.x = x;
this.y = y;
}
Pos.prototype.getIndex = function () {
return this.x+"x"+this.y;
}
Pos.prototype.toString = function () {
return this.getIndex();
}
Pos.prototype.clone = function () {
return new Pos (this.x,this.y);
}
|
"use strict";
const {
LUA_MINSTACK,
LUA_RIDX_GLOBALS,
LUA_RIDX_MAINTHREAD,
constant_types: {
LUA_NUMTAGS,
LUA_TNIL,
LUA_TTABLE,
LUA_TTHREAD
},
thread_status: {
LUA_OK
}
} = require('./defs.js');
const lobject = require('./lobject.js');
const ldo = require('./ldo.js');
const lapi = require('./lapi.js');
const ltable = require('./ltable.js');
const ltm = require('./ltm.js');
const EXTRA_STACK = 5;
const BASIC_STACK_SIZE = 2 * LUA_MINSTACK;
class CallInfo {
constructor() {
this.func = null;
this.funcOff = NaN;
this.top = NaN;
this.previous = null;
this.next = null;
/* only for Lua functions */
this.l_base = NaN; /* base for this function */
this.l_code = null; /* reference to this.func.p.code */
this.l_savedpc = NaN; /* offset into l_code */
/* only for JS functions */
this.c_k = null; /* continuation in case of yields */
this.c_old_errfunc = null;
this.c_ctx = null; /* context info. in case of yields */
this.nresults = NaN;
this.callstatus = NaN;
}
}
class lua_State {
constructor(g) {
this.id = g.id_counter++;
this.base_ci = new CallInfo(); /* CallInfo for first level (C calling Lua) */
this.top = NaN; /* first free slot in the stack */
this.stack_last = NaN; /* last free slot in the stack */
this.oldpc = NaN; /* last pc traced */
/* preinit_thread */
this.l_G = g;
this.stack = null;
this.ci = null;
this.errorJmp = null;
this.nCcalls = 0;
this.hook = null;
this.hookmask = 0;
this.basehookcount = 0;
this.allowhook = 1;
this.hookcount = this.basehookcount;
this.nny = 1;
this.status = LUA_OK;
this.errfunc = 0;
}
}
class global_State {
constructor() {
this.id_counter = 1; /* used to give objects unique ids */
this.ids = new WeakMap();
this.mainthread = null;
this.l_registry = new lobject.TValue(LUA_TNIL, null);
this.panic = null;
this.atnativeerror = null;
this.version = null;
this.tmname = new Array(ltm.TMS.TM_N);
this.mt = new Array(LUA_NUMTAGS);
}
}
const luaE_extendCI = function(L) {
let ci = new CallInfo();
L.ci.next = ci;
ci.previous = L.ci;
ci.next = null;
L.ci = ci;
return ci;
};
const luaE_freeCI = function(L) {
let ci = L.ci;
ci.next = null;
};
const stack_init = function(L1, L) {
L1.stack = new Array(BASIC_STACK_SIZE);
L1.top = 0;
L1.stack_last = BASIC_STACK_SIZE - EXTRA_STACK;
/* initialize first ci */
let ci = L1.base_ci;
ci.next = ci.previous = null;
ci.callstatus = 0;
ci.funcOff = L1.top;
ci.func = L1.stack[L1.top];
L1.stack[L1.top++] = new lobject.TValue(LUA_TNIL, null);
ci.top = L1.top + LUA_MINSTACK;
L1.ci = ci;
};
const freestack = function(L) {
L.ci = L.base_ci;
luaE_freeCI(L);
L.stack = null;
};
/*
** Create registry table and its predefined values
*/
const init_registry = function(L, g) {
let registry = ltable.luaH_new(L);
g.l_registry.sethvalue(registry);
ltable.luaH_setint(registry, LUA_RIDX_MAINTHREAD, new lobject.TValue(LUA_TTHREAD, L));
ltable.luaH_setint(registry, LUA_RIDX_GLOBALS, new lobject.TValue(LUA_TTABLE, ltable.luaH_new(L)));
};
/*
** open parts of the state that may cause memory-allocation errors.
** ('g->version' !== NULL flags that the state was completely build)
*/
const f_luaopen = function(L) {
let g = L.l_G;
stack_init(L, L);
init_registry(L, g);
ltm.luaT_init(L);
g.version = lapi.lua_version(null);
};
const lua_newthread = function(L) {
let g = L.l_G;
let L1 = new lua_State(g);
L.stack[L.top] = new lobject.TValue(LUA_TTHREAD, L1);
lapi.api_incr_top(L);
L1.hookmask = L.hookmask;
L1.basehookcount = L.basehookcount;
L1.hook = L.hook;
L1.hookcount = L1.basehookcount;
stack_init(L1, L);
return L1;
};
const luaE_freethread = function(L, L1) {
freestack(L1);
};
const lua_newstate = function() {
let g = new global_State();
let L = new lua_State(g);
g.mainthread = L;
if (ldo.luaD_rawrunprotected(L, f_luaopen, null) !== LUA_OK) {
L = null;
}
return L;
};
const close_state = function(L) {
freestack(L);
};
const lua_close = function(L) {
L = L.l_G.mainthread; /* only the main thread can be closed */
close_state(L);
};
module.exports.lua_State = lua_State;
module.exports.CallInfo = CallInfo;
module.exports.CIST_OAH = (1<<0); /* original value of 'allowhook' */
module.exports.CIST_LUA = (1<<1); /* call is running a Lua function */
module.exports.CIST_HOOKED = (1<<2); /* call is running a debug hook */
module.exports.CIST_FRESH = (1<<3); /* call is running on a fresh invocation of luaV_execute */
module.exports.CIST_YPCALL = (1<<4); /* call is a yieldable protected call */
module.exports.CIST_TAIL = (1<<5); /* call was tail called */
module.exports.CIST_HOOKYIELD = (1<<6); /* last hook called yielded */
module.exports.CIST_LEQ = (1<<7); /* using __lt for __le */
module.exports.CIST_FIN = (1<<8); /* call is running a finalizer */
module.exports.EXTRA_STACK = EXTRA_STACK;
module.exports.lua_close = lua_close;
module.exports.lua_newstate = lua_newstate;
module.exports.lua_newthread = lua_newthread;
module.exports.luaE_extendCI = luaE_extendCI;
module.exports.luaE_freeCI = luaE_freeCI;
module.exports.luaE_freethread = luaE_freethread;
|
const precision = require('./precision')
const AGG_NAME = 'geo_geohash'
const AGG_NAME_NESTED = 'geo_geohash_nested'
const ES_FIELD = 'contact.geoCoords'
async function aggGeohash(search, { top, left, bottom, right }) {
const searchParams = {
index: undefined, // this is set when queries combined in parent class
body: {
query: undefined, // this is set when queries combined in parent class
aggs: {
[AGG_NAME]: {
filter: {
geo_bounding_box: {
[ES_FIELD]: { top, left, bottom, right },
},
},
aggs: {
[AGG_NAME_NESTED]: {
geohash_grid: {
field: ES_FIELD,
precision: precision({ top, left, bottom, right }),
},
}
},
}
}
},
size: 0,
}
try {
const response = await search(searchParams)
const buckets = response.aggregations[AGG_NAME][AGG_NAME_NESTED].buckets.map(x => ({
key: `${x.key}`,
name: `${x.key}`,
count: x.doc_count,
}))
return {
buckets,
}
} catch(e) {
throw e
}
}
module.exports = aggGeohash
|
/*! @license Firebase v4.3.0
Build: rev-bd8265e
Terms: https://firebase.google.com/terms/ */
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
/**
* Copyright 2017 Google 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.
*/
var scope;
if (typeof global !== 'undefined') {
scope = global;
} else if (typeof self !== 'undefined') {
scope = self;
} else {
try {
scope = Function('return this')();
} catch (e) {
throw new Error('polyfill failed because global object is unavailable in this environment');
}
}
var globalScope = exports.globalScope = scope;
//# sourceMappingURL=globalScope.js.map
|
(function() {
var modelsByExtension = {
'.ogg': 'audio',
'.ogv': 'video',
'.jpg': 'image',
'.png': 'image',
'.js': 'scene',
'.json': 'scene',
'.obj': 'scene',
'.gltf': 'scene',
'.fbx': 'scene',
'.dae': 'scene',
'.zip': 'scene'
}
function uploadFile(file) {
var dfd = when.defer()
var fnl = file.name.toLowerCase()
var extname = fnl.substring(fnl.lastIndexOf('.'))
var modelName = modelsByExtension[extname]
var formData = new FormData()
formData.append('filename', file.name)
formData.append('file', file)
$.ajax({
url: '/upload/' + modelName,
type: 'POST',
xhr: function() {
var xhr = $.ajaxSettings.xhr()
xhr.upload.addEventListener('progress', function(evt) {
if (evt.lengthComputable)
E2.ui.updateProgressBar(Math.floor(evt.loaded/evt.total * 100))
}, false)
return xhr
},
success: function(uploadedFile) {
E2.track({
event: 'uploaded',
modelName: modelName,
path: uploadedFile.url
})
E2.ui.updateProgressBar(100)
E2.models.fileList.addFile(file)
uploadedFile.modelName = modelName
dfd.resolve(uploadedFile)
},
error: function(err) {
var errMsg = err.responseJSON ? err.responseJSON.message : err
dfd.reject(errMsg)
},
data: formData,
cache: false,
contentType: false,
processData: false,
dataType: 'json'
})
return dfd.promise
}
// Traverse the pasted nodes and perform any fixup (fix
function postPasteFixup(nodes, fixupCallback) {
function fixupNode(node) {
if (E2.GRAPH_NODES.indexOf(node.plugin.id) > -1) {
for (var i = 0, len = node.plugin.graph.nodes.length; i < len; ++i) {
fixupNode(node.plugin.graph.nodes[i])
}
}
if (fixupCallback)
fixupCallback(node)
}
for (var i = 0, len = nodes.length; i < len; ++i) {
fixupNode(nodes[i])
}
}
function instantiatePluginForUpload(uploaded, position) {
var dfd = when.defer()
var pluginId
// add a node to graph if graph visible
switch(uploaded.modelName) {
case 'image':
pluginId = 'url_texture_generator'
break;
case 'scene':
pluginId = 'three_loader_scene'
break;
case 'audio':
pluginId = 'url_audio_buffer_generator'
break;
case 'video':
pluginId = 'url_video_generator'
break;
}
var node = E2.app.createPlugin(pluginId, position)
node.plugin.state.url = uploaded.url
E2.track({
event: 'nodeAdded',
id: pluginId,
fromUpload: true
})
E2.app.graphApi.addNode(E2.core.active_graph, node)
dfd.resolve(node)
postPasteFixup([node])
return dfd.promise
}
function instantiateTemplateForUpload(asset, position) {
var dfd = when.defer()
var templateName
var templateData = _.clone(asset)
var isEquiRectangular = asset.tags.indexOf('equirectangular') !== -1
function fixupCallback(node) {
if (node.plugin.id === 'three_mesh') {
node.plugin.postLoadCallback = new TexturePlacementHelper()
}
if (node.plugin.id === 'three_loader_scene') {
node.plugin.postLoadCallback = new ObjectPlacementHelper()
}
}
console.info('instantiating template for asset', asset)
if (!templateData.name) {
templateData.name = asset.path
.substring(asset.path.lastIndexOf('/') + 1)
}
// add to scene if graph not visible
switch(asset.modelName) {
case 'image':
templateName = 'texture-plane.hbs'
if (isEquiRectangular) {
templateName = '360photo.hbs'
}
break;
case 'scene':
templateName = 'scene.hbs'
break;
case 'audio':
templateName = 'audio.hbs'
break;
case 'video':
templateName = 'video_plane.patch.hbs'
break;
}
$.get('/patchTemplates/'+templateName)
.done(function(templateSource) {
var template = Handlebars.compile(templateSource)
var patch = template(templateData)
try {
patch = JSON.parse(patch)
} catch(err) {
return dfd.reject(err)
}
E2.app.undoManager.begin('Drag & Drop Upload')
// if there is already a 360 photo in the scene,
// replace it with this one
if (isEquiRectangular) {
E2.app.removeEntityFromScene('threesixty_photo_entity')
}
E2.track({
event: 'patchAdded',
name: templateName,
fromUpload: true
})
var pasted = E2.app.pasteInGraph(E2.core.root_graph, patch, position[0], position[1])
postPasteFixup(pasted.nodes, fixupCallback)
if (E2.app.isWorldEditorActive() && asset.modelName !== 'audio') {
E2.app.worldEditor.onEntityDropped(pasted.nodes[0])
}
E2.app.undoManager.end()
dfd.resolve()
})
.fail(function(error) {
dfd.reject(error)
})
return dfd.promise
}
/**
* listen to file drops, and upload all accepted files to right category on server
*/
VizorUI.prototype.initDropUpload = function() {
var that = this
var target = $(document)
E2.dom.dragOverlay.height(E2.dom.canvases.height())
function cleanup() {
E2.dom.dropUploading.hide()
E2.dom.dragOverlay.hide()
that.uploading = false
$('body').css('pointerEvents', 'all')
document.removeEventListener('visibilitychange', cleanup)
return false
}
target.on('drop', function(e) {
e.preventDefault();
var dropPosition = [ e.clientX, e.clientY ]
E2.dom.dropArea.hide()
if (!E2.models.user.get('username')) {
E2.dom.dragOverlay.hide()
cleanup()
return bootbox.alert('Please sign in before uploading.')
}
var files = e.originalEvent.dataTransfer.files;
var acceptedFiles = []
for (var i=0; i < files.length; i++) {
var file = files[i]
var fnl = file.name.toLowerCase()
var extname = fnl.substring(fnl.lastIndexOf('.'))
if (modelsByExtension[extname])
acceptedFiles.push(file)
}
if (!acceptedFiles.length)
return cleanup()
E2.dom.dropUploading.show()
that.uploading = true
when.map(acceptedFiles, uploadFile)
.catch(function(err) {
bootbox.alert('Upload failed: ' + err)
})
.then(function(uploadedFiles) {
return when.map(uploadedFiles, function(uploaded) {
// dropping into root graph, you want it in the scene
if (E2.core.active_graph === E2.core.root_graph)
return instantiateTemplateForUpload(uploaded, dropPosition)
if (E2.ui.isPatchEditorVisible()) {
return instantiatePluginForUpload(uploaded, dropPosition)
} else {
return instantiateTemplateForUpload(uploaded, dropPosition)
}
})
})
.then(function() {
cleanup()
})
return false
})
target.on('dragenter', function(e) {
e.stopPropagation()
e.preventDefault()
document.addEventListener('visibilitychange', cleanup)
})
target.on('dragover', function(e) {
e.stopPropagation()
e.preventDefault()
$('body').css('pointerEvents', 'none')
if (!that.isUploading()) {
E2.dom.dragOverlay.show()
E2.dom.dropArea.show()
} else {
return false
}
return true
})
target.on('dragleave dragend', function(e) {
e.stopPropagation()
e.preventDefault()
// we get dragleave on CANVAS and HTML elements, drop the CANVAS ones
if (e.target.tagName !== 'HTML')
return;
cleanup()
return false
})
}
})()
|
// This is a thin wrapper around node-teamspeak which automatically reconnects
// when there is a socket event, and handles closing and dispatching
// appropriately as a result.
var console = require('better-console');
var ts3 = require('node-teamspeak');
var async = require('async');
function connect(ctx, config) {
ctx.restarted = false;
ctx.cl = new ts3(config.get("server.host"), config.get("server.port"));
ctx.cl.on('connect', function() {
async.series([
function (cb) {
ctx.cl.send("login",
{client_login_name: config.get("server.user"), client_login_password: config.get("server.pass")},
cb);
},
function (cb) {
ctx.cl.send("use", {sid: 1}, cb);
},
function (cb) {
ctx.cl.send("clientupdate", {client_nickname: ctx.username}, cb);
},
function (cb) {
ctx.cl.send("whoami", {client_nickname: ctx.username}, function (err, response) {
if (err) {
cb(err);
} else {
ctx.clid = response.client_id;
cb();
}
});
},
function (cb) {
ctx.cl.send("clientmove", {clid: ctx.clid, cid: ctx.cid}, function(err) {
if (err) {
if (err.id != 770) {
return cb(err);
}
}
cb();
});
}
], function (err) {
if (err) {
console.warn("Supervisor connection error: " + JSON.stringify(err));
ctx.cl.close();
return;
}
ctx.ready = true;
})
});
ctx.cl.on('close', function() {
ctx.ready = false;
if (ctx.enabled && !ctx.restarted) {
console.warn("connection closed, reconnecting..");
ctx.restarted = true;
setTimeout(function() {
connect(ctx, config);
}, 5000);
}
})
ctx.cl.on('error', function(err) {
ctx.ready = false;
if (ctx.enabled && !ctx.restarted) {
console.warn("socket error " + err + ", reconnecting..");
ctx.restarted = true;
setTimeout(function() {
connect(ctx, config);
}, 5000);
}
})
ctx.cl.on('textmessage', function(data) {
if (ctx.enabled && (data.invokername != config.get("bot.name"))) {
// TODO: make this use the bot's invokeruid instead
ctx.on_channel_message(data);
}
})
}
module.exports = function TS3Bot(config, username, cid) {
var ctx = {
cl: null,
enabled: true,
restarted: false,
ready: false,
username: username,
cid: cid,
clid: 0,
on_channel_message: function() {}
};
connect(ctx, config);
this.close = function() {
ctx.enabled = false;
if (ctx.cl) {
ctx.cl.close();
}
}
this.on_channel_message = function(cb) {
ctx.on_channel_message = cb;
}
this.send = function(cmd, options, cb) {
if (ctx.ready && ctx.cl) {
ctx.cl.send(cmd, options, cb);
} else {
var self = this;
setTimeout(function() {
self.send(cmd, options, cb);
}, 1000);
}
}
this.move_to_channel = function(cid, cb) {
ctx.cid = cid;
this.send("clientmove", {clid: ctx.clid, cid: ctx.cid}, function(err, response) {
if (err && err.id == 770) {
err = null;
}
cb(err);
})
}
this.change_username = function(name, cb) {
ctx.username = name;
this.send("clientupdate", {client_nickname: ctx.username}, function(err, response) {
cb(err);
})
}
this.send_private_message = function(clid, msg, cb) {
this.send("sendtextmessage", {targetmode: 1, target: clid, msg: msg}, function(err) {
cb(err);
});
}
this.send_channel_message = function(msg, cb) {
this.send("sendtextmessage", {targetmode: 2, msg: msg}, function(err) {
cb(err);
})
}
this.watch_channel = function(cb) {
this.send("servernotifyregister", {event: "textchannel", id: ctx.cid}, function(err) {
cb(err);
})
}
this.get_server_info = function(cb) {
this.send("serverinfo", {}, function(err, response) {
cb(err, response)
})
}
this.get_client_info = function(clid, cb) {
this.send("clientinfo", {clid: clid}, function(err, response) {
cb(err, response);
})
}
this.get_client_list = function(cb) {
this.send("clientlist", {}, function(err, response) {
cb(err, response);
})
}
// send a heartbeat every 5 seconds to prevent a timeout
var self = this;
async.forever(function(next) {
setTimeout(function() {
self.send("whoami", {}, function(err) {
if (ctx.enabled) {
next()
}
})
}, 5000)
})
}
|
export {default} from 'ember-frost-bunsen/components/inputs/datetime'
|
const {UseServiceWorker, AppSubUrl, AppVer} = window.config;
const cachePrefix = 'static-cache-v'; // actual version is set in the service worker script
async function unregister() {
const registrations = await navigator.serviceWorker.getRegistrations();
await Promise.all(registrations.map((registration) => {
return registration.active && registration.unregister();
}));
}
async function invalidateCache() {
const cacheKeys = await caches.keys();
await Promise.all(cacheKeys.map((key) => {
return key.startsWith(cachePrefix) && caches.delete(key);
}));
}
async function checkCacheValidity() {
const cacheKey = AppVer;
const storedCacheKey = localStorage.getItem('staticCacheKey');
// invalidate cache if it belongs to a different gitea version
if (cacheKey && storedCacheKey !== cacheKey) {
await invalidateCache();
localStorage.setItem('staticCacheKey', cacheKey);
}
}
export default async function initServiceWorker() {
if (!('serviceWorker' in navigator)) return;
if (UseServiceWorker) {
try {
// normally we'd serve the service worker as a static asset from StaticUrlPrefix but
// the spec strictly requires it to be same-origin so it has to be AppSubUrl to work
await Promise.all([
checkCacheValidity(),
navigator.serviceWorker.register(`${AppSubUrl}/serviceworker.js`),
]);
} catch (err) {
console.error(err);
await Promise.all([
invalidateCache(),
unregister(),
]);
}
} else {
await Promise.all([
invalidateCache(),
unregister(),
]);
}
}
|
Type.registerNamespace("Sys.Extended.UI.HtmlEditor");
Sys.Extended.UI.HtmlEditor.Trim = function(value) {
return value.replace(/[\x00-\x1F]+/g, "");
};
Sys.Extended.UI.HtmlEditor.TrimAll = function(value) {
return value.replace(/[\x00-\x1F]/g, "").replace(/^[\x20]+/g, "").replace(/[\x20]+$/g, "");
};
Sys.Extended.UI.HtmlEditor.isIE = (Sys.Browser.agent == Sys.Browser.InternetExplorer);
Sys.Extended.UI.HtmlEditor.isSafari = (Sys.Browser.agent == Sys.Browser.Safari || (Sys.Browser.agent == null && Sys.Browser.version == 5 && Sys.Browser.name == "Netscape"));
Sys.Extended.UI.HtmlEditor.isOpera = (Sys.Browser.agent == Sys.Browser.Opera);
Sys.Extended.UI.HtmlEditor.tryReplaceRgb = function(value) {
var result = value;
var re = /(rgb\s*\(\s*([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\s*\))/ig;
function hex(d) {
return (d < 16) ? ("0" + d.toString(16)) : d.toString(16);
};
function repl($0, $1, $2, $3, $4) {
var r = parseInt($2);
var g = parseInt($3);
var b = parseInt($4);
return "#" + hex(r) + hex(g) + hex(b);
}
try { // some versions of Safari don't support such replace
result = result.replace(re, repl);
} catch(e) { }
return result;
}
Sys.Extended.UI.HtmlEditor._getScrollTop = function(win) {
var doc = win.document;
var scrollTop = 0;
if(typeof (win.pageYOffset) == 'number')
scrollTop = win.pageYOffset;
if(doc.body && doc.body.scrollTop)
scrollTop = doc.body.scrollTop;
else if(doc.documentElement && doc.documentElement.scrollTop)
scrollTop = doc.documentElement.scrollTop;
return scrollTop;
}
Sys.Extended.UI.HtmlEditor._getScrollLeft = function(win) {
var doc = win.document;
var scrollLeft = 0;
if(typeof (win.pageXOffset) == 'number')
scrollLeft = win.pageXOffset;
else if(doc.body && doc.body.scrollLeft)
scrollLeft = doc.body.scrollLeft;
else if(doc.documentElement && doc.documentElement.scrollLeft)
scrollLeft = doc.documentElement.scrollLeft;
return scrollLeft;
}
Sys.Extended.UI.HtmlEditor.addFormOnSubmit = function(handler, editPanel) {
var form = window.theForm;
if(window.theForm != null && typeof window.theForm != "undefined") {
if(form.HtmlEditor_editPanels == null || typeof form.HtmlEditor_editPanels == "undefined") {
form.originalOnSubmit_HtmlEditor = window.theForm.onsubmit;
form.HtmlEditor_editPanels = [];
window.theForm.onsubmit = Sys.Extended.UI.HtmlEditor.EditPanelsOnSubmit;
if(window.__doPostBack != null && typeof window.__doPostBack != "undefined")
if(window.__doPostBack_HtmlEditor_original == null || typeof window.__doPostBack_HtmlEditor_original == "undefined") {
window.__doPostBack_HtmlEditor_original = window.__doPostBack;
window.__doPostBack = Sys.Extended.UI.HtmlEditor.EditPanelsOnPostBack;
}
if(window.ValidatorGetValue != null && typeof window.ValidatorGetValue != "undefined")
if(window.ValidatorGetValue_HtmlEditor_original == null || typeof window.ValidatorGetValue_HtmlEditor_original == "undefined") {
window.ValidatorGetValue_HtmlEditor_original = window.ValidatorGetValue;
window.ValidatorGetValue = Sys.Extended.UI.HtmlEditor.ValidatorGetValue;
}
}
form.HtmlEditor_editPanels.push({ handler: handler, editPanel: editPanel });
}
}
Sys.Extended.UI.HtmlEditor.removeFormOnSubmit = function(handler) {
var form = window.theForm;
if(window.theForm != null && typeof window.theForm != "undefined") {
var original = form.originalOnSubmit_HtmlEditor;
if(form.HtmlEditor_editPanels != null && typeof form.HtmlEditor_editPanels != "undefined") {
var newArr = [];
for(var i = 0; i < form.HtmlEditor_editPanels.length; i++) {
var cur = form.HtmlEditor_editPanels[i];
if(cur.handler != handler)
newArr.push(cur);
}
form.HtmlEditor_editPanels = newArr;
if(form.HtmlEditor_editPanels.length == 0) {
window.theForm.onsubmit = original;
form.originalOnSubmit_HtmlEditor = null;
form.HtmlEditor_editPanels = null;
if(window.__doPostBack_HtmlEditor_original != null && typeof window.__doPostBack_HtmlEditor_original != "undefined") {
window.__doPostBack = window.__doPostBack_HtmlEditor_original;
window.__doPostBack_HtmlEditor_original = null;
}
if(window.ValidatorGetValue_HtmlEditor_original != null && typeof window.ValidatorGetValue_HtmlEditor_original != "undefined") {
window.ValidatorGetValue = window.ValidatorGetValue_HtmlEditor_original;
window.ValidatorGetValue_HtmlEditor_original = null;
}
}
}
}
}
Sys.Extended.UI.HtmlEditor.EditPanelsOnSubmit = function(e) {
var form = window.theForm,
ret = true;
for(var i = 0; i < form.HtmlEditor_editPanels.length; i++) {
var ret = form.HtmlEditor_editPanels[i].handler(e);
if(!ret)
break;
}
if(ret && form.originalOnSubmit_HtmlEditor != null && typeof form.originalOnSubmit_HtmlEditor != "undefined")
ret = form.originalOnSubmit_HtmlEditor(e);
if(!ret || !window.Page_IsValid)
for(var i = 0; i < form.HtmlEditor_editPanels.length; i++)
form.HtmlEditor_editPanels[i].editPanel._contentPrepared = false;
return ret;
}
Sys.Extended.UI.HtmlEditor.ValidatorGetValue = function(id) {
var component = $find(id);
if(component != null) {
var editPanel = null;
if(Sys.Extended.UI.HtmlEditor.Editor.isInstanceOfType(component))
editPanel = component.get_editPanel();
else if(Sys.Extended.UI.HtmlEditor.EditPanel.isInstanceOfType(component))
editPanel = component;
if(editPanel != null) {
var content = editPanel._contentForValidation;
if(content == null || typeof content == "undefined")
content = editPanel.get_content();
return content;
}
}
return window.ValidatorGetValue_HtmlEditor_original(id);
}
Sys.Extended.UI.HtmlEditor.EditPanelsOnPostBack = function(eventTarget, eventArgument) {
var form = window.theForm;
for(var i = 0; i < form.HtmlEditor_editPanels.length; i++) {
var ret = form.HtmlEditor_editPanels[i].handler(null);
if(!ret)
return false;
}
if(window.__doPostBack_HtmlEditor_original != null && typeof window.__doPostBack_HtmlEditor_original != "undefined")
return window.__doPostBack_HtmlEditor_original(eventTarget, eventArgument);
return true;
}
Sys.Extended.UI.HtmlEditor.getRealAttributeIE = function(element, name, source) {
var value = source,
n_value = "";
function tempFunc(p0, p1) {
n_value = p1;
}
element.outerHTML.replace(new RegExp("^(?:<[^>]*?" + name + "=\")([^\"]*?)\"", "ig"), tempFunc);
if(n_value == "")
element.outerHTML.replace(new RegExp("^(?:<[^>]*?" + name + "=')([^']*?)'", "ig"), tempFunc);
if(n_value == "")
element.outerHTML.replace(new RegExp("^(?:<[^>]*?" + name + "=)([^\s>]*?)", "ig"), tempFunc);
if(value != n_value && n_value != "") {
value = n_value;
value = value.replace(/&/g, "&");
}
return value;
}
Sys.Extended.UI.HtmlEditor.getRealAttribute = function(element, name) {
var searchName = name.toLowerCase(),
attrs = element.attributes,
value = "";
for(i = 0; i < attrs.length; ++i) {
var a = attrs.item(i);
if(!a.specified)
continue;
var name = a.name.toLowerCase();
if(name == searchName) {
value = a.value;
if(Sys.Extended.UI.HtmlEditor.isIE)
value = Sys.Extended.UI.HtmlEditor.getRealAttributeIE(element, name, value);
if(name == "src" || name == "href")
value = value.replace(/(\(S\([A-Za-z0-9_]+\)\)\/)/, "");
break;
}
}
return value;
}
Sys.Extended.UI.HtmlEditor.enabledWordTags = [
"img",
"strong",
"p",
"b",
"i",
"u",
"a",
"h1",
"h2",
"h3",
"h4",
"h5",
"h6",
"table",
"tbody",
"tr",
"td",
"ul",
"ol",
"li",
"span",
"div",
"font",
"xml",
"del",
"ins",
"em",
"sub",
"sup",
"hr",
"br"
];
Sys.Extended.UI.HtmlEditor.cleanUp = function(html) {
var old_ret;
var ret = Sys.Extended.UI.HtmlEditor.Trim(html.replace(/[\x00-\x1F]+/g, " "))
.replace(/^[^\u0000]+?<html(?:[^>]*?)>/gi, "").replace(/<\/html(?:[^>]*?)>[^\u0000]*$/gi, "")
.replace(/<head(?:[^>]*?)>[^\u0000]*?<\/head(?:[^>]*?)>/gi, "")
.replace(/<body[^>]*?>([^\u0000]*?)<\/body(?:[^>]*?)>/gi, "$1")
.replace(/<\/?html(?:[^>]*?)>/gi, "")
.replace(/<\/?head(?:[^>]*?)>/gi, "")
.replace(/<\/?body(?:[^>]*?)>/gi, "")
.replace(/<!--(\w|\W)+?-->/ig, "") // remove comments
.replace(/(<[\/]?)(?:o|v|x|p|w|\?xml):(\w+)([^>]*?>)/ig, "$1$2$3") // remove prefixes
.replace(/<(IMAGEDATA)([^>]*?)>/ig, "<img$2>") // replace ImageData
.replace(/<p[^>]*><p> <\/p><\/p>/ig, "<br>") // remove empty P
.replace(/<p[^>]*?\/>/ig, "").replace(/<(p|div)[^>]*?> <\/(\1)[^>]*?>/ig, "").replace(/<(p|div)[^>]*?><\/(\1)[^>]*?>/ig, "");
// remove some attributes
do {
old_ret = ret;
ret = ret.replace(/<([^>]*)(?:class|size|lang|face|start|type|border|[ovwxp]:\w+)=(?:\'[^\']*\'|\"[^\"]*\"|[^> ]+)([^>]*)>/ig, "<$1$2>");
} while(ret != old_ret)
// remain enabled tags only
var div = document.createElement("div");
div.innerHTML = ret;
function diver(elem) {
var n = elem.childNodes.length;
for(var i = 0; i < elem.childNodes.length; i++) {
var child = elem.childNodes.item(i);
if(child.nodeType == 1) {
if(child.tagName.indexOf("/") >= 0) {
i--;
child.parentNode.removeChild(child);
} else {
var search = child.tagName.toLowerCase(),
found = false,
nn = Sys.Extended.UI.HtmlEditor.enabledWordTags.length;
for(var j = 0; j < nn; j++)
if(Sys.Extended.UI.HtmlEditor.enabledWordTags[j] == search) {
found = true;
break;
}
diver(child);
if(!found) {
i += child.childNodes.length;
while(child.firstChild)
child.parentNode.insertBefore(child.firstChild, child);
child.parentNode.removeChild(child);
i--;
} else {
var s_background_color = child.style.backgroundColor,
s_color = child.style.color;
child.style.cssText = "";
child.removeAttribute("style");
if(child.getAttribute("width") && child.getAttribute("width").length > 0)
child.style.width = child.getAttribute("width");
if(child.width && child.width.length > 0)
child.style.width = child.width;
child.width = "";
try {
child.removeAttribute("width");
} catch(e) { }
if(child.getAttribute("height") && child.getAttribute("height").length > 0)
child.style.height = child.getAttribute("height");
if(child.height && child.height.length > 0)
child.style.height = child.height;
child.height = "";
try {
child.removeAttribute("height");
} catch(e) { }
if(search == "table") {
child.style.borderLeftWidth = "1px";
child.style.borderLeftColor = "black";
child.style.borderLeftStyle = "solid";
child.style.borderTopWidth = "1px";
child.style.borderTopColor = "black";
child.style.borderTopStyle = "solid";
child.style.backgroundColor = s_background_color;
child.style.color = s_color;
}
if(search == "td") {
child.style.borderRightWidth = "1px";
child.style.borderRightColor = "black";
child.style.borderRightStyle = "solid";
child.style.borderBottomWidth = "1px";
child.style.borderBottomColor = "black";
child.style.borderBottomStyle = "solid";
child.style.backgroundColor = s_background_color;
child.style.color = s_color;
}
if(search == "font" || search == "span") {
child.style.backgroundColor = s_background_color;
child.style.color = s_color;
var attrs = child.attributes,
n = 0;
for(var m = 0; m < attrs.length; ++m) {
var a = attrs.item(m);
if(!a.specified)
continue;
n++;
}
if(n == 0 && child.style.cssText == "") {
i += child.childNodes.length;
while(child.firstChild)
child.parentNode.insertBefore(child.firstChild, child);
child.parentNode.removeChild(child);
i--;
}
}
}
}
}
}
}
diver(div);
ret = Sys.Extended.UI.HtmlEditor.Trim(div.innerHTML);
delete div;
ret = ret.replace(/<[\/]?(xml|del|ins)[^>]*?>/ig, "") // remove some tags (content should be remained)
.replace(/<(p|div)[^>]*?>/ig, "") // remove P, DIV tags (content should be remained) <br> is added
.replace(/<\/(p|div)[^>]*?>/ig, "<br>");
// remove empty style tags
do {
old_ret = ret;
ret = ret.replace(/<b><\/b>/ig, "").replace(/<i><\/i>/ig, "").replace(/<u><\/u>/ig, "").replace(/<strong><\/strong>/ig, "").replace(/<em><\/em>/ig, "").replace(/<sub><\/sub>/ig, "").replace(/<sup><\/sup>/ig, "");
ret = ret.replace(/<span[^>]*?><\/span>/ig, "").replace(/<span>([^<]+?)<\/span>/ig, "$1");
ret = ret.replace(/<font[^>]*?><\/font>/ig, "").replace(/<font>([^<]+?)<\/font>/ig, "$1");
} while(ret != old_ret)
// replace all Microsoft special characters
ret = ret.replace(/’/g, "'")
.replace(/‘/g, "'")
.replace(/–/g, "-")
.replace(/—/g, "-")
.replace(/…/g, "...")
.replace(/"/g, "\"")
.replace(/“/g, "\"")
.replace(/”/g, "\"")
.replace(//g, "")
.replace(/•/g, "")
.replace(/[ \s]+/g, " ").replace(/(( )+)/g, " "); // remove extra spaces
if(document.all)
ret = ret.replace(/^[\x00-\x1F]* /, "");
return ret;
};
Sys.Extended.UI.HtmlEditor.spanJoiner = function(element, doc, sFrom, sTo, nobr) {
var sIndex = 0,
sLength = element.childNodes.length;
if(typeof sFrom != "undefined" && sFrom != null)
sIndex = sFrom;
if(typeof sTo != "undefined" && sTo != null)
sLength = sTo;
for(var i = sIndex; i < sLength && i < element.childNodes.length; i++) {
var child = element.childNodes.item(i)
if(child.parentNode != element)
continue;
switch(child.nodeType) {
case 1: // Node.ELEMENT_NODE
if(child.childNodes.length == 0 && Sys.Extended.UI.HtmlEditor.isStyleTag(child.tagName) && child.tagName.toUpperCase() != "A" && !(child.className.length > 0 || (child.getAttribute("class") && child.getAttribute("class").length > 0)) && !Sys.Extended.UI.HtmlEditor.isTempElement(child)) {
element.removeChild(child);
i--;
sLength--;
continue;
}
if(child.tagName.toUpperCase() == "SPAN") {
while(child.childNodes.length == 1 && child.firstChild.nodeType == 1) {
if(child.firstChild.tagName.toUpperCase() == "SPAN" && !Sys.Extended.UI.HtmlEditor.isTempElement(child.firstChild)) {
var attrs = Sys.Extended.UI.HtmlEditor.differAttr(child.firstChild, []),
styles = Sys.Extended.UI.HtmlEditor.differStyle(child.firstChild),
oldSpan = child.firstChild,
chieldren = oldSpan.childNodes;
while(oldSpan.firstChild != null)
child.insertBefore(oldSpan.firstChild, oldSpan);
for(var j = 0; j < styles.length; j++) {
if(styles[j][1]) {
try {
if(child.style[styles[j][0]]) {
if(styles[j][0].toLowerCase().indexOf("color") >= 0) {
child.style[styles[j][0]] = styles[j][1];
} else {
try {
var sv = child.style[styles[j][0]];
child.style[styles[j][0]] = child.style[styles[j][0]] + " " + styles[j][1];
if(sv == child.style[styles[j][0]])
child.style[styles[j][0]] = styles[j][1];
} catch(e) {
child.style[styles[j][0]] = styles[j][1];
}
}
} else {
child.style[styles[j][0]] = styles[j][1];
}
} catch(ee) { }
}
}
for(var j = 0; j < attrs.length; j++)
if(attrs[j][1])
child.setAttribute(attrs[j][0], attrs[j][1]);
child.removeChild(oldSpan);
continue;
} else {
if(child.firstChild.tagName.toUpperCase() == "SPAN" && Sys.Extended.UI.HtmlEditor.isTempElement(child.firstChild)) {
var svv = child.firstChild;
child.parentNode.insertBefore(child.firstChild, child);
child.parentNode.removeChild(child);
child = svv;
}
}
break;
}
var tempArr = [],
nextChild = child.nextSibling;
while(!Sys.Extended.UI.HtmlEditor.isTempElement(child) && nextChild && i + 1 < sLength && (nextChild.nodeType == 3 || (nextChild.nodeType == 1 &&
(nextChild.tagName.toUpperCase() == "SPAN" || (nextChild.tagName.toUpperCase() == "BR") && typeof nobr == "undefined") &&
!Sys.Extended.UI.HtmlEditor.isTempElement(nextChild)))) {
if(nextChild.nodeType == 3) {
if(("" + nextChild.data + "").length == 0) {
nextChild.parentNode.removeChild(nextChild);
nextChild = child.nextSibling;
sLength--;
} else {
break;
}
} else {
if(nextChild.tagName.toUpperCase() == "BR") {
tempArr.push(nextChild);
nextChild = nextChild.nextSibling;
} else {
var attrs = Sys.Extended.UI.HtmlEditor.differAttr(child, [], nextChild),
styles = Sys.Extended.UI.HtmlEditor.differStyle(child, nextChild);
if(attrs.length == 0 && styles.length == 0 && child.className == nextChild.className) {
var n = tempArr.length;
for(var j = 0; j < n; j++) {
child.appendChild(tempArr[j]);
sLength--;
}
tempArr = [];
while(nextChild.firstChild)
child.appendChild(nextChild.firstChild);
nextChild.parentNode.removeChild(nextChild);
nextChild = child.nextSibling;
sLength--;
} else {
break;
}
}
}
}
if(!Sys.Extended.UI.HtmlEditor.isTempElement(child) && child.className.length == 0) {
var attrs = Sys.Extended.UI.HtmlEditor.differAttr(child, []),
styles = Sys.Extended.UI.HtmlEditor.differStyle(child);
if(attrs.length == 0 && styles.length == 0) {
i--;
sLength--;
while(child.firstChild) {
child.parentNode.insertBefore(child.firstChild, child);
sLength++;
}
child.parentNode.removeChild(child);
continue;
}
}
}
if(child.parentNode != null) {
if(child.childNodes.length == 0 && Sys.Extended.UI.HtmlEditor.isStyleTag(child.tagName) && child.tagName.toUpperCase() != "A" && !(child.className.length > 0 || (child.getAttribute("class") && child.getAttribute("class").length > 0)) && !Sys.Extended.UI.HtmlEditor.isTempElement(child)) {
element.removeChild(child);
i--;
sLength--;
continue;
} else {
Sys.Extended.UI.HtmlEditor.spanJoiner(child, doc);
}
}
break;
}
}
};
Sys.Extended.UI.HtmlEditor._styleTags = [
"strong",
"em",
"u",
"strike",
"s",
"span",
"font",
"b",
"sub",
"sup",
"a",
"i"
];
Sys.Extended.UI.HtmlEditor.isStyleTag = function(tag) {
if(!tag)
return false;
for(var i = 0; i < Sys.Extended.UI.HtmlEditor._styleTags.length; i++)
if(Sys.Extended.UI.HtmlEditor._styleTags[i].toLowerCase() == tag.toLowerCase())
return true;
return false;
};
Sys.Extended.UI.HtmlEditor.smartClassName = "MSIEparagraph";
Sys.Extended.UI.HtmlEditor.noContextMenuAttribute = "obout-no-contextmenu";
Sys.Extended.UI.HtmlEditor.isTempElement = function(el) {
if(el.id && el.id.length > 0 && el.id.indexOf(Sys.Extended.UI.HtmlEditor.smartClassName) >= 0)
return true;
return false;
};
Sys.Extended.UI.HtmlEditor.differAttr = function(element, pr, comp) {
var result = [],
parent = element.parentNode;
if(typeof comp != "undefined")
parent = comp;
if(!parent || !parent.tagName || !Sys.Extended.UI.HtmlEditor.isStyleTag(parent.tagName))
parent = null;
if(element.attributes)
for(var i = 0; i < element.attributes.length; i++) {
var attr = element.attributes[i],
brk = false;
for(var j = 0; j < pr.length; j++)
if(attr.name.toUpperCase() == pr[j].toUpperCase()) {
brk = true;
break;
}
if(brk)
continue;
if(attr.name.toUpperCase() == "STYLE")
continue;
if(attr.name.toUpperCase().substr(0, 4) == "_MOZ")
continue;
if(attr.specified)
if(parent && parent.attributes && parent.attributes[attr.name]) {
var pattr = parent.attributes[attr.name];
if(pattr)
if(attr.name != pattr.name || attr.value != pattr.value)
result.push([attr.name, attr.value]);
} else {
if(attr.name.toUpperCase() == "CLASS" && attr.value == "")
continue;
result.push([attr.name, attr.value]);
}
}
return result;
};
Sys.Extended.UI.HtmlEditor.differStyle = function(element, comp) {
var result = [],
parent = element.parentNode;
if(typeof comp != "undefined")
parent = comp;
if(!parent || !parent.tagName || !Sys.Extended.UI.HtmlEditor.isStyleTag(parent.tagName))
parent = null;
function _putStyle(i, _style) {
_style = "" + _style;
if(i.toLowerCase() == "textdecoration") {
var _arr = _style.split(" ");
for(var j = 0; j < _arr.length; j++)
result.push([i, Sys.Extended.UI.HtmlEditor.Trim(_arr[j])]);
} else {
result.push([i, _style]);
}
}
for(var i in element.style) {
if(i && typeof i == "string" && i != "accelerator") {
var ii = i;
if(!isNaN(parseInt(i))) {
if(!Sys.Extended.UI.HtmlEditor.isSafari)
continue;
ii = element.style[i];
}
var style = element.style[ii];
if(style && typeof style == "string" && style != "accelerator") {
if(parent && parent.style) {
var pstyle = parent.style[ii];
if(ii.toLowerCase() != "csstext" && ii.toLowerCase() != "length")
if(style != pstyle)
_putStyle(ii, style);
} else {
if(ii.toLowerCase() != "csstext" && ii.toLowerCase() != "length")
_putStyle(ii, style);
}
}
}
}
if(typeof comp != "undefined")
for(var i in parent.style) {
if(i && typeof i == "string" && i != "accelerator") {
var ii = i;
if(!isNaN(parseInt(i))) {
if(!Sys.Extended.UI.HtmlEditor.isSafari)
continue;
ii = element.style[i];
}
var style = parent.style[ii];
if(style && typeof style == "string" && style != "accelerator") {
var pstyle = element.style[ii];
if(i.toLowerCase() != "csstext" && ii.toLowerCase() != "length")
if(style != pstyle)
_putStyle(ii, style);
}
}
}
return result;
};
Sys.Extended.UI.HtmlEditor.brXHTML = function(str) {
return str.replace(/<br>/ig, "<br/>");
};
Sys.Extended.UI.HtmlEditor._needsClosingTag = function(el) {
var closingTags = " script style div span a del strong em u strike font b sub sup p iframe li ul ol placeholder textarea td tr ";
return (closingTags.indexOf(" " + el.tagName.toLowerCase() + " ") != -1);
};
Sys.Extended.UI.HtmlEditor._encodeText_ = function(str) {
return str.replace(/&/ig, "&").replace(/</ig, "<").replace(/>/ig, ">").replace(/\"/ig, """).replace(/\xA0/ig, " ");
};
Sys.Extended.UI.HtmlEditor._noNeedsClosingTag = function(el) {
var closingTags = " hr br ";
return (closingTags.indexOf(" " + el.tagName.toLowerCase() + " ") != -1);
};
Sys.Extended.UI.HtmlEditor.canBeInsideP = function(el, prize) {
if(el && el.style && el.style.display && el.style.display.toLowerCase() == "inline")
return true;
var name = el.tagName.toUpperCase();
if(name.length == 2)
if(name.substr(0, 1) == "H" && parseInt(name.substr(1, 1)) > 0)
return false;
switch(name) {
case "TBODY":
case "TR":
case "TD":
if(typeof prize != "undefined") {
var par = el.parentNode;
while(par && par.tagName && par.tagName.toUpperCase() != "TABLE")
par = par.parentNode;
if(par.tagName.toUpperCase() == "TABLE" && par.style && par.style.display && par.style.display.toLowerCase() == "inline")
return true;
}
case "P":
case "PRE":
case "TABLE":
case "OL":
case "UL":
case "LI":
case "HR":
case "DIV":
case "BLOCKQUOTE":
case "FORM":
case "FIELDSET":
case "LEGEND":
return false;
default:
return true;
}
};
Sys.Extended.UI.HtmlEditor.convertAlign = function(aval) {
var value, n;
try {
n = parseInt(aval) - 1;
} catch(e) {
return aval;
}
switch(n) {
case 1:
value = "left";
break;
case 2:
value = "right";
break;
case 3:
value = "texttop";
break;
case 4:
value = "absmiddle";
break;
case 5:
value = "baseline";
break;
case 6:
value = "absbottom";
break;
case 7:
value = "bottom";
break;
case 8:
value = "middle";
break;
case 9:
value = "top";
break;
default:
value = aval.replace(/\"/g, """);
}
return value;
};
Sys.Extended.UI.HtmlEditor.getHTML = function(root, outputRoot, must) {
try {
if(typeof must == "undefined")
if(!outputRoot && root.nodeType == 1) {
return root.innerHTML;
} else {
if(outputRoot && root.nodeType == 1 && Sys.Extended.UI.HtmlEditor.isIE)
return root.outerHTML;
}
} catch(e) { }
var html = new Sys.Extended.UI.HtmlEditor.jsDocument(true);
Sys.Extended.UI.HtmlEditor._getHTML_(html, root, outputRoot);
return html.toString();
};
Sys.Extended.UI.HtmlEditor._getHTML_ = function(html, root, outputRoot, must) {
switch(root.nodeType) {
case 1: // Node.ELEMENT_NODE
case 11: // Node.DOCUMENT_FRAGMENT_NODE
if(root.tagName && root.tagName.indexOf("/") >= 0) {
if(Sys.Extended.UI.HtmlEditor.isIE) {
var tag = root.tagName.toLowerCase().substr(root.tagName.indexOf("/") + 1),
prev = root.previousSibling;
if(tag == "embed")
return;
while(prev != null) {
if(prev.nodeType == root.nodeType && prev.tagName && prev.tagName.toLowerCase() == tag) {
html.append("</teo" + Sys.Extended.UI.HtmlEditor.smartClassName + ":" + root.tagName.toLowerCase().substr(root.tagName.indexOf("/") + 1) + ">");
return;
}
prev = prev.previousSibling;
}
}
return;
}
var closed, noSlash, i;
if(outputRoot && root.tagName.length > 0) {
var tag = root.tagName.toLowerCase();
closed = (!(root.hasChildNodes() || Sys.Extended.UI.HtmlEditor._needsClosingTag(root)));
noSlash = true;
var scope = "";
if(Sys.Extended.UI.HtmlEditor.isIE && root.scopeName && typeof root.scopeName != "undefined")
scope = (root.scopeName.toUpperCase() == "HTML") ? "" : (root.scopeName + ":");
if(Sys.Extended.UI.HtmlEditor.isIE && (closed || tag == "placeholder") && !Sys.Extended.UI.HtmlEditor._noNeedsClosingTag(root) && tag != "embed") {
var next = root.nextSibling;
while(next != null) {
if(next.nodeType == root.nodeType && next.tagName) {
var nextTagName = next.tagName;
if(nextTagName.indexOf("/") >= 0)
if(nextTagName.toLowerCase().substr(nextTagName.indexOf("/") + 1) == tag) {
closed = false;
noSlash = false;
break;
}
}
next = next.nextSibling;
}
}
if(!Sys.Extended.UI.HtmlEditor.canBeInsideP(root))
html.append("\n");
html.append("<" + ((!closed && !noSlash) ? "teo" + Sys.Extended.UI.HtmlEditor.smartClassName + ":" : scope) + tag);
if(Sys.Extended.UI.HtmlEditor.isIE && root.name && root.name.length > 0)
html.append(" name=\"" + root.name.replace(/\"/g, """) + '"');
if(Sys.Extended.UI.HtmlEditor.isIE && root.value && root.value.length > 0 && tag != "textarea")
html.append(" value=\"" + root.value.replace(/\"/g, """) + '"');
if(Sys.Extended.UI.HtmlEditor.isIE && root.className && root.className.length > 0)
html.append(" class=\"" + root.className.replace(/\"/g, """) + '"');
if(Sys.Extended.UI.HtmlEditor.isIE && root.align && root.align.length > 0)
html.append(" align=\"" + root.align.replace(/\"/g, """) + '"');
if(Sys.Extended.UI.HtmlEditor.isIE && root.color && root.color.length > 0)
html.append(" color=\"" + root.color.replace(/\"/g, """) + '"');
if(Sys.Extended.UI.HtmlEditor.isIE && root.size && root.size.length > 0 && root.size != "+0")
html.append(" size=\"" + root.size.replace(/\"/g, """) + '"');
if(Sys.Extended.UI.HtmlEditor.isIE && root.shape && root.shape.length > 0)
html.write(" shape" + '="' + root.shape.replace(/\"/g, """) + '"');
if(Sys.Extended.UI.HtmlEditor.isIE && root.coords && root.coords.length > 0)
html.write(" coords" + '="' + root.coords.replace(/\"/g, """) + '"');
var attrs = root.attributes,
cssForSafari = null;
for(i = 0; i < attrs.length; ++i) {
var a = attrs.item(i);
if(!a.specified)
continue;
var name = a.name.toLowerCase();
if(name.substr(0, 4) == "_moz")
// Mozilla reports some special attributes
// here we don't need them.
continue;
if(name == "teoalign")
continue;
var value;
if(name != 'style') {
if(name == 'width') {
value = root.width;
if(Sys.Extended.UI.HtmlEditor.isIE && value == 0) {
var n_value = 0;
root.outerHTML.replace(new RegExp("^(?:<[^>]*?width=)([\\d]+)", "ig"), function(p0, p1) { n_value = p1; });
if(value != n_value)
value = n_value;
}
} else
if(name == 'height') {
value = root.height;
if(Sys.Extended.UI.HtmlEditor.isIE && value == 0) {
var n_value = 0;
root.outerHTML.replace(new RegExp("^(?:<[^>]*?height=)([\\d]+)", "ig"), function(p0, p1) { n_value = p1; });
if(value != n_value)
value = n_value;
}
} else
if(Sys.Extended.UI.HtmlEditor.isIE && name == 'name' && root.name && root.name.length > 0)
continue;
else
if(Sys.Extended.UI.HtmlEditor.isIE && name == 'value' && root.value && root.value.length > 0)
continue;
else
if(Sys.Extended.UI.HtmlEditor.isIE && name == 'align' && root.align && root.align.length > 0)
continue;
else
if(Sys.Extended.UI.HtmlEditor.isIE && name == 'class' && root.className && root.className.length > 0)
continue;
else
if(Sys.Extended.UI.HtmlEditor.isIE && name == 'color' && root.color && root.color.length > 0)
continue;
else
if(Sys.Extended.UI.HtmlEditor.isIE && name == 'size' && root.size && root.size.length > 0)
continue;
else
if(Sys.Extended.UI.HtmlEditor.isIE && name == 'shape' && root.shape && root.shape.length > 0)
continue;
else
if(Sys.Extended.UI.HtmlEditor.isIE && name == 'coords' && root.coords && root.coords.length > 0)
continue;
else {
if(tag == "embed" && name == "align" && (Sys.Extended.UI.HtmlEditor.isIE)) {
value = Sys.Extended.UI.HtmlEditor.convertAlign(a.value);
} else {
value = a.value;
if(Sys.Extended.UI.HtmlEditor.isSafari && name == "class")
if(/apple-style/ig.test(value))
continue;
if(name == "src" || name == "href") {
if(Sys.Extended.UI.HtmlEditor.isIE)
value = Sys.Extended.UI.HtmlEditor.getRealAttributeIE(root, name, value);
value = value.replace(/(\(S\([A-Za-z0-9_]+\)\)\/)/, "");
}
value = value.replace(/\"/g, """);
}
}
} else {
if(Sys.Extended.UI.HtmlEditor.isSafari)
cssForSafari = a.value;
continue;
}
var qchar = "\"";
if(("" + value + "").indexOf("\"") >= 0)
qchar = "'";
if(name != null)
html.append(" " + name + '=' + qchar + value + qchar);
}
if(root.style.cssText.length > 0 || cssForSafari != null) {
var name = "style",
re1 = /(url\((?:[^\)]*)\))/ig,
urls = [];
function f2($0, $1) {
urls.push($1);
}
var value = ((cssForSafari != null) ? cssForSafari : root.style.cssText).toLowerCase();
value.replace(re1, f2);
var times = 0;
function f3() {
var temp = urls[times];
times++;
return temp;
}
value = Sys.Extended.UI.HtmlEditor.tryReplaceRgb(value.replace(re1, f3)).replace(/(font-weight\s*:\s*)(700)/ig, "$1bold")
.replace(/([\s]*-moz-[^;]*[;][\s]*)/ig, "").replace(/(-moz-.*)$/i, "")
.replace(/(background-position: 0% 0%[;]*[\s]*)/ig, "");
if(Sys.Extended.UI.HtmlEditor.isSafari) {
function repSaf($0, $1, $2, $3) {
return $1 + $2.replace(/(,)/g, "") + $3;
}
value = value.replace(/(text-decoration:)([^;$]+)([;$])/ig, repSaf);
}
if(Sys.Extended.UI.HtmlEditor.isSafari || Sys.Extended.UI.HtmlEditor.isOpera) {
function repSafOp($0, $1, $2, $3) {
return $1 + $2.replace(/(['"])/g, "") + $3;
}
value = value.replace(/(font-family:)([^;]+)([;]*)/ig, repSafOp);
}
if(value.length > 0) {
var qchar = "\"";
if(("" + value + "").indexOf("\"") >= 0)
qchar = "'";
html.append(" " + name + '=' + qchar + value + qchar);
}
}
html.append(closed ? " />" : ">");
if(tag == "br")
html.append("\n");
}
if(root.tagName && root.tagName.toUpperCase() == "SCRIPT")
html.append(root.text);
if(root.tagName && root.tagName.toUpperCase() == "STYLE") {
html.append(root.innerHTML);
} else {
for(i = root.firstChild; i; i = i.nextSibling)
Sys.Extended.UI.HtmlEditor._getHTML_(html, i, true)
}
if(outputRoot && root.tagName.length > 0 && !closed && noSlash)
html.append("</" + scope + root.tagName.toLowerCase() + ">");
break;
case 3: // Node.TEXT_NODE
html.append(Sys.Extended.UI.HtmlEditor._encodeText_("" + root.data + ""));
break;
case 8: // Node.COMMENT_NODE
if(root.length > 0)
html.append("<!--" + root.data + "-->");
else // IE bug tricking (negative lengths happen there)
html.append("<!---->");
break;
}
};
Sys.Extended.UI.HtmlEditor.RemoveContextMenu = function() {
var editor = this;
var hhh = editor._contextElement.parentNode.removeChild(editor._contextElement);
if(hhh)
delete hhh;
editor._contextElement = null;
editor._contextTable = null;
if(editor.__saved_range__) {
editor.__saved_range__.select();
editor.__saved_range__ = null;
}
};
Sys.Extended.UI.HtmlEditor.contentEditable = function(el, prize) {
while(el != null) {
try {
var mean = null;
if(el.contentEditable != null && typeof el.contentEditable != "undefined" && !(Sys.Extended.UI.HtmlEditor.isSafari || Sys.Extended.UI.HtmlEditor.isOpera)) {
if(!el.contentEditable || el.contentEditable == "false")
mean = false;
else
mean = true;
} else {
var value = el.getAttribute("contenteditable");
if(typeof value == "boolean") {
mean = value;
} else {
if(typeof value == "string" && value.toLowerCase() == "false")
mean = false;
}
}
if(mean != null && typeof mean == "boolean")
if(!mean)
return el;
} catch(ex) { }
if(typeof prize != "undefined" && prize)
return null;
if(el.tagName != null && typeof el.tagName != "undefined" && (el.tagName.toUpperCase() == "BODY" || el.tagName.toUpperCase() == "HTML"))
break;
el = el.parentNode;
}
return null;
};
Sys.Extended.UI.HtmlEditor.getSelParent = function(editor) {
var sel = editor._getSelection(),
range = editor._createRange(sel),
parent = null;
if(Sys.Extended.UI.HtmlEditor.isIE) {
if(sel.type.toLowerCase() == "control")
parent = range.item(0);
else
parent = editor._getParent(range);
} else {
parent = editor._getParent(range);
if(parent.nodeType != 3 && range.startContainer == range.endContainer) {
var p = parent;
parent = parent.childNodes.item(range.startOffset);
if(parent == null)
parent = p;
}
}
return parent;
};
Sys.Extended.UI.HtmlEditor.__getIndex = function(el) {
var ind = 0;
if(el.parentNode)
for(; ind < el.parentNode.childNodes.length; ind++)
if(el.parentNode.childNodes.item(ind) == el)
break;
return ind;
};
Sys.Extended.UI.HtmlEditor.isInlineElement = function(el) {
if(el.nodeType == 3)
return true;
if(el.nodeType != 1)
return false;
if(!el.tagName || el.tagName.length == 0)
return false;
if(el && el.style && el.style.display && el.style.display.toLowerCase() == "inline")
return true;
var name = el.tagName.toUpperCase();
if(name.length == 2)
if(name.substr(0, 1) == "H" && parseInt(name.substr(1, 1)) > 0)
return false;
switch(name) {
case "BR":
case "TBODY":
case "TR":
case "TD":
case "P":
case "PRE":
case "TABLE":
case "OL":
case "UL":
case "LI":
case "HR":
case "DIV":
case "BLOCKQUOTE":
case "FORM":
case "FIELDSET":
case "LEGEND":
return false;
default:
return true;
}
};
Sys.Extended.UI.HtmlEditor.capLock = function(e) {
var kc = e.charCode,
sk = e.shiftKey ? e.shiftKey : ((kc == 16) ? true : false);
if(((kc >= 65 && kc <= 90) && !sk) || ((kc >= 97 && kc <= 122) && sk))
return true;
else
return false;
};
Sys.Extended.UI.HtmlEditor.operateAnchors = function(editor, _doc, _prize) {
var aList = _doc.getElementsByTagName("A"),
ret = false;
for(var i = 0; i < aList.length; i++) {
var a = aList[i];
if(a.name && a.name.length > 0) {
var imgToDelete = [];
for(var j = 0; j < a.childNodes.length; j++) {
var node = a.childNodes.item(j);
if(node.nodeType == 1 && node.tagName && node.tagName.toUpperCase() == "IMG" && node.src == editor._editPanel.get_imagePath_anchor()) {
imgToDelete.push(node);
ret = true;
}
}
while(imgToDelete.length > 0)
a.removeChild(imgToDelete.pop());
if(!_prize) {
var img = _doc.createElement("IMG");
img.title = a.name;
img.src = editor._editPanel.get_imagePath_anchor();
img.setAttribute(editor.noContextMenuAttributeName(), "yes");
a.appendChild(img);
}
}
}
return ret;
};
Sys.Extended.UI.HtmlEditor.operatePlaceHolders = function(editor, _doc, _prize) {
var ret = false;
if(_prize) {
var tempCollection = _doc.getElementsByTagName("IMG");
var aList = [];
for(var i = 0; i < tempCollection.length; i++)
aList.push(tempCollection[i]);
for(var i = 0; i < aList.length; i++) {
var a = aList[i],
dum = a.getAttribute("dummytag");
if(dum && dum.length > 0 && dum.toLowerCase() == "placeholder") {
var ph = _doc.createElement("PLACEHOLDER"),
title = a.title;
if(title == null || typeof title == "undefined")
title = a.getAttribute("title");
ph.name = title;
ph.setAttribute("name", title);
a.parentNode.insertBefore(ph, a);
a.parentNode.removeChild(a);
ret = true;
}
}
} else {
var tempCollection = _doc.getElementsByTagName("PLACEHOLDER");
var aList = [];
for(var i = 0; i < tempCollection.length; i++)
aList.push(tempCollection[i]);
for(var i = 0; i < aList.length; i++) {
var a = aList[i],
nd = true;
try {
if(a.childNodes.length > 0)
nd = false;
} catch(ex) { }
if(nd) {
var name = a.name;
if(name == null || typeof name == "undefined")
name = a.getAttribute("name");
var img = _doc.createElement("IMG");
img.title = name;
img.src = editor._editPanel.get_imagePath_placeHolder();
img.setAttribute("dummytag", "placeholder");
img.setAttribute("title", name);
a.parentNode.insertBefore(img, a);
a.parentNode.removeChild(a);
}
}
}
return ret;
};
Sys.Extended.UI.HtmlEditor.inspectForShadows = function(el) {
var aList = el.getElementsByTagName("IMG");
for(var i = 0; i < aList.length; i++) {
if(aList[i].getAttribute(Sys.Extended.UI.HtmlEditor.attachedIdAttribute) && aList[i].getAttribute(Sys.Extended.UI.HtmlEditor.attachedIdAttribute).length > 0) {
try {
if(Sys.Extended.UI.HtmlEditor.isIE)
$removeHandler(aList[i], "dragstart", Sys.Extended.UI.HtmlEditor.stopDrag);
else
$removeHandler(aList[i], "draggesture", Sys.Extended.UI.HtmlEditor.stopDrag);
} catch(e) { }
if(Sys.Extended.UI.HtmlEditor.isIE)
$addHandler(aList[i], "dragstart", Sys.Extended.UI.HtmlEditor.stopDrag);
else
$addHandler(aList[i], "draggesture", Sys.Extended.UI.HtmlEditor.stopDrag);
}
}
};
Sys.Extended.UI.HtmlEditor.attachedIdAttribute = "obout-attached-id";
Sys.Extended.UI.HtmlEditor.stopDrag = function(ev) {
if(ev)
ev.stopPropagation();
ev.preventDefault();
return false;
};
Sys.Extended.UI.HtmlEditor.replacingRules =
[
["strong", "font-weight", "bold"],
["b", "font-weight", "bold"],
["strong", "font-weight", "700"],
["em", "font-style", "italic"],
["i", "font-style", "italic"],
["u", "text-decoration", "underline"],
["strike", "text-decoration", "line-through"]
];
Sys.Extended.UI.HtmlEditor.replaceOldTags = function(root, editor) {
var innerHTML = root.innerHTML,
need = false;
for(var j = 0; j < Sys.Extended.UI.HtmlEditor.replacingRules.length; j++) {
var reg = new RegExp("<" + Sys.Extended.UI.HtmlEditor.replacingRules[j][0] + "[\s>]", "ig");
if(reg.test(innerHTML)) {
need = true;
break;
}
}
if(!need)
if(!(/<font[\s>]/ig.test(innerHTML)))
return;
for(var i = 0; i < root.childNodes.length; i++) {
var child = root.childNodes.item(i);
if(child.nodeType == 1) {
var found = null,
childTagName = child.tagName.toLowerCase();
for(var j = 0; j < Sys.Extended.UI.HtmlEditor.replacingRules.length; j++)
if(Sys.Extended.UI.HtmlEditor.replacingRules[j][0].toLowerCase() == childTagName) {
found = Sys.Extended.UI.HtmlEditor.replacingRules[j];
break;
}
if(found) {
var span = editor._doc.createElement("SPAN");
span.style["cssText"] = child.style["cssText"];
if(Sys.Extended.UI.HtmlEditor.isIE)
span.style[found[1]] = found[2];
else
span.style[found[1].replace(/\-(\w)/g, function(strMatch, p1) { return p1.toUpperCase(); })] = found[2];
while(child.firstChild)
span.appendChild(child.firstChild);
root.insertBefore(span, child);
root.removeChild(child);
child = span;
} else {
if(childTagName == "font") {
var span = editor._doc.createElement("SPAN"),
save = child.size;
span.style["cssText"] = child.style["cssText"];
if(child.color)
span.style.color = child.color;
if(child.face)
span.style.fontFamily = child.face;
while(child.firstChild)
span.appendChild(child.firstChild);
root.insertBefore(span, child);
root.removeChild(child);
if(save) {
var font = editor._doc.createElement("FONT");
font.size = save;
root.insertBefore(font, span);
if(span.style["cssText"].length > 0) {
font.appendChild(span);
child = span;
} else {
while(span.firstChild)
font.appendChild(span.firstChild);
root.removeChild(span);
child = font;
}
} else {
child = span;
}
}
}
Sys.Extended.UI.HtmlEditor.replaceOldTags(child, editor);
}
}
};
Sys.Extended.UI.HtmlEditor.getStyle = function(oElm, strCssRule) {
var strValue = "";
if(oElm.nodeType == 1) {
if(oElm.ownerDocument && oElm.ownerDocument.defaultView && oElm.ownerDocument.defaultView.getComputedStyle) {
strValue = oElm.ownerDocument.defaultView.getComputedStyle(oElm, "").getPropertyValue(strCssRule);
} else if(oElm.currentStyle) {
try {
strCssRule = strCssRule.replace(/\-(\w)/g, function(strMatch, p1) { return p1.toUpperCase(); });
strValue = oElm.currentStyle[strCssRule];
} catch(ex) {
strValue = oElm.style[strCssRule];
}
} else {
strValue = oElm.style[strCssRule];
}
}
return strValue;
};
Sys.Extended.UI.HtmlEditor._Marker = function(editor, rng, sel) {
if(Sys.Extended.UI.HtmlEditor.isIE) {
this._nArr = Sys.Extended.UI.HtmlEditor.getNames(editor._doc.body);
this._save = editor._doc.body.innerHTML;
this._tree = null;
if(sel.type.toLowerCase() == "control") {
try {
var el = rng.item(0);
this._tree = [];
while(el && (el.nodeType == 3 || !el.tagName || el.tagName.toUpperCase() != "BODY")) {
var n = 0;
while(el.previousSibling) {
n++;
el = el.previousSibling;
}
this._tree.push(n);
el = el.parentNode;
}
} catch(e) { }
} else {
this._offsetLeft = rng.offsetLeft;
this._offsetTop = rng.offsetTop;
}
} else {
if(Sys.Extended.UI.HtmlEditor.isOpera)
this._save = Sys.Extended.UI.HtmlEditor.Trim(editor._doc.body.innerHTML);
else
this._save = editor._doc.body.cloneNode(true);
this._tree = [];
this._offset = 0;
try {
var el = rng.startContainer;
this._offset = rng.startOffset;
if(el && el.nodeType == 1 && el.tagName.toUpperCase() == "HTML") {
el = editor._doc.body;
setTimeout(function() {
try {
sel = editor._getSelection();
rng = editor._createRange();
editor._removeAllRanges(sel);
rng.setStart(el, 0);
rng.setEnd(el, 0);
editor._selectRange(sel, rng);
} catch(e) { }
}, 0);
}
while(el && el.nodeType && (el.nodeType == 3 || !el.tagName || el.tagName.toUpperCase() != "BODY")) {
var n = 0;
while(el.previousSibling) {
n++;
if(Sys.Extended.UI.HtmlEditor.isOpera)
if(el.nodeType == 3 && el.previousSibling != null && el.previousSibling.nodeType == 3)
n--;
el = el.previousSibling;
}
this._tree.push(n);
el = el.parentNode;
}
} catch(e) { }
}
};
Sys.Extended.UI.HtmlEditor.__stackMaxSize = 30;
Sys.Extended.UI.HtmlEditor.getNames = function(el) {
var aList = el.all,
mArr = [],
nArr = []
for(var i = 0; i < aList.length; i++) {
var a = aList[i];
if(a.name && a.name.length > 0) {
var tag = a.tagName,
coll = el.getElementsByTagName(tag),
n = 0;
for(var j = 0; j < coll.length; j++)
if(coll[j] == a) {
n = j;
break;
}
nArr[tag] = n;
mArr.push([tag, nArr[tag], a.name]);
}
}
return mArr;
};
Sys.Extended.UI.HtmlEditor.setNames = function(el, mArr) {
for(var i = 0; i < mArr.length; i++)
if(el.getElementsByTagName(mArr[i][0]).length > mArr[i][1])
el.getElementsByTagName(mArr[i][0])[mArr[i][1]].name = mArr[i][2];
};
Sys.Extended.UI.HtmlEditor._lookChild = function(root, seek) {
for(var i = 0; i < root.childNodes.length; i++) {
var child = root.childNodes.item(i);
if(child == seek)
return i;
if(child.nodeType == 1)
if(Sys.Extended.UI.HtmlEditor._lookChild(child, seek) >= 0)
return i;
}
return -1;
};
Sys.Extended.UI.HtmlEditor.getHrefsText = function(txt) {
var result = []
function regRepl(p0, p1, p2, p3, p4, p5, p6, p7) {
var tag = p1.replace(/^<([^\s>]+)/, "$1"),
insert = true,
i = 0;
for(; i < result.length; i++)
if(result[i][0] == tag) {
insert = false;
break;
}
if(insert)
result[i] = [tag];
result[i].push(p5);
};
var reg = new RegExp("(<[^\\s><]+)([^><]*?)(href=)(\"|')([^\\4]*?)(\\4)((?:[^><]*?)>)", "ig");
txt.replace(reg, regRepl);
return result;
};
Sys.Extended.UI.HtmlEditor.setHrefsText = function(el, mArr) {
for(var j = 0; j < mArr.length; j++) {
var aList = el.getElementsByTagName(mArr[j][0]),
k = 1;
for(var i = 0; i < aList.length; i++) {
if(!aList[i].href)
continue;
if(mArr[j][k] && mArr[j][k].length > 0) {
var trickIE;
if(Sys.Extended.UI.HtmlEditor.isIE)
trickIE = aList[i].innerHTML;
aList[i].href = mArr[j][k].replace(/&/ig, "&");
if(Sys.Extended.UI.HtmlEditor.isIE)
aList[i].innerHTML = trickIE;
}
k++;
}
}
};
Sys.Extended.UI.HtmlEditor.getImagesText = function(txt) {
var mArr = [];
function regRepl(p0, p1, p2, p3, p4, p5) {
mArr.push(p3);
return p0;
}
txt.replace(/(<img(?:.*?))(src=")(.*?)(")((?:.*?)>)/ig, regRepl);
return mArr;
};
Sys.Extended.UI.HtmlEditor.setImagesText = function(el, mArr) {
var aList = el.getElementsByTagName("IMG"),
k = 0;
for(var i = 0; i < aList.length; i++) {
if(!aList[i].src)
continue;
if(mArr[k] && mArr[k].length > 0)
aList[i].src = mArr[k].replace(/&/ig, "&");
k++;
}
};
Sys.Extended.UI.HtmlEditor.canHaveChildren = function(elem) {
if(Sys.Extended.UI.HtmlEditor.isIE)
return elem.canHaveChildren;
else
return !/^(area|base|basefont|col|frame|hr|img|br|input|isindex|link|meta|param)$/.test(elem.tagName.toLowerCase());
};
Sys.Extended.UI.HtmlEditor._setCursor = function(el1, editor) {
var el = el1;
if(Sys.Extended.UI.HtmlEditor.isIE) {
var sel = editor._getSelection(),
range = editor._createRange(sel);
if(sel.type.toLowerCase() == "control") {
range.remove(0);
sel.empty();
range = editor._createRange();
}
var isText = (el.nodeType == 3),
span;
if(isText) {
span = editor._doc.createElement("SPAN");
span.innerHTML = " ";
el.parentNode.insertBefore(span, el);
el = span;
}
var location = $common.getLocation(el),
_left = location.x, _top = location.y;
if(isText)
span.parentNode.removeChild(span);
try {
range.moveToPoint(_left, _top);
} catch(e) { }
range.select();
} else {
var sel = editor._getSelection(),
range = editor._createRange();
range.setStart(el, 0);
range.setEnd(el, 0);
editor._removeAllRanges(sel);
editor._selectRange(sel, range);
editor.focusEditor();
}
};
Sys.Extended.UI.HtmlEditor.myClone = function(el, doc, prize) {
var ela;
if(Sys.Extended.UI.HtmlEditor.isIE && el.tagName && (el.tagName.toUpperCase() == "EMBED" || el.tagName.toUpperCase() == "OBJECT")) {
var div = doc.createElement("DIV");
try {
div.innerHTML = el.outerHTML;
ela = div.firstChild;
} catch(e) {
ela = el;
}
delete div;
} else {
ela = el.cloneNode(prize);
}
return ela;
};
Sys.Extended.UI.HtmlEditor.unStyle = function(el) {
var _prn = (el.parentNode != null && typeof el.parentNode != "undefined") ? el.parentNode : null;
if(_prn) {
var _fnd = null;
while(_prn && _prn.tagName && _prn.tagName.toUpperCase() != "BODY" && Sys.Extended.UI.HtmlEditor.isStyleTag(_prn.tagName) &&
(_prn.tagName.toUpperCase() != "A")) {
_fnd = _prn;
_prn = _prn.parentNode;
}
if(_fnd) {
function diver(add, el, rpr, before, prize) {
var par = rpr.cloneNode(false);
if(add)
if(add.push && typeof add.push == "function")
for(var iii = 0; iii < add.length; iii++)
par.appendChild(add[iii]);
else
par.appendChild(add);
if(prize) {
par.appendChild(el);
} else {
while(el) {
var elSibling = before ? el.previousSibling : el.nextSibling;
if(el.nodeType == 1 || (el.nodeType == 3 && Sys.Extended.UI.HtmlEditor.Trim("" + el.data + "").length > 0)) {
if(el.nodeType == 1)
if(el.tagName && Sys.Extended.UI.HtmlEditor.isStyleTag(el.tagName) && el.childNodes.length == 0 && !Sys.Extended.UI.HtmlEditor.isTempElement(el))
el = null;
if(el) {
if(par.childNodes.length == 0 || !before)
par.appendChild(el);
else
par.insertBefore(el, par.firstChild);
}
}
el = elSibling;
}
}
if(par.childNodes.length == 0) {
delete par;
par = null;
} else if(par.childNodes.length == 1 && par.firstChild.nodeType == 3 && ("" + par.firstChild.data + "").length == 0) {
delete par;
par = null;
} else {
if(!prize && par.tagName && Sys.Extended.UI.HtmlEditor.isStyleTag(par.tagName) && (par.tagName.toUpperCase() != "A") && !Sys.Extended.UI.HtmlEditor.isTempElement(par)) {
var elNumber = par.childNodes.length;
for(var cnt = 0; cnt < par.childNodes.length; cnt++) {
var inn = par.childNodes.item(cnt);
if(inn.nodeType == 1 && inn.tagName && !Sys.Extended.UI.HtmlEditor.isStyleTag(inn.tagName) &&
(inn.tagName.toUpperCase() == "BR" || inn.tagName.toUpperCase() == "TABLE" ||
Sys.Extended.UI.HtmlEditor.isTempElement(inn)))
elNumber--;
}
if(elNumber == 0) {
var parr = [];
while(par.firstChild) {
var inn = par.removeChild(par.firstChild);
parr.push(inn);
}
par = parr;
}
}
}
if(rpr == _fnd) {
return par;
} else {
if(!prize)
return diver(par, before ? rpr.previousSibling : rpr.nextSibling, rpr.parentNode, before, prize);
else
return diver(null, par, rpr.parentNode, before, prize);
}
};
_prn = el.parentNode;
if(el.previousSibling == null && el.nextSibling == null &&
_prn && _prn.tagName && _prn.tagName.toUpperCase() != "BODY" && Sys.Extended.UI.HtmlEditor.isStyleTag(_prn.tagName) &&
Sys.Extended.UI.HtmlEditor.differAttr(_prn, ["class", "color", "face", "size"]).length > 0)
el = _prn;
var p1 = diver(null, el.previousSibling, el.parentNode, true, false),
p2 = diver(null, el.nextSibling, el.parentNode, false, false);
var par = _fnd.parentNode;
if(p1) {
if(p1.push && typeof p1.push == "function") {
for(var iii = 0; iii < p1.length; iii++)
par.insertBefore(p1[iii], _fnd);
} else {
par.insertBefore(p1, _fnd);
}
}
if(el.nodeType == 1 && el.tagName &&
(el.tagName.toUpperCase() == "BR" || el.tagName.toUpperCase() == "TABLE" ||
Sys.Extended.UI.HtmlEditor.isTempElement(el))) {
par.insertBefore(el, _fnd);
} else {
var p3 = diver(null, el, el.parentNode, false, true);
par.insertBefore(p3, _fnd);
}
if(p2) {
if(p2.push && typeof p2.push == "function") {
for(var iii = 0; iii < p2.length; iii++)
par.insertBefore(p2[iii], _fnd);
} else {
par.insertBefore(p2, _fnd);
}
}
par.removeChild(_fnd);
}
}
};
Sys.Extended.UI.HtmlEditor.isTempElement = function(el) {
if(el.id && el.id.length > 0 && el.id.indexOf(Sys.Extended.UI.HtmlEditor.smartClassName) >= 0)
return true;
return false;
};
Sys.Extended.UI.HtmlEditor._moveTagsUp = function(lBound, rBound) {
function _dive(next) {
if(!Sys.Extended.UI.HtmlEditor.isInlineElement(next) || next.nodeType == 3) {
Sys.Extended.UI.HtmlEditor.unStyle(next);
} else if(next.tagName && Sys.Extended.UI.HtmlEditor.isStyleTag(next.tagName) && (next.tagName.toUpperCase() != "A") && !Sys.Extended.UI.HtmlEditor.isTempElement(next)) {
var nnn = next.firstChild;
while(nnn != null) {
var nnnNext = nnn.nextSibling;
_dive(nnn);
nnn = nnnNext;
}
}
}
var next = lBound;
while(next != null && next != rBound) {
var nextSibling = next.nextSibling;
_dive(next);
next = nextSibling;
}
};
Sys.Extended.UI.HtmlEditor._commonTotalParent = function(first, last) {
var ret = null,
par = first.parentNode,
fst = first;
while(par) {
if(par.tagName && !Sys.Extended.UI.HtmlEditor.isStyleTag(par.tagName)) {
var indexLast = Sys.Extended.UI.HtmlEditor._lookChild(par, last);
if(indexLast >= 0) {
var indexFirst = 0;
for(var i = 0; i < par.childNodes.length; i++)
if(par.childNodes.item(i) == fst) {
indexFirst = i;
break;
}
return { parent: par, indexFirst: indexFirst, indexLast: indexLast };
}
}
fst = par;
par = par.parentNode;
}
return ret;
};
Sys.Extended.UI.HtmlEditor._commonParent = function(first, last) {
var ret = null,
par = first.parentNode,
fst = first;
while(par && par.tagName.toUpperCase() != "BODY" && Sys.Extended.UI.HtmlEditor.isStyleTag(par.tagName)) {
var indexLast = Sys.Extended.UI.HtmlEditor._lookChild(par, last);
if(indexLast >= 0) {
var indexFirst = 0;
for(var i = 0; i < par.childNodes.length; i++) {
if(par.childNodes.item(i) == fst) {
indexFirst = i;
break;
}
}
return { parent: par, indexFirst: indexFirst, indexLast: indexLast };
}
fst = par;
par = par.parentNode;
}
return ret;
};
Sys.Extended.UI.HtmlEditor.positionInParagraph = function(marker, el, left, par, wordBound) {
while(true) {
var result = Sys.Extended.UI.HtmlEditor.positionInParagraphLevel(marker, el, left, wordBound);
if(result != null)
return result;
if(par.tagName && Sys.Extended.UI.HtmlEditor.isStyleTag(par.tagName) && (par.tagName.toUpperCase() != "A") && !Sys.Extended.UI.HtmlEditor.isTempElement(par)) {
el = left ? par.previousSibling : par.nextSibling;
par = par.parentNode;
} else {
if(!left || par.firstChild == null)
par.appendChild(marker);
else
par.insertBefore(marker, par.firstChild);
return marker;
}
}
};
Sys.Extended.UI.HtmlEditor.positionInParagraphLevel = function(marker, el, left, wordBound) {
while(el) {
var elSibling = left ? el.previousSibling : el.nextSibling;
if(!Sys.Extended.UI.HtmlEditor.isInlineElement(el)) {
var par = el.parentNode;
if(!left) {
par.insertBefore(marker, el);
} else {
if(el.nextSibling)
par.insertBefore(marker, el.nextSibling);
else
par.appendChild(marker);
}
return marker;
} else if(typeof wordBound == "function" && el.nodeType == 3) {
var j, str = "" + el.data + "";
if(left) {
for(j = str.length - 1; j >= 0; j--)
if(wordBound(str.substr(j, 1)))
break;
} else {
for(j = 0; j < str.length; j++)
if(wordBound(str.substr(j, 1)))
break;
}
if(j >= 0 && j < str.length) {
var par = el.parentNode,
newNode;
if((j > 0 || (left && j == 0)) && (j < str.length - 1 || (!left && j == str.length - 1))) {
if(left)
newNode = el.splitText(j + 1);
else
newNode = el.splitText(j);
par.insertBefore(marker, newNode);
} else {
if(!left) {
par.insertBefore(marker, el);
} else {
if(el.nextSibling)
par.insertBefore(marker, el.nextSibling);
else
par.appendChild(marker);
}
}
return marker;
}
}
el = left ? el.lastChild : el.firstChild;
if(el) {
var result = Sys.Extended.UI.HtmlEditor.positionInParagraphLevel(marker, el, left, wordBound);
if(result != null)
return result;
}
el = elSibling;
}
return null;
};
Sys.Extended.UI.HtmlEditor._addEvent = function(el, evname, func) {
if(el.attachEvent)
el.attachEvent("on" + evname, func);
else if(el.addEventListener)
el.addEventListener(evname, func, true);
};
Sys.Extended.UI.HtmlEditor._addEvents = function(el, evs, func) {
for(var i = 0; i < evs.length; i++)
Sys.Extended.UI.HtmlEditor._addEvent(el, evs[i], func);
};
Sys.Extended.UI.HtmlEditor._removeEvent = function(el, evname, func) {
if(el.detachEvent)
el.detachEvent("on" + evname, func);
else if(el.removeEventListener)
el.removeEventListener(evname, func, true);
};
Sys.Extended.UI.HtmlEditor._removeEvents = function(el, evs, func) {
for(var i = 0; i < evs.length; i++)
Sys.Extended.UI.HtmlEditor._removeEvent(el, evs[i], func);
};
Sys.Extended.UI.HtmlEditor._stopEvent = function(ev) {
if(ev) {
if(Sys.Extended.UI.HtmlEditor.isIE) {
ev.cancelBubble = true;
ev.returnValue = false;
} else {
ev.preventDefault();
ev.stopPropagation();
}
}
};
Sys.Extended.UI.HtmlEditor.restrictedTags = ["DIV", "P", "TD", "TR", "TABLE", "TBODY", "LI", "OL", "UL", "FORM", "INPUT"]; // this list can be increased
Sys.Extended.UI.HtmlEditor.isRestricted = function(element) {
var elementTagName = element.tagName.toUpperCase();
for(var i = 0; i < Sys.Extended.UI.HtmlEditor.restrictedTags.length; i++)
if(Sys.Extended.UI.HtmlEditor.restrictedTags[i].toUpperCase() == elementTagName)
return true;
if(Sys.Extended.UI.HtmlEditor.isIE && element.scopeName.toUpperCase() != "HTML")
return true;
return false;
};
Sys.Extended.UI.HtmlEditor.jsDocument = function(noExtraLf) {
this.noExtraLf = (typeof noExtraLf != "undefined" && noExtraLf);
this.text = []; //array to store the string
this.write = function(str) {
if(!this.noExtraLf || (this.text.length == 0 && str != "\n") || (this.text.length > 0 && (this.text[this.text.length - 1] != "\n" || str != "\n")))
this.text[this.text.length] = str;
};
this.append = this.write;
this.writeln = function(str) {
this.text[this.text.length] = str + "\n";
}
this.toString = function() {
return this.text.join("");
}
this.clear = function() {
delete this.text;
this.text = null;
this.text = new Array;
}
};
Sys.Extended.UI.HtmlEditor.isHeader = function(el) {
var name = el.tagName.toUpperCase();
if(name.length == 2)
if(name.substr(0, 1) == "H" && parseInt(name.substr(1, 1)) > 0)
return true;
return false;
};
Sys.Extended.UI.HtmlEditor._getReallyFirst = function(root) {
if(typeof root.firstChild != "undefined" && root.firstChild != null)
if(typeof root.firstChild.childNodes != "undefined" && root.firstChild.childNodes != null)
return Sys.Extended.UI.HtmlEditor._getReallyFirst(root.firstChild)
return root;
};
Sys.Extended.UI.HtmlEditor._getReallyLast = function(root) {
if(typeof root.lastChild != "undefined" && root.lastChild != null)
if(typeof root.lastChild.childNodes != "undefined" && root.lastChild.childNodes != null)
return Sys.Extended.UI.HtmlEditor._getReallyLast(root.lastChild)
return root;
};
Sys.Extended.UI.HtmlEditor._reallyFirst = function(root, seek) {
if(root.firstChild) {
if(root.firstChild == seek)
return true;
if(root.firstChild.childNodes)
if(Sys.Extended.UI.HtmlEditor._lookChild(root.firstChild, seek) == 0)
return Sys.Extended.UI.HtmlEditor._reallyFirst(root.firstChild, seek)
}
return false;
};
Sys.Extended.UI.HtmlEditor._reallyLast = function(root, seek) {
if(root.lastChild) {
if(root.lastChild == seek)
return true;
if(root.lastChild.childNodes)
if(Sys.Extended.UI.HtmlEditor._lookChild(root.lastChild, seek) == root.lastChild.childNodes.length - 1)
return Sys.Extended.UI.HtmlEditor._reallyLast(root.lastChild, seek)
}
return false;
};
Sys.Extended.UI.HtmlEditor.getContainer = function(container, el) {
if(el == container)
return container;
if(container.nodeType == 1) {
for(var i = 0; i < container.childNodes.length; i++) {
var child = container.childNodes.item(i);
if(el == child)
return child;
if(child.nodeType == 1) {
var ind = Sys.Extended.UI.HtmlEditor._lookChild(child, el);
if(ind >= 0) {
if(child.tagName && Sys.Extended.UI.HtmlEditor.isStyleTag(child.tagName) && (child.tagName.toUpperCase() != "A") && !Sys.Extended.UI.HtmlEditor.isTempElement(child))
return Sys.Extended.UI.HtmlEditor.getContainer(child, el);
else
return child;
}
}
}
}
return null;
};
Sys.Extended.UI.HtmlEditor._TryTransformFromPxToPt = function(fontSize, editor, _id) {
var ret = fontSize.replace(/^(\d+)\.(\d+)px/i, "$1px");
if(!Sys.Extended.UI.HtmlEditor.isIE) {
if(ret && ret.length > 0) {
var seek = ret.toLowerCase().split(",")[0];
if(typeof _id != "undefined") {
var el = document.getElementById(_id);
if(el != null) {
var i;
for(i = 0; i < el.options.length; i++) {
var cur = Sys.Extended.UI.HtmlEditor.fontSizeSeek(el.options.item(i).value.toLowerCase().split(",")[0]);
if(cur == seek)
break;
}
if(i == el.options.length) {
var span = editor._doc.createElement("SPAN");
editor._doc.body.appendChild(span);
for(i = 1; i < 100; i++) {
span.style.fontSize = i + "pt";
if(Sys.Extended.UI.HtmlEditor.getStyle(span, "font-size").replace(/^(\d+)\.(\d+)px/i, "$1px") == seek) {
seek = i + "pt";
break;
}
}
span.parentNode.removeChild(span);
}
}
}
ret = seek;
}
}
return ret;
};
Sys.Extended.UI.HtmlEditor.fontSizeSeek = function(val) {
var seek = val.toString();
switch(seek) {
case "1":
seek = "8pt";
break;
case "2":
seek = "10pt";
break;
case "3":
seek = "12pt";
break;
case "4":
seek = "14pt";
break;
case "5":
seek = "18pt";
break;
case "6":
seek = "24pt";
break;
case "7":
seek = "36pt";
break;
}
return seek;
};
Sys.Extended.UI.HtmlEditor.getOwnerDocument = function(node) {
return node.nodeType == 9 ? node : node.ownerDocument || node.document;
};
Sys.Extended.UI.HtmlEditor.getClientViewportElement = function(opt_node) {
var doc;
if(opt_node.nodeType == 9)
doc = opt_node;
else
doc = Sys.Extended.UI.HtmlEditor.getOwnerDocument(opt_node);
if(Sys.Extended.UI.HtmlEditor.isIE && doc.compatMode != 'CSS1Compat')
return doc.body;
return doc.documentElement;
};
Sys.Extended.UI.HtmlEditor.isReallyVisible = function(el) {
var elem = el,
real_visible = true;
while(elem) {
if(elem.style && Sys.Extended.UI.HtmlEditor.getStyle(elem, "display") == "none") {
real_visible = false;
break;
}
elem = elem.parentNode;
}
return real_visible;
}
Sys.Extended.UI.HtmlEditor.setSelectionRange = function(input, selectionStart, selectionEnd) {
input.focus();
if(input.setSelectionRange) {
input.setSelectionRange(selectionStart, selectionEnd);
} else if(input.createTextRange) {
var range = input.createTextRange();
range.collapse(true);
range.moveEnd('character', selectionEnd);
range.moveStart('character', selectionStart);
range.select();
}
};
Sys.Extended.UI.HtmlEditor.setElementVisibility = function(element) {
var ret = new Array(),
elem = element;
while(elem && elem.nodeType == 1 && elem.tagName.toUpperCase() != "BODY") {
var display = elem.style.display,
visibility = elem.style.visibility;
if(elem.style && (display == "none" || visibility == "hidden")) {
ret.push({ element: elem, display: display, visibility: visibility });
elem.style.display = "";
elem.style.visibility = "visible";
}
elem = elem.parentNode;
}
return ret;
};
Sys.Extended.UI.HtmlEditor.restoreElementVisibility = function(arr) {
for(var i = 0; i < arr.length; i++) {
var item = arr[i],
style = item.element.style;
style.display = item.display;
style.visibility = item.visibility;
}
};
if(!Sys.Extended.UI.HtmlEditor.isIE) {
try { //not all such browsers support getter/setter
Sys.Extended.UI.HtmlEditor.__MozillaGetInnerText = function(node, html) {
var els = node.childNodes;
for(var i = 0; i < els.length; i++) {
var elem = els[i];
if(elem.nodeType == 3)
html.write(elem.nodeValue.replace("\n", ""));
if(elem.nodeType == 1) {
var display = Sys.Extended.UI.HtmlEditor.getStyle(elem, "display"),
visibility = Sys.Extended.UI.HtmlEditor.getStyle(elem, "visibility");
if(Sys.Extended.UI.HtmlEditor.__needLineBreakBefore(elem))
html.write("\n");
if(Sys.Extended.UI.HtmlEditor.__needTabBefore(elem))
html.write("\t");
if(display != "none" && visibility != "hidden")
Sys.Extended.UI.HtmlEditor.__MozillaGetInnerText(elem, html);
if(Sys.Extended.UI.HtmlEditor.__needLineBreakAfter(elem))
html.write("\n");
}
}
};
Sys.Extended.UI.HtmlEditor.__needLineBreakBefore = function(el) {
var _Tags = " div table p pre ol ul blockquote form fieldset ";
return (_Tags.indexOf(" " + el.tagName.toLowerCase() + " ") != -1);
};
Sys.Extended.UI.HtmlEditor.__needLineBreakAfter = function(el) {
var _Tags = " br div table tr p pre ol ul li hr blockquote form fieldset legend ";
return (_Tags.indexOf(" " + el.tagName.toLowerCase() + " ") != -1);
};
Sys.Extended.UI.HtmlEditor.__needTabBefore = function(el) {
var _Tags = " td li ";
return (_Tags.indexOf(" " + el.tagName.toLowerCase() + " ") != -1);
};
} catch(ex) { }
}
|
'use strict';
const common = require('../common');
const assert = require('assert');
const fs = require('fs');
const path = require('path');
const doesNotExist = path.join(common.tmpDir, '__this_should_not_exist');
const readOnlyFile = path.join(common.tmpDir, 'read_only_file');
const readWriteFile = path.join(common.tmpDir, 'read_write_file');
function createFileWithPerms(file, mode) {
fs.writeFileSync(file, '');
fs.chmodSync(file, mode);
}
common.refreshTmpDir();
createFileWithPerms(readOnlyFile, 0o444);
createFileWithPerms(readWriteFile, 0o666);
/*
* On non-Windows supported platforms, fs.access(readOnlyFile, W_OK, ...)
* always succeeds if node runs as the super user, which is sometimes the
* case for tests running on our continuous testing platform agents.
*
* In this case, this test tries to change its process user id to a
* non-superuser user so that the test that checks for write access to a
* read-only file can be more meaningful.
*
* The change of user id is done after creating the fixtures files for the same
* reason: the test may be run as the superuser within a directory in which
* only the superuser can create files, and thus it may need superuser
* priviledges to create them.
*
* There's not really any point in resetting the process' user id to 0 after
* changing it to 'nobody', since in the case that the test runs without
* superuser privilege, it is not possible to change its process user id to
* superuser.
*
* It can prevent the test from removing files created before the change of user
* id, but that's fine. In this case, it is the responsibility of the
* continuous integration platform to take care of that.
*/
let hasWriteAccessForReadonlyFile = false;
if (!common.isWindows && process.getuid() === 0) {
hasWriteAccessForReadonlyFile = true;
try {
process.setuid('nobody');
hasWriteAccessForReadonlyFile = false;
} catch (err) {
}
}
assert.strictEqual(typeof fs.F_OK, 'number');
assert.strictEqual(typeof fs.R_OK, 'number');
assert.strictEqual(typeof fs.W_OK, 'number');
assert.strictEqual(typeof fs.X_OK, 'number');
fs.access(__filename, common.mustCall((err) => {
assert.ifError(err);
}));
fs.access(__filename, fs.R_OK, common.mustCall((err) => {
assert.ifError(err);
}));
fs.access(doesNotExist, common.mustCall((err) => {
assert.notStrictEqual(err, null, 'error should exist');
assert.strictEqual(err.code, 'ENOENT');
assert.strictEqual(err.path, doesNotExist);
}));
fs.access(readOnlyFile, fs.F_OK | fs.R_OK, common.mustCall((err) => {
assert.ifError(err);
}));
fs.access(readOnlyFile, fs.W_OK, common.mustCall((err) => {
if (hasWriteAccessForReadonlyFile) {
assert.ifError(err);
} else {
assert.notStrictEqual(err, null, 'error should exist');
assert.strictEqual(err.path, readOnlyFile);
}
}));
assert.throws(() => {
fs.access(100, fs.F_OK, common.mustNotCall());
}, /^TypeError: path must be a string or Buffer$/);
assert.throws(() => {
fs.access(__filename, fs.F_OK);
}, /^TypeError: "callback" argument must be a function$/);
assert.throws(() => {
fs.access(__filename, fs.F_OK, {});
}, /^TypeError: "callback" argument must be a function$/);
assert.doesNotThrow(() => {
fs.accessSync(__filename);
});
assert.doesNotThrow(() => {
const mode = fs.F_OK | fs.R_OK | fs.W_OK;
fs.accessSync(readWriteFile, mode);
});
assert.throws(
() => { fs.accessSync(doesNotExist); },
(err) => {
assert.strictEqual(err.code, 'ENOENT');
assert.strictEqual(err.path, doesNotExist);
assert.strictEqual(
err.message,
`ENOENT: no such file or directory, access '${doesNotExist}'`
);
assert.strictEqual(err.constructor, Error);
return true;
}
);
|
var CombinedStream = require('combined-stream');
var util = require('util');
var path = require('path');
var http = require('http');
var https = require('https');
var parseUrl = require('url').parse;
var fs = require('fs');
var mime = require('mime-types');
var async = require('async');
var populate = require('./populate.js');
// Public API
module.exports = FormData;
// make it a Stream
util.inherits(FormData, CombinedStream);
/**
* Create readable "multipart/form-data" streams.
* Can be used to submit forms
* and file uploads to other web applications.
*
* @constructor
*/
function FormData() {
if (!(this instanceof FormData)) {
throw new TypeError('Failed to construct FormData: Please use the _new_ operator, this object constructor cannot be called as a function.');
}
this._overheadLength = 0;
this._valueLength = 0;
this._lengthRetrievers = [];
CombinedStream.call(this);
}
FormData.LINE_BREAK = '\r\n';
FormData.DEFAULT_CONTENT_TYPE = 'application/octet-stream';
FormData.prototype.append = function(field, value, options) {
options = options || {};
// allow filename as single option
if (typeof options == 'string') {
options = {filename: options};
}
var append = CombinedStream.prototype.append.bind(this);
// all that streamy business can't handle numbers
if (typeof value == 'number') {
value = '' + value;
}
// https://github.com/felixge/node-form-data/issues/38
if (util.isArray(value)) {
// Please convert your array into string
// the way web server expects it
this._error(new Error('Arrays are not supported.'));
return;
}
var header = this._multiPartHeader(field, value, options);
var footer = this._multiPartFooter();
append(header);
append(value);
append(footer);
// pass along options.knownLength
this._trackLength(header, value, options);
};
FormData.prototype._trackLength = function(header, value, options) {
var valueLength = 0;
// used w/ getLengthSync(), when length is known.
// e.g. for streaming directly from a remote server,
// w/ a known file a size, and not wanting to wait for
// incoming file to finish to get its size.
if (options.knownLength != null) {
valueLength += +options.knownLength;
} else if (Buffer.isBuffer(value)) {
valueLength = value.length;
} else if (typeof value === 'string') {
valueLength = Buffer.byteLength(value);
}
this._valueLength += valueLength;
// @check why add CRLF? does this account for custom/multiple CRLFs?
this._overheadLength +=
Buffer.byteLength(header) +
FormData.LINE_BREAK.length;
// empty or either doesn't have path or not an http response
if (!value || ( !value.path && !(value.readable && value.hasOwnProperty('httpVersion')) )) {
return;
}
// no need to bother with the length
if (!options.knownLength) {
this._lengthRetrievers.push(function(next) {
if (value.hasOwnProperty('fd')) {
// take read range into a account
// `end` = Infinity –> read file till the end
//
// TODO: Looks like there is bug in Node fs.createReadStream
// it doesn't respect `end` options without `start` options
// Fix it when node fixes it.
// https://github.com/joyent/node/issues/7819
if (value.end != undefined && value.end != Infinity && value.start != undefined) {
// when end specified
// no need to calculate range
// inclusive, starts with 0
next(null, value.end + 1 - (value.start ? value.start : 0));
// not that fast snoopy
} else {
// still need to fetch file size from fs
fs.stat(value.path, function(err, stat) {
var fileSize;
if (err) {
next(err);
return;
}
// update final size based on the range options
fileSize = stat.size - (value.start ? value.start : 0);
next(null, fileSize);
});
}
// or http response
} else if (value.hasOwnProperty('httpVersion')) {
next(null, +value.headers['content-length']);
// or request stream http://github.com/mikeal/request
} else if (value.hasOwnProperty('httpModule')) {
// wait till response come back
value.on('response', function(response) {
value.pause();
next(null, +response.headers['content-length']);
});
value.resume();
// something else
} else {
next('Unknown stream');
}
});
}
};
FormData.prototype._multiPartHeader = function(field, value, options) {
// custom header specified (as string)?
// it becomes responsible for boundary
// (e.g. to handle extra CRLFs on .NET servers)
if (typeof options.header == 'string') {
return options.header;
}
var contentDisposition = this._getContentDisposition(value, options);
var contentType = this._getContentType(value, options);
var contents = '';
var headers = {
// add custom disposition as third element or keep it two elements if not
'Content-Disposition': ['form-data', 'name="' + field + '"'].concat(contentDisposition || []),
// if no content type. allow it to be empty array
'Content-Type': [].concat(contentType || [])
};
// allow custom headers.
if (typeof options.header == 'object') {
populate(headers, options.header);
}
var header;
for (var prop in headers) {
header = headers[prop];
// skip nullish headers.
if (header == null) {
continue;
}
// convert all headers to arrays.
if (!Array.isArray(header)) {
header = [header];
}
// add non-empty headers.
if (header.length) {
contents += prop + ': ' + header.join('; ') + FormData.LINE_BREAK;
}
}
return '--' + this.getBoundary() + FormData.LINE_BREAK + contents + FormData.LINE_BREAK;
};
FormData.prototype._getContentDisposition = function(value, options) {
var contentDisposition;
// custom filename takes precedence
// fs- and request- streams have path property
// formidable and the browser add a name property.
var filename = options.filename || value.name || value.path;
// or try http response
if (!filename && value.readable && value.hasOwnProperty('httpVersion')) {
filename = value.client._httpMessage.path;
}
if (filename) {
contentDisposition = 'filename="' + path.basename(filename) + '"';
}
return contentDisposition;
};
FormData.prototype._getContentType = function(value, options) {
// use custom content-type above all
var contentType = options.contentType;
// or try `name` from formidable, browser
if (!contentType && value.name) {
contentType = mime.lookup(value.name);
}
// or try `path` from fs-, request- streams
if (!contentType && value.path) {
contentType = mime.lookup(value.path);
}
// or if it's http-reponse
if (!contentType && value.readable && value.hasOwnProperty('httpVersion')) {
contentType = value.headers['content-type'];
}
// or guess it from the filename
if (!contentType && options.filename) {
contentType = mime.lookup(options.filename);
}
// fallback to the default content type if `value` is not simple value
if (!contentType && typeof value == 'object') {
contentType = FormData.DEFAULT_CONTENT_TYPE;
}
return contentType;
};
FormData.prototype._multiPartFooter = function() {
return function(next) {
var footer = FormData.LINE_BREAK;
var lastPart = (this._streams.length === 0);
if (lastPart) {
footer += this._lastBoundary();
}
next(footer);
}.bind(this);
};
FormData.prototype._lastBoundary = function() {
return '--' + this.getBoundary() + '--' + FormData.LINE_BREAK;
};
FormData.prototype.getHeaders = function(userHeaders) {
var header;
var formHeaders = {
'content-type': 'multipart/form-data; boundary=' + this.getBoundary()
};
for (header in userHeaders) {
if (userHeaders.hasOwnProperty(header)) {
formHeaders[header.toLowerCase()] = userHeaders[header];
}
}
return formHeaders;
};
// TODO: Looks like unused function
FormData.prototype.getCustomHeaders = function(contentType) {
contentType = contentType ? contentType : 'multipart/form-data';
var formHeaders = {
'content-type': contentType + '; boundary=' + this.getBoundary(),
'content-length': this.getLengthSync()
};
return formHeaders;
};
FormData.prototype.getBoundary = function() {
if (!this._boundary) {
this._generateBoundary();
}
return this._boundary;
};
FormData.prototype._generateBoundary = function() {
// This generates a 50 character boundary similar to those used by Firefox.
// They are optimized for boyer-moore parsing.
var boundary = '--------------------------';
for (var i = 0; i < 24; i++) {
boundary += Math.floor(Math.random() * 10).toString(16);
}
this._boundary = boundary;
};
// Note: getLengthSync DOESN'T calculate streams length
// As workaround one can calculate file size manually
// and add it as knownLength option
FormData.prototype.getLengthSync = function() {
var knownLength = this._overheadLength + this._valueLength;
// Don't get confused, there are 3 "internal" streams for each keyval pair
// so it basically checks if there is any value added to the form
if (this._streams.length) {
knownLength += this._lastBoundary().length;
}
// https://github.com/form-data/form-data/issues/40
if (this._lengthRetrievers.length) {
// Some async length retrievers are present
// therefore synchronous length calculation is false.
// Please use getLength(callback) to get proper length
this._error(new Error('Cannot calculate proper length in synchronous way.'));
}
return knownLength;
};
FormData.prototype.getLength = function(cb) {
var knownLength = this._overheadLength + this._valueLength;
if (this._streams.length) {
knownLength += this._lastBoundary().length;
}
if (!this._lengthRetrievers.length) {
process.nextTick(cb.bind(this, null, knownLength));
return;
}
async.parallel(this._lengthRetrievers, function(err, values) {
if (err) {
cb(err);
return;
}
values.forEach(function(length) {
knownLength += length;
});
cb(null, knownLength);
});
};
FormData.prototype.submit = function(params, cb) {
var request
, options
, defaults = {method: 'post'}
;
// parse provided url if it's string
// or treat it as options object
if (typeof params == 'string') {
params = parseUrl(params);
options = populate({
port: params.port,
path: params.pathname,
host: params.hostname
}, defaults);
// use custom params
} else {
options = populate(params, defaults);
// if no port provided use default one
if (!options.port) {
options.port = options.protocol == 'https:' ? 443 : 80;
}
}
// put that good code in getHeaders to some use
options.headers = this.getHeaders(params.headers);
// https if specified, fallback to http in any other case
if (options.protocol == 'https:') {
request = https.request(options);
} else {
request = http.request(options);
}
// get content length and fire away
this.getLength(function(err, length) {
if (err) {
this._error(err);
return;
}
// add content length
request.setHeader('Content-Length', length);
this.pipe(request);
if (cb) {
request.on('error', cb);
request.on('response', cb.bind(this, null));
}
}.bind(this));
return request;
};
FormData.prototype._error = function(err) {
if (!this.error) {
this.error = err;
this.pause();
this.emit('error', err);
}
};
|
import { get } from "ember-metal/property_get";
import { set } from "ember-metal/property_set";
import run from "ember-metal/run_loop";
import EmberView from "ember-views/views/view";
import ContainerView from "ember-views/views/container_view";
var parentView, view;
QUnit.module("Ember.View#element", {
teardown: function() {
run(function() {
if (parentView) { parentView.destroy(); }
view.destroy();
});
}
});
test("returns null if the view has no element and no parent view", function() {
view = EmberView.create() ;
equal(get(view, 'parentView'), null, 'precond - has no parentView');
equal(get(view, 'element'), null, 'has no element');
});
test("returns null if the view has no element and parent view has no element", function() {
parentView = ContainerView.create({
childViews: [ EmberView.extend() ]
});
view = get(parentView, 'childViews').objectAt(0);
equal(get(view, 'parentView'), parentView, 'precond - has parent view');
equal(get(parentView, 'element'), null, 'parentView has no element');
equal(get(view, 'element'), null, ' has no element');
});
test("returns element if you set the value", function() {
view = EmberView.create();
equal(get(view, 'element'), null, 'precond- has no element');
var dom = document.createElement('div');
set(view, 'element', dom);
equal(get(view, 'element'), dom, 'now has set element');
});
test("should not allow the elementId to be changed after inserted", function() {
view = EmberView.create({
elementId: 'one'
});
run(function() {
view.appendTo('#qunit-fixture');
});
raises(function() {
view.set('elementId', 'two');
}, "raises elementId changed exception");
equal(view.get('elementId'), 'one', 'elementId is still "one"');
});
|
/**
* Sorter for an object on a property
*
* @param {string} property - The property to sort on.
*
* @returns {number} - The sort value for that property.
*/
export default function onProperty(property) {
return (a, b) => {
if (a[property] > b[property]) {
return 1;
}
if (a[property] < b[property]) {
return -1;
}
return 0;
};
}
|
app.registerAbstractClass("Abstract/AppAbstract", {
$_extends: "Abstract/AppAbstractBase",
$_traits: ["Trait/AppTraitForAbstract"],
$_abstract: {
reset: function() {},
destruct: function() {}
},
execute: function()
{
this.callParent('execute');
return true;
}
});
|
YUI.add('gallery-progress-bar', function(Y) {
var LANG = Y.Lang;
Y.ProgressBar = Y.Base.create('progressBar', Y.Widget, [], {
_anim: null,
/** set up **/
renderUI: function() {
Y.log('renderUI', 'info', 'Y.ProgressBar');
this.get('contentBox').append(LANG.sub(this.get('layout'), {
sliderClass: this.getClassName('slider'),
labelClass: this.getClassName('label')
}));
},
bindUI: function() {
Y.log('bindUI', 'info', 'Y.ProgressBar');
this.after('labelChange', this._updateLabel);
this.after('labelTemplateChange', this._updateLabel);
this.after('progressChange', this._updateBar);
},
syncUI: function() {
Y.log('syncUI', 'info', 'Y.ProgressBar');
this._updateBar();
},
/** A little bit of sugar **/
increment: function(step) {
Y.log('increment', 'info', 'Y.ProgressBar');
step = step || 1;
this.set('progress', this.get('progress') + parseFloat(step, 10));
return this;
},
decrement: function(step) {
Y.log('decrement', 'info', 'Y.ProgressBar');
step = step || 1;
this.set('progress', this.get('progress') - parseFloat(step, 10));
return this;
},
update: function(progress) {
Y.log('update', 'info', 'Y.ProgressBar');
this.set('progress', progress);
return this;
},
setLabelAt: function(position, value) {
Y.log('setLabelAt', 'info', 'Y.ProgressBar');
var label = this.get('label');
position = parseFloat(position, 10);
label[position] = value;
this.set('label', label);
return this;
},
removeLabelAt: function(position) {
Y.log('removeLabelAt', 'info', 'Y.ProgressBar');
var label = this.get('label');
position = parseFloat(position, 10);
if (label[position] !== undefined && label[position] !== null) {
delete label[position];
}
this.set('label', label);
return this;
},
setLabelTemplateAt: function(position, value) {
Y.log('setLabelTemplateAt', 'info', 'Y.ProgressBar');
var template = this.get('labelTemplate');
position = parseFloat(position, 10);
template[position] = value;
this.set('labelTemplate', template);
return this;
},
removeLabelTemplateAt: function(position) {
Y.log('removeLabelTemplateAt', 'info', 'Y.ProgressBar');
var template = this.get('labelTemplate');
position = parseFloat(position, 10);
if (template[position] !== undefined && template[position] !== null) {
delete template[position];
}
this.set('labelTemplate', template);
return this;
},
/** protected updaters **/
_updateLabel: function(e) {
Y.log('_updateLabel', 'info', 'Y.ProgressBar');
var progress = this.get('progress'),
attrs = this.getAttrs(),
label = this._getLabel(progress),
labelTemplate = this._getLabelTemplate(progress);
attrs.label = label || '';
this.get('contentBox').all('.' + this.getClassName('label')).set('text', LANG.sub(labelTemplate, attrs));
},
_updateBar: function(e) {
Y.log('_updateBar', 'info', 'Y.ProgressBar');
var cb = this.get('contentBox'),
position = cb.get('offsetWidth') * this.get('progress') / 100;
if (!this._anim) {
this._makeAnim();
}
if (this._anim && this._anim.get('running')) {
this._anim.stop();
}
this._anim.set('to.width', position);
this._anim.run();
this._updateLabel();
},
_makeAnim: function() {
Y.log('_makeAnim', 'info', 'Y.ProgressBar');
var animConfig = this.get('animation'),
node = this.get('contentBox').one(this.get('animateNode'));
animConfig.node = node;
if (!animConfig.to) {
animConfig.to = {
width: 0
};
}
this._anim = new Y.Anim(animConfig);
},
_getAnimateNode: function() {
return ('.' + this.getClassName('slider'));
},
_getLabel : function(progress) {
Y.log('_getLabel', 'info', 'Y.ProgressBar');
var label = this.get('label'),
labelString = null,
keys, i = -1, l;
if ( !LANG.isObject(label) ) {
return label;
}
if (label[progress] !== undefined && label[progress] !== null) {
labelString = label[progress];
} else {
keys = Y.Object.keys(label);
keys.sort(Y.Array.numericSort);
l = keys.length;
while (++i < l) {
if (keys[i] <= progress) {
labelString = label[keys[i]];
}
}
}
return labelString;
},
_getLabelTemplate : function(progress) {
Y.log('_getLabelTemplate', 'info', 'Y.ProgressBar');
var template = this.get('labelTemplate'),
templateString = null,
keys, i = -1, l;
if ( !LANG.isObject(template) ) {
return template;
}
if (template[progress] !== undefined && template[progress] !== null) {
templateString = template[progress];
} else {
keys = Y.Object.keys(template);
keys.sort(Y.Array.numericSort);
l = keys.length;
while (++i < l) {
if (keys[i] <= progress) {
templateString = template[keys[i]];
}
}
}
return templateString;
}
}, {
ATTRS: {
animation: {
value: {
easing: Y.Easing.easeIn,
duration: 0.5
}
},
animateNode: {
valueFn: '_getAnimateNode'
},
/* REMOVED FOR TRANSITION BUG
transition : {
value : {
easing : 'ease-out',
duration: 0.5
}
},
*/
labelTemplate: {
value: { 0 : '{label} - {progress}%' },
validator: function(val) {
return (LANG.isString(val) || LANG.isObject(val));
},
setter: function(val) {
if (LANG.isString(val)) {
val = {
0: val
};
}
return val;
}
},
label: {
value: {
0: 'Loading',
100: 'Complete'
},
validator: function(val) {
return (LANG.isString(val) || LANG.isObject(val));
},
setter: function(val) {
if (LANG.isString(val)) {
val = {
0: val
};
}
return val;
}
},
layout: {
value: '<div class="{sliderClass} {labelClass}"></div>'
},
precision: {
value: 2,
setter: function(val) {
return parseInt(val, 10);
}
},
progress: {
value: 0,
setter: function(val) {
var precision = Math.pow(10, this.get('precision'));
val = parseFloat(val, 10);
if (val < 0) {
val = 0;
} else if (val > 100) {
val = 100;
}
return Math.round(val * precision) / precision;
}
}
}
});
}, 'gallery-2011.02.09-21-32' ,{requires:['widget','anim','base-build']});
|
goog.addDependency("base.js", ['goog'], []);
goog.addDependency("../cljs/core.js", ['cljs.core'], ['goog.string', 'goog.object', 'goog.string.StringBuffer', 'goog.array']);
|
/*
* MelonJS Game Engine
* Copyright (C) 2011 - 2013, Olivier BIOT
* http://www.melonjs.org
*
*/
(function($) {
/**
* me.ObjectSettings contains the object attributes defined in Tiled<br>
* and is created by the engine and passed as parameter to the corresponding object when loading a level<br>
* the field marked Mandatory are to be defined either in Tiled, or in the before calling the parent constructor<br>
* <img src="images/object_properties.png"/><br>
* @class
* @protected
* @memberOf me
*/
me.ObjectSettings = {
/**
* object entity name<br>
* as defined in the Tiled Object Properties
* @public
* @type String
* @name name
* @memberOf me.ObjectSettings
*/
name : null,
/**
* image ressource name to be loaded<br>
* MANDATORY<br>
* (in case of TiledObject, this field is automatically set)
* @public
* @type String
* @name image
* @memberOf me.ObjectSettings
*/
image : null,
/**
* specify a transparent color for the image in rgb format (#rrggbb)<br>
* OPTIONAL<br>
* (using this option will imply processing time on the image)
* @public
* @deprecated Use PNG or GIF with transparency instead
* @type String
* @name transparent_color
* @memberOf me.ObjectSettings
*/
transparent_color : null,
/**
* width of a single sprite in the spritesheet<br>
* MANDATORY<br>
* (in case of TiledObject, this field is automatically set)
* @public
* @type Int
* @name spritewidth
* @memberOf me.ObjectSettings
*/
spritewidth : null,
/**
* height of a single sprite in the spritesheet<br>
* OPTIONAL<br>
* if not specified the value will be set to the corresponding image height<br>
* (in case of TiledObject, this field is automatically set)
* @public
* @type Int
* @name spriteheight
* @memberOf me.ObjectSettings
*/
spriteheight : null,
/**
* custom type for collision detection<br>
* OPTIONAL
* @public
* @type String
* @name type
* @memberOf me.ObjectSettings
*/
type : 0,
/**
* Enable collision detection for this object<br>
* OPTIONAL
* @public
* @type Boolean
* @name collidable
* @memberOf me.ObjectSettings
*/
collidable : true
};
/**
* A pool of Object entity <br>
* This object is used for object pooling - a technique that might speed up your game
* if used properly. <br>
* If some of your classes will be instantiated and removed a lot at a time, it is a
* good idea to add the class to this entity pool. A separate pool for that class
* will be created, which will reuse objects of the class. That way they won't be instantiated
* each time you need a new one (slowing your game), but stored into that pool and taking one
* already instantiated when you need it.<br><br>
* This object is also used by the engine to instantiate objects defined in the map,
* which means, that on level loading the engine will try to instantiate every object
* found in the map, based on the user defined name in each Object Properties<br>
* <img src="images/object_properties.png"/><br>
* There is no constructor function for me.entityPool, this is a static object
* @namespace me.entityPool
* @memberOf me
*/
me.entityPool = (function() {
// hold public stuff in our singletong
var obj = {};
/*---------------------------------------------
PRIVATE STUFF
---------------------------------------------*/
var entityClass = {};
/*---------------------------------------------
PUBLIC STUFF
---------------------------------------------*/
/*---
init
---*/
obj.init = function() {
// add default entity object
obj.add("me.ObjectEntity", me.ObjectEntity);
obj.add("me.CollectableEntity", me.CollectableEntity);
obj.add("me.LevelEntity", me.LevelEntity);
obj.add("me.Tween", me.Tween, true);
};
/**
* Add an object to the pool. <br>
* Pooling must be set to true if more than one such objects will be created. <br>
* (note) If pooling is enabled, you shouldn't instantiate objects with `new`.
* See examples in {@link me.entityPool#newInstanceOf}
* @name add
* @memberOf me.entityPool
* @public
* @function
* @param {String} className as defined in the Name field of the Object Properties (in Tiled)
* @param {Object} class corresponding Class to be instantiated
* @param {Boolean} [objectPooling=false] enables object pooling for the specified class
* - speeds up the game by reusing existing objects
* @example
* // add our users defined entities in the entity pool
* me.entityPool.add("playerspawnpoint", PlayerEntity);
* me.entityPool.add("cherryentity", CherryEntity, true);
* me.entityPool.add("heartentity", HeartEntity, true);
* me.entityPool.add("starentity", StarEntity, true);
*/
obj.add = function(className, entityObj, pooling) {
if (!pooling) {
entityClass[className.toLowerCase()] = {
"class" : entityObj,
"pool" : undefined
};
return;
}
entityClass[className.toLowerCase()] = {
"class" : entityObj,
"pool" : [],
"active" : []
};
};
/**
* Return a new instance of the requested object (if added into the object pool)
* @name newInstanceOf
* @memberOf me.entityPool
* @public
* @function
* @param {String} className as used in {@link me.entityPool#add}
* @param {} [arguments...] arguments to be passed when instantiating/reinitializing the object
* @example
* me.entityPool.add("player", PlayerEntity);
* var player = me.entityPool.newInstanceOf("player");
* @example
* me.entityPool.add("bullet", BulletEntity, true);
* me.entityPool.add("enemy", EnemyEntity, true);
* // ...
* // when we need to manually create a new bullet:
* var bullet = me.entityPool.newInstanceOf("bullet", x, y, direction);
* // ...
* // params aren't a fixed number
* // when we need new enemy we can add more params, that the object construct requires:
* var enemy = me.entityPool.newInstanceOf("enemy", x, y, direction, speed, power, life);
* // ...
* // when we want to destroy existing object, the remove
* // function will ensure the object can then be reallocated later
* me.game.remove(enemy);
* me.game.remove(bullet);
*/
obj.newInstanceOf = function(data) {
var name = typeof data === 'string' ? data.toLowerCase() : undefined;
var args = Array.prototype.slice.call(arguments);
if (name && entityClass[name]) {
var proto;
if (!entityClass[name]['pool']) {
proto = entityClass[name]["class"];
args[0] = proto;
return new (proto.bind.apply(proto, args))();
}
var obj, entity = entityClass[name];
proto = entity["class"];
if (entity["pool"].length > 0) {
obj = entity["pool"].pop();
// call the object init function if defined (JR's Inheritance)
if (typeof obj.init === "function") {
obj.init.apply(obj, args.slice(1));
}
// call the object onResetEvent function if defined
if (typeof obj.onResetEvent === "function") {
obj.onResetEvent.apply(obj, args.slice(1));
}
} else {
args[0] = proto;
obj = new (proto.bind.apply(proto, args))();
obj.className = name;
}
entity["active"].push(obj);
return obj;
}
// Tile objects can be created with a GID attribute;
// The TMX parser will use it to create the image property.
var settings = arguments[3];
if (settings && settings.gid && settings.image) {
return new me.SpriteObject(settings.x, settings.y, settings.image);
}
if (name) {
console.error("Cannot instantiate entity of type '" + data + "': Class not found!");
}
return null;
};
/**
* purge the entity pool from any inactive object <br>
* Object pooling must be enabled for this function to work<br>
* note: this will trigger the garbage collector
* @name purge
* @memberOf me.entityPool
* @public
* @function
*/
obj.purge = function() {
for (var className in entityClass) {
entityClass[className]["pool"] = [];
}
};
/**
* Remove object from the entity pool <br>
* Object pooling for the object class must be enabled,
* and object must have been instantiated using {@link me.entityPool#newInstanceOf},
* otherwise this function won't work
* @name freeInstance
* @memberOf me.entityPool
* @public
* @function
* @param {Object} instance to be removed
*/
obj.freeInstance = function(obj) {
var name = obj.className;
if (!name || !entityClass[name]) {
return;
}
var notFound = true;
for (var i = 0, len = entityClass[name]["active"].length; i < len; i++) {
if (entityClass[name]["active"][i] === obj) {
notFound = false;
entityClass[name]["active"].splice(i, 1);
break;
}
}
if (notFound) {
return;
}
entityClass[name]["pool"].push(obj);
};
// return our object
return obj;
})();
/************************************************************************************/
/* */
/* a generic object entity */
/* */
/************************************************************************************/
/**
* a Generic Object Entity<br>
* Object Properties (settings) are to be defined in Tiled, <br>
* or when calling the parent constructor
*
* @class
* @extends me.Renderable
* @memberOf me
* @constructor
* @param {Number} x the x coordinates of the sprite object
* @param {Number} y the y coordinates of the sprite object
* @param {me.ObjectSettings} settings Object Properties as defined in Tiled <br> <img src="images/object_properties.png"/>
*/
me.ObjectEntity = me.Renderable.extend(
/** @scope me.ObjectEntity.prototype */ {
/**
* define the type of the object<br>
* default value : none<br>
* @public
* @type String
* @name type
* @memberOf me.ObjectEntity
*/
type : 0,
/**
* flag to enable collision detection for this object<br>
* default value : true<br>
* @public
* @type Boolean
* @name collidable
* @memberOf me.ObjectEntity
*/
collidable : true,
/**
* Entity collision Box<br>
* (reference to me.ObjectEntity.shapes[0].getBounds)
* @public
* @deprecated
* @type me.Rect
* @name collisionBox
* @memberOf me.ObjectEntity
*/
collisionBox : null,
/**
* Entity collision shapes<br>
* (RFU - Reserved for Future Usage)
* @protected
* @type Object[]
* @name shapes
* @memberOf me.ObjectEntity
*/
shapes : null,
/**
* The entity renderable object (if defined)
* @public
* @type me.Renderable
* @name renderable
* @memberOf me.ObjectEntity
*/
renderable : null,
// just to keep track of when we flip
lastflipX : false,
lastflipY : false,
/** @ignore */
init : function(x, y, settings) {
// instantiate pos here to avoid
// later re-instantiation
if (this.pos === null) {
this.pos = new me.Vector2d();
}
// call the parent constructor
this.parent(this.pos.set(x,y),
~~settings.spritewidth || ~~settings.width,
~~settings.spriteheight || ~~settings.height);
if (settings.image) {
var image = typeof settings.image === "string" ? me.loader.getImage(settings.image) : settings.image;
this.renderable = new me.AnimationSheet(0, 0, image,
~~settings.spritewidth,
~~settings.spriteheight,
~~settings.spacing,
~~settings.margin);
// check for user defined transparent color
if (settings.transparent_color) {
this.renderable.setTransparency(settings.transparent_color);
}
}
// set the object entity name
this.name = settings.name?settings.name.toLowerCase():"";
/**
* entity current velocity<br>
* @public
* @type me.Vector2d
* @name vel
* @memberOf me.ObjectEntity
*/
if (this.vel === undefined) {
this.vel = new me.Vector2d();
}
this.vel.set(0,0);
/**
* entity current acceleration<br>
* @public
* @type me.Vector2d
* @name accel
* @memberOf me.ObjectEntity
*/
if (this.accel === undefined) {
this.accel = new me.Vector2d();
}
this.accel.set(0,0);
/**
* entity current friction<br>
* @public
* @name friction
* @memberOf me.ObjectEntity
*/
if (this.friction === undefined) {
this.friction = new me.Vector2d();
}
this.friction.set(0,0);
/**
* max velocity (to limit entity velocity)<br>
* @public
* @type me.Vector2d
* @name maxVel
* @memberOf me.ObjectEntity
*/
if (this.maxVel === undefined) {
this.maxVel = new me.Vector2d();
}
this.maxVel.set(1000, 1000);
// some default contants
/**
* Default gravity value of the entity<br>
* default value : 0.98 (earth gravity)<br>
* to be set to 0 for RPG, shooter, etc...<br>
* Note: Gravity can also globally be defined through me.sys.gravity
* @public
* @see me.sys.gravity
* @type Number
* @name gravity
* @memberOf me.ObjectEntity
*/
this.gravity = me.sys.gravity!==undefined ? me.sys.gravity : 0.98;
// just to identify our object
this.isEntity = true;
/**
* dead/living state of the entity<br>
* default value : true
* @public
* @type Boolean
* @name alive
* @memberOf me.ObjectEntity
*/
this.alive = true;
// make sure it's visible by default
this.visible = true;
// and also non floating by default
this.floating = false;
// and non persistent per default
this.isPersistent = false;
/**
* falling state of the object<br>
* true if the object is falling<br>
* false if the object is standing on something<br>
* @readonly
* @public
* @type Boolean
* @name falling
* @memberOf me.ObjectEntity
*/
this.falling = false;
/**
* jumping state of the object<br>
* equal true if the entity is jumping<br>
* @readonly
* @public
* @type Boolean
* @name jumping
* @memberOf me.ObjectEntity
*/
this.jumping = true;
// some usefull slope variable
this.slopeY = 0;
/**
* equal true if the entity is standing on a slope<br>
* @readonly
* @public
* @type Boolean
* @name onslope
* @memberOf me.ObjectEntity
*/
this.onslope = false;
/**
* equal true if the entity is on a ladder<br>
* @readonly
* @public
* @type Boolean
* @name onladder
* @memberOf me.ObjectEntity
*/
this.onladder = false;
/**
* equal true if the entity can go down on a ladder<br>
* @readonly
* @public
* @type Boolean
* @name disableTopLadderCollision
* @memberOf me.ObjectEntity
*/
this.disableTopLadderCollision = false;
// to enable collision detection
this.collidable = typeof(settings.collidable) !== "undefined" ? settings.collidable : true;
// default objec type
this.type = settings.type || 0;
// default flip value
this.lastflipX = this.lastflipY = false;
// ref to the collision map
this.collisionMap = me.game.collisionMap;
/**
* Define if an entity can go through breakable tiles<br>
* default value : false<br>
* @public
* @type Boolean
* @name canBreakTile
* @memberOf me.ObjectEntity
*/
this.canBreakTile = false;
/**
* a callback when an entity break a tile<br>
* @public
* @callback
* @name onTileBreak
* @memberOf me.ObjectEntity
*/
this.onTileBreak = null;
// add a default shape
if (settings.isEllipse===true) {
// ellipse
this.addShape(new me.Ellipse(new me.Vector2d(0,0), this.width, this.height));
}
else if ((settings.isPolygon===true) || (settings.isPolyline===true)) {
// add a polyshape
this.addShape(new me.PolyShape(new me.Vector2d(0,0), settings.points, settings.isPolygon));
// set the entity object based on the bounding box size ?
this.width = this.collisionBox.width;
this.height = this.collisionBox.height;
}
else {
// add a rectangle
this.addShape(new me.Rect(new me.Vector2d(0,0), this.width, this.height));
}
},
/**
* specify the size of the hit box for collision detection<br>
* (allow to have a specific size for each object)<br>
* e.g. : object with resized collision box :<br>
* <img src="images/me.Rect.colpos.png"/>
* @name updateColRect
* @memberOf me.ObjectEntity
* @function
* @param {Number} x x offset (specify -1 to not change the width)
* @param {Number} w width of the hit box
* @param {Number} y y offset (specify -1 to not change the height)
* @param {Number} h height of the hit box
*/
updateColRect : function(x, w, y, h) {
this.collisionBox.adjustSize(x, w, y, h);
},
/**
* add a collision shape to this entity<
* @name addShape
* @memberOf me.ObjectEntity
* @public
* @function
* @param {me.objet} shape a shape object
*/
addShape : function(shape) {
if (this.shapes === null) {
this.shapes = [];
}
this.shapes.push(shape);
// some hack to get the collisionBox working in this branch
// to be removed once the ticket #103 will be done
if (this.shapes.length === 1) {
this.collisionBox = this.shapes[0].getBounds();
// collisionBox pos vector is a reference to this pos vector
this.collisionBox.pos = this.pos;
// offset position vector
this.pos.add(this.shapes[0].offset);
}
},
/**
* onCollision Event function<br>
* called by the game manager when the object collide with shtg<br>
* by default, if the object type is Collectable, the destroy function is called
* @name onCollision
* @memberOf me.ObjectEntity
* @function
* @param {me.Vector2d} res collision vector
* @param {me.ObjectEntity} obj the other object that hit this object
* @protected
*/
onCollision : function(res, obj) {
// destroy the object if collectable
if (this.collidable && (this.type === me.game.COLLECTABLE_OBJECT))
me.game.remove(this);
},
/**
* set the entity default velocity<br>
* note : velocity is by default limited to the same value, see setMaxVelocity if needed<br>
* @name setVelocity
* @memberOf me.ObjectEntity
* @function
* @param {Number} x velocity on x axis
* @param {Number} y velocity on y axis
* @protected
*/
setVelocity : function(x, y) {
this.accel.x = x !== 0 ? x : this.accel.x;
this.accel.y = y !== 0 ? y : this.accel.y;
// limit by default to the same max value
this.setMaxVelocity(x,y);
},
/**
* cap the entity velocity to the specified value<br>
* @name setMaxVelocity
* @memberOf me.ObjectEntity
* @function
* @param {Number} x max velocity on x axis
* @param {Number} y max velocity on y axis
* @protected
*/
setMaxVelocity : function(x, y) {
this.maxVel.x = x;
this.maxVel.y = y;
},
/**
* set the entity default friction<br>
* @name setFriction
* @memberOf me.ObjectEntity
* @function
* @param {Number} x horizontal friction
* @param {Number} y vertical friction
* @protected
*/
setFriction : function(x, y) {
this.friction.x = x || 0;
this.friction.y = y || 0;
},
/**
* Flip object on horizontal axis
* @name flipX
* @memberOf me.ObjectEntity
* @function
* @param {Boolean} flip enable/disable flip
*/
flipX : function(flip) {
if (flip !== this.lastflipX) {
this.lastflipX = flip;
if (this.renderable && this.renderable.flipX) {
// flip the animation
this.renderable.flipX(flip);
}
// flip the collision box
this.collisionBox.flipX(this.width);
}
},
/**
* Flip object on vertical axis
* @name flipY
* @memberOf me.ObjectEntity
* @function
* @param {Boolean} flip enable/disable flip
*/
flipY : function(flip) {
if (flip !== this.lastflipY) {
this.lastflipY = flip;
if (this.renderable && this.renderable.flipY) {
// flip the animation
this.renderable.flipY(flip);
}
// flip the collision box
this.collisionBox.flipY(this.height);
}
},
/**
* helper function for platform games: <br>
* make the entity move left of right<br>
* @name doWalk
* @memberOf me.ObjectEntity
* @function
* @param {Boolean} left will automatically flip horizontally the entity sprite
* @protected
* @deprecated
* @example
* if (me.input.isKeyPressed('left'))
* {
* this.doWalk(true);
* }
* else if (me.input.isKeyPressed('right'))
* {
* this.doWalk(false);
* }
*/
doWalk : function(left) {
this.flipX(left);
this.vel.x += (left) ? -this.accel.x * me.timer.tick : this.accel.x * me.timer.tick;
},
/**
* helper function for platform games: <br>
* make the entity move up and down<br>
* only valid is the player is on a ladder
* @name doClimb
* @memberOf me.ObjectEntity
* @function
* @param {Boolean} up will automatically flip vertically the entity sprite
* @protected
* @deprecated
* @example
* if (me.input.isKeyPressed('up'))
* {
* this.doClimb(true);
* }
* else if (me.input.isKeyPressed('down'))
* {
* this.doClimb(false);
* }
*/
doClimb : function(up) {
// add the player x acceleration to the y velocity
if (this.onladder) {
this.vel.y = (up) ? -this.accel.x * me.timer.tick
: this.accel.x * me.timer.tick;
this.disableTopLadderCollision = !up;
return true;
}
return false;
},
/**
* helper function for platform games: <br>
* make the entity jump<br>
* @name doJump
* @memberOf me.ObjectEntity
* @function
* @protected
* @deprecated
*/
doJump : function() {
// only jump if standing
if (!this.jumping && !this.falling) {
this.vel.y = -this.maxVel.y * me.timer.tick;
this.jumping = true;
return true;
}
return false;
},
/**
* helper function for platform games: <br>
* force to the entity to jump (for double jump)<br>
* @name forceJump
* @memberOf me.ObjectEntity
* @function
* @protected
* @deprecated
*/
forceJump : function() {
this.jumping = this.falling = false;
this.doJump();
},
/**
* return the distance to the specified entity
* @name distanceTo
* @memberOf me.ObjectEntity
* @function
* @param {me.ObjectEntity} entity Entity
* @return {Number} distance
*/
distanceTo: function(e)
{
// the me.Vector2d object also implements the same function, but
// we have to use here the center of both entities
var dx = (this.pos.x + this.hWidth) - (e.pos.x + e.hWidth);
var dy = (this.pos.y + this.hHeight) - (e.pos.y + e.hHeight);
return Math.sqrt(dx*dx+dy*dy);
},
/**
* return the distance to the specified point
* @name distanceToPoint
* @memberOf me.ObjectEntity
* @function
* @param {me.Vector2d} vector vector
* @return {Number} distance
*/
distanceToPoint: function(v)
{
// the me.Vector2d object also implements the same function, but
// we have to use here the center of both entities
var dx = (this.pos.x + this.hWidth) - (v.x);
var dy = (this.pos.y + this.hHeight) - (v.y);
return Math.sqrt(dx*dx+dy*dy);
},
/**
* return the angle to the specified entity
* @name angleTo
* @memberOf me.ObjectEntity
* @function
* @param {me.ObjectEntity} entity Entity
* @return {Number} angle in radians
*/
angleTo: function(e)
{
// the me.Vector2d object also implements the same function, but
// we have to use here the center of both entities
var ax = (e.pos.x + e.hWidth) - (this.pos.x + this.hWidth);
var ay = (e.pos.y + e.hHeight) - (this.pos.y + this.hHeight);
return Math.atan2(ay, ax);
},
/**
* return the angle to the specified point
* @name angleToPoint
* @memberOf me.ObjectEntity
* @function
* @param {me.Vector2d} vector vector
* @return {Number} angle in radians
*/
angleToPoint: function(v)
{
// the me.Vector2d object also implements the same function, but
// we have to use here the center of both entities
var ax = (v.x) - (this.pos.x + this.hWidth);
var ay = (v.y) - (this.pos.y + this.hHeight);
return Math.atan2(ay, ax);
},
/**
* handle the player movement on a slope
* and update vel value
* @ignore
*/
checkSlope : function(tile, left) {
// first make the object stick to the tile
this.pos.y = tile.pos.y - this.height;
// normally the check should be on the object center point,
// but since the collision check is done on corner, we must do the same thing here
if (left)
this.slopeY = tile.height - (this.collisionBox.right + this.vel.x - tile.pos.x);
else
this.slopeY = (this.collisionBox.left + this.vel.x - tile.pos.x);
// cancel y vel
this.vel.y = 0;
// set player position (+ workaround when entering/exiting slopes tile)
this.pos.y += this.slopeY.clamp(0, tile.height);
},
/**
* compute the new velocity value
* @ignore
*/
computeVelocity : function(vel) {
// apply gravity (if any)
if (this.gravity) {
// apply a constant gravity (if not on a ladder)
vel.y += !this.onladder?(this.gravity * me.timer.tick):0;
// check if falling / jumping
this.falling = (vel.y > 0);
this.jumping = this.falling?false:this.jumping;
}
// apply friction
if (this.friction.x)
vel.x = me.utils.applyFriction(vel.x,this.friction.x);
if (this.friction.y)
vel.y = me.utils.applyFriction(vel.y,this.friction.y);
// cap velocity
if (vel.y !== 0)
vel.y = vel.y.clamp(-this.maxVel.y,this.maxVel.y);
if (vel.x !== 0)
vel.x = vel.x.clamp(-this.maxVel.x,this.maxVel.x);
},
/**
* handle the player movement, "trying" to update his position<br>
* @name updateMovement
* @memberOf me.ObjectEntity
* @function
* @return {me.Vector2d} a collision vector
* @example
* // make the player move
* if (me.input.isKeyPressed('left'))
* {
* this.vel.x -= this.accel.x * me.timer.tick;
* }
* else if (me.input.isKeyPressed('right'))
* {
* this.vel.x += this.accel.x * me.timer.tick;
* }
* // update player position
* var res = this.updateMovement();
*
* // check for collision result with the environment
* if (res.x != 0)
* {
* // x axis
* if (res.x<0)
* console.log("x axis : left side !");
* else
* console.log("x axis : right side !");
* }
* else if(res.y != 0)
* {
* // y axis
* if (res.y<0)
* console.log("y axis : top side !");
* else
* console.log("y axis : bottom side !");
*
* // display the tile type
* console.log(res.yprop.type)
* }
*
* // check player status after collision check
* var updated = (this.vel.x!=0 || this.vel.y!=0);
*/
updateMovement : function() {
this.computeVelocity(this.vel);
// Adjust position only on collidable object
var collision;
if (this.collidable) {
// check for collision
collision = this.collisionMap.checkCollision(this.collisionBox, this.vel);
// update some flags
this.onslope = collision.yprop.isSlope || collision.xprop.isSlope;
// clear the ladder flag
this.onladder = false;
// y collision
if (collision.y) {
// going down, collision with the floor
this.onladder = collision.yprop.isLadder || collision.yprop.isTopLadder;
if (collision.y > 0) {
if (collision.yprop.isSolid ||
(collision.yprop.isPlatform && (this.collisionBox.bottom - 1 <= collision.ytile.pos.y)) ||
(collision.yprop.isTopLadder && !this.disableTopLadderCollision)) {
// adjust position to the corresponding tile
this.pos.y = ~~this.pos.y;
this.vel.y = (this.falling) ?collision.ytile.pos.y - this.collisionBox.bottom: 0 ;
this.falling = false;
}
else if (collision.yprop.isSlope && !this.jumping) {
// we stop falling
this.checkSlope(collision.ytile, collision.yprop.isLeftSlope);
this.falling = false;
}
else if (collision.yprop.isBreakable) {
if (this.canBreakTile) {
// remove the tile
me.game.currentLevel.clearTile(collision.ytile.col, collision.ytile.row);
if (this.onTileBreak)
this.onTileBreak();
}
else {
// adjust position to the corresponding tile
this.pos.y = ~~this.pos.y;
this.vel.y = (this.falling) ?collision.ytile.pos.y - this.collisionBox.bottom: 0;
this.falling = false;
}
}
}
// going up, collision with ceiling
else if (collision.y < 0) {
if (!collision.yprop.isPlatform && !collision.yprop.isLadder && !collision.yprop.isTopLadder) {
this.falling = true;
// cancel the y velocity
this.vel.y = 0;
}
}
}
// x collision
if (collision.x) {
this.onladder = collision.xprop.isLadder || collision.yprop.isTopLadder;
if (collision.xprop.isSlope && !this.jumping) {
this.checkSlope(collision.xtile, collision.xprop.isLeftSlope);
this.falling = false;
} else {
// can walk through the platform & ladder
if (!collision.xprop.isPlatform && !collision.xprop.isLadder && !collision.xprop.isTopLadder) {
if (collision.xprop.isBreakable && this.canBreakTile) {
// remove the tile
me.game.currentLevel.clearTile(collision.xtile.col, collision.xtile.row);
if (this.onTileBreak) {
this.onTileBreak();
}
} else {
this.vel.x = 0;
}
}
}
}
}
// update player position
this.pos.add(this.vel);
// returns the collision "vector"
return collision;
},
/**
* Checks if this entity collides with others entities.
* @public
* @name collide
* @memberOf me.ObjectEntity
* @function
* @param {Boolean} [multiple=false] check for multiple collision
* @return {me.Vector2d} collision vector or an array of collision vector (if multiple collision){@link me.Rect#collideVsAABB}
* @example
* // update player movement
* this.updateMovement();
*
* // check for collision with other objects
* res = this.collide();
*
* // check if we collide with an enemy :
* if (res && (res.obj.type == me.game.ENEMY_OBJECT))
* {
* if (res.x != 0)
* {
* // x axis
* if (res.x<0)
* console.log("x axis : left side !");
* else
* console.log("x axis : right side !");
* }
* else
* {
* // y axis
* if (res.y<0)
* console.log("y axis : top side !");
* else
* console.log("y axis : bottom side !");
* }
* }
*/
collide : function(multiple) {
return me.game.collide(this, multiple || false);
},
/**
* Checks if the specified entity collides with others entities of the specified type.
* @public
* @name collideType
* @memberOf me.ObjectEntity
* @function
* @param {String} type Entity type to be tested for collision
* @param {Boolean} [multiple=false] check for multiple collision
* @return {me.Vector2d} collision vector or an array of collision vector (multiple collision){@link me.Rect#collideVsAABB}
*/
collideType : function(type, multiple) {
return me.game.collideType(this, type, multiple || false);
},
/** @ignore */
update : function() {
if (this.renderable) {
return this.renderable.update();
}
return false;
},
/**
* @ignore
*/
getBounds : function() {
if (this.renderable) {
// translate the renderable position since its
// position is relative to this entity
return this.renderable.getBounds().translateV(this.pos);
}
return null;
},
/**
* object draw<br>
* not to be called by the end user<br>
* called by the game manager on each game loop
* @name draw
* @memberOf me.ObjectEntity
* @function
* @protected
* @param {Context2d} context 2d Context on which draw our object
**/
draw : function(context) {
// draw the sprite if defined
if (this.renderable) {
// translate the renderable position (relative to the entity)
// and keeps it in the entity defined bounds
// anyway to optimize this ?
var x = ~~(this.pos.x + (this.anchorPoint.x * (this.width - this.renderable.width)));
var y = ~~(this.pos.y + (this.anchorPoint.y * (this.height - this.renderable.height)));
context.translate(x, y);
this.renderable.draw(context);
context.translate(-x, -y);
}
},
/**
* Destroy function<br>
* @ignore
*/
destroy : function() {
// free some property objects
if (this.renderable) {
this.renderable.destroy.apply(this.renderable, arguments);
this.renderable = null;
}
this.onDestroyEvent.apply(this, arguments);
this.collisionBox = null;
this.shapes = [];
},
/**
* OnDestroy Notification function<br>
* Called by engine before deleting the object
* @name onDestroyEvent
* @memberOf me.ObjectEntity
* @function
*/
onDestroyEvent : function() {
// to be extended !
}
});
/************************************************************************************/
/* */
/* a Collectable entity */
/* */
/************************************************************************************/
/**
* @class
* @extends me.ObjectEntity
* @memberOf me
* @constructor
* @param {Number} x the x coordinates of the sprite object
* @param {Number} y the y coordinates of the sprite object
* @param {me.ObjectSettings} settings object settings
*/
me.CollectableEntity = me.ObjectEntity.extend(
/** @scope me.CollectableEntity.prototype */
{
/** @ignore */
init : function(x, y, settings) {
// call the parent constructor
this.parent(x, y, settings);
this.type = me.game.COLLECTABLE_OBJECT;
}
});
/************************************************************************************/
/* */
/* a level entity */
/* */
/************************************************************************************/
/**
* @class
* @extends me.ObjectEntity
* @memberOf me
* @constructor
* @param {Number} x the x coordinates of the object
* @param {Number} y the y coordinates of the object
* @param {me.ObjectSettings} settings object settings
*/
me.LevelEntity = me.ObjectEntity.extend(
/** @scope me.LevelEntity.prototype */
{
/** @ignore */
init : function(x, y, settings) {
this.parent(x, y, settings);
this.nextlevel = settings.to;
this.fade = settings.fade;
this.duration = settings.duration;
this.fading = false;
// a temp variable
this.gotolevel = settings.to;
},
/**
* @ignore
*/
onFadeComplete : function() {
me.levelDirector.loadLevel(this.gotolevel);
me.game.viewport.fadeOut(this.fade, this.duration);
},
/**
* go to the specified level
* @name goTo
* @memberOf me.LevelEntity
* @function
* @param {String} [level=this.nextlevel] name of the level to load
* @protected
*/
goTo : function(level) {
this.gotolevel = level || this.nextlevel;
// load a level
//console.log("going to : ", to);
if (this.fade && this.duration) {
if (!this.fading) {
this.fading = true;
me.game.viewport.fadeIn(this.fade, this.duration,
this.onFadeComplete.bind(this));
}
} else {
me.levelDirector.loadLevel(this.gotolevel);
}
},
/** @ignore */
onCollision : function() {
this.goTo();
}
});
/*---------------------------------------------------------*/
// END END END
/*---------------------------------------------------------*/
})(window);
|
(function() {
var a, b, c, d, e, col, otherCol;
module("Backbone.Collection", {
setup: function() {
a = new Backbone.Model({id: 3, label: 'a'});
b = new Backbone.Model({id: 2, label: 'b'});
c = new Backbone.Model({id: 1, label: 'c'});
d = new Backbone.Model({id: 0, label: 'd'});
e = null;
col = new Backbone.Collection([a,b,c,d]);
otherCol = new Backbone.Collection();
}
});
test("new and sort", 6, function() {
var counter = 0;
col.on('sort', function(){ counter++; });
deepEqual(col.pluck('label'), ['a', 'b', 'c', 'd']);
col.comparator = function(a, b) {
return a.id > b.id ? -1 : 1;
};
col.sort();
equal(counter, 1);
deepEqual(col.pluck('label'), ['a', 'b', 'c', 'd']);
col.comparator = function(model) { return model.id; };
col.sort();
equal(counter, 2);
deepEqual(col.pluck('label'), ['d', 'c', 'b', 'a']);
equal(col.length, 4);
});
test("String comparator.", 1, function() {
var collection = new Backbone.Collection([
{id: 3},
{id: 1},
{id: 2}
], {comparator: 'id'});
deepEqual(collection.pluck('id'), [1, 2, 3]);
});
test("new and parse", 3, function() {
var Collection = Backbone.Collection.extend({
parse : function(data) {
return _.filter(data, function(datum) {
return datum.a % 2 === 0;
});
}
});
var models = [{a: 1}, {a: 2}, {a: 3}, {a: 4}];
var collection = new Collection(models, {parse: true});
strictEqual(collection.length, 2);
strictEqual(collection.first().get('a'), 2);
strictEqual(collection.last().get('a'), 4);
});
test("clone preserves model and comparator", 3, function() {
var Model = Backbone.Model.extend();
var comparator = function(model){ return model.id; };
var collection = new Backbone.Collection([{id: 1}], {
model: Model,
comparator: comparator
}).clone();
collection.add({id: 2});
ok(collection.at(0) instanceof Model);
ok(collection.at(1) instanceof Model);
strictEqual(collection.comparator, comparator);
});
test("get", 6, function() {
equal(col.get(0), d);
equal(col.get(d.clone()), d);
equal(col.get(2), b);
equal(col.get({id: 1}), c);
equal(col.get(c.clone()), c);
equal(col.get(col.first().cid), col.first());
});
test("get with non-default ids", 5, function() {
var MongoModel = Backbone.Model.extend({idAttribute: '_id'});
var model = new MongoModel({_id: 100});
var col = new Backbone.Collection([model], {model: MongoModel});
equal(col.get(100), model);
equal(col.get(model.cid), model);
equal(col.get(model), model);
equal(col.get(101), void 0);
var col2 = new Backbone.Collection();
col2.model = MongoModel;
col2.add(model.attributes);
equal(col2.get(model.clone()), col2.first());
});
test('get with "undefined" id', function() {
var collection = new Backbone.Collection([{id: 1}, {id: 'undefined'}]);
equal(collection.get(1).id, 1);
});
test("update index when id changes", 4, function() {
var col = new Backbone.Collection();
col.add([
{id : 0, name : 'one'},
{id : 1, name : 'two'}
]);
var one = col.get(0);
equal(one.get('name'), 'one');
col.on('change:name', function (model) { ok(this.get(model)); });
one.set({name: 'dalmatians', id : 101});
equal(col.get(0), null);
equal(col.get(101).get('name'), 'dalmatians');
});
test("at", 2, function() {
equal(col.at(2), c);
equal(col.at(-2), c);
});
test("pluck", 1, function() {
equal(col.pluck('label').join(' '), 'a b c d');
});
test("add", 14, function() {
var added, opts, secondAdded;
added = opts = secondAdded = null;
e = new Backbone.Model({id: 10, label : 'e'});
otherCol.add(e);
otherCol.on('add', function() {
secondAdded = true;
});
col.on('add', function(model, collection, options){
added = model.get('label');
opts = options;
});
col.add(e, {amazing: true});
equal(added, 'e');
equal(col.length, 5);
equal(col.last(), e);
equal(otherCol.length, 1);
equal(secondAdded, null);
ok(opts.amazing);
var f = new Backbone.Model({id: 20, label : 'f'});
var g = new Backbone.Model({id: 21, label : 'g'});
var h = new Backbone.Model({id: 22, label : 'h'});
var atCol = new Backbone.Collection([f, g, h]);
equal(atCol.length, 3);
atCol.add(e, {at: 1});
equal(atCol.length, 4);
equal(atCol.at(1), e);
equal(atCol.last(), h);
var coll = new Backbone.Collection(new Array(2));
var addCount = 0;
coll.on('add', function(){
addCount += 1;
});
coll.add([undefined, f, g]);
equal(coll.length, 5);
equal(addCount, 3);
coll.add(new Array(4));
equal(coll.length, 9);
equal(addCount, 7);
});
test("add multiple models", 6, function() {
var col = new Backbone.Collection([{at: 0}, {at: 1}, {at: 9}]);
col.add([{at: 2}, {at: 3}, {at: 4}, {at: 5}, {at: 6}, {at: 7}, {at: 8}], {at: 2});
for (var i = 0; i <= 5; i++) {
equal(col.at(i).get('at'), i);
}
});
test("add; at should have preference over comparator", 1, function() {
var Col = Backbone.Collection.extend({
comparator: function(a,b) {
return a.id > b.id ? -1 : 1;
}
});
var col = new Col([{id: 2}, {id: 3}]);
col.add(new Backbone.Model({id: 1}), {at: 1});
equal(col.pluck('id').join(' '), '3 1 2');
});
test("add; at should add to the end if the index is out of bounds", 1, function() {
var col = new Backbone.Collection([{id: 2}, {id: 3}]);
col.add(new Backbone.Model({id: 1}), {at: 5});
equal(col.pluck('id').join(' '), '2 3 1');
});
test("can't add model to collection twice", function() {
var col = new Backbone.Collection([{id: 1}, {id: 2}, {id: 1}, {id: 2}, {id: 3}]);
equal(col.pluck('id').join(' '), '1 2 3');
});
test("can't add different model with same id to collection twice", 1, function() {
var col = new Backbone.Collection;
col.unshift({id: 101});
col.add({id: 101});
equal(col.length, 1);
});
test("merge in duplicate models with {merge: true}", 3, function() {
var col = new Backbone.Collection;
col.add([{id: 1, name: 'Moe'}, {id: 2, name: 'Curly'}, {id: 3, name: 'Larry'}]);
col.add({id: 1, name: 'Moses'});
equal(col.first().get('name'), 'Moe');
col.add({id: 1, name: 'Moses'}, {merge: true});
equal(col.first().get('name'), 'Moses');
col.add({id: 1, name: 'Tim'}, {merge: true, silent: true});
equal(col.first().get('name'), 'Tim');
});
test("add model to multiple collections", 10, function() {
var counter = 0;
var e = new Backbone.Model({id: 10, label : 'e'});
e.on('add', function(model, collection) {
counter++;
equal(e, model);
if (counter > 1) {
equal(collection, colF);
} else {
equal(collection, colE);
}
});
var colE = new Backbone.Collection([]);
colE.on('add', function(model, collection) {
equal(e, model);
equal(colE, collection);
});
var colF = new Backbone.Collection([]);
colF.on('add', function(model, collection) {
equal(e, model);
equal(colF, collection);
});
colE.add(e);
equal(e.collection, colE);
colF.add(e);
equal(e.collection, colE);
});
test("add model with parse", 1, function() {
var Model = Backbone.Model.extend({
parse: function(obj) {
obj.value += 1;
return obj;
}
});
var Col = Backbone.Collection.extend({model: Model});
var col = new Col;
col.add({value: 1}, {parse: true});
equal(col.at(0).get('value'), 2);
});
test("add with parse and merge", function() {
var collection = new Backbone.Collection();
collection.parse = function(attrs) {
return _.map(attrs, function(model) {
if (model.model) return model.model;
return model;
});
};
collection.add({id: 1});
collection.add({model: {id: 1, name: 'Alf'}}, {parse: true, merge: true});
equal(collection.first().get('name'), 'Alf');
});
test("add model to collection with sort()-style comparator", 3, function() {
var col = new Backbone.Collection;
col.comparator = function(a, b) {
return a.get('name') < b.get('name') ? -1 : 1;
};
var tom = new Backbone.Model({name: 'Tom'});
var rob = new Backbone.Model({name: 'Rob'});
var tim = new Backbone.Model({name: 'Tim'});
col.add(tom);
col.add(rob);
col.add(tim);
equal(col.indexOf(rob), 0);
equal(col.indexOf(tim), 1);
equal(col.indexOf(tom), 2);
});
test("comparator that depends on `this`", 2, function() {
var col = new Backbone.Collection;
col.negative = function(num) {
return -num;
};
col.comparator = function(a) {
return this.negative(a.id);
};
col.add([{id: 1}, {id: 2}, {id: 3}]);
deepEqual(col.pluck('id'), [3, 2, 1]);
col.comparator = function(a, b) {
return this.negative(b.id) - this.negative(a.id);
};
col.sort();
deepEqual(col.pluck('id'), [1, 2, 3]);
});
test("remove", 11, function() {
var removed = null;
var result = null;
col.on('remove', function(model, col, options) {
removed = model.get('label');
equal(options.index, 3);
equal(col.get(model), undefined, '#3693: model cannot be fetched from collection');
});
result = col.remove(d);
equal(removed, 'd');
strictEqual(result, d);
//if we try to remove d again, it's not going to actually get removed
result = col.remove(d);
strictEqual(result, undefined);
equal(col.length, 3);
equal(col.first(), a);
col.off();
result = col.remove([c, d]);
equal(result.length, 1, 'only returns removed models');
equal(result[0], c, 'only returns removed models');
result = col.remove([c, b]);
equal(result.length, 1, 'only returns removed models');
equal(result[0], b, 'only returns removed models');
});
test("add and remove return values", 13, function() {
var Even = Backbone.Model.extend({
validate: function(attrs) {
if (attrs.id % 2 !== 0) return "odd";
}
});
var col = new Backbone.Collection;
col.model = Even;
var list = col.add([{id: 2}, {id: 4}], {validate: true});
equal(list.length, 2);
ok(list[0] instanceof Backbone.Model);
equal(list[1], col.last());
equal(list[1].get('id'), 4);
list = col.add([{id: 3}, {id: 6}], {validate: true});
equal(col.length, 3);
equal(list[0], false);
equal(list[1].get('id'), 6);
var result = col.add({id: 6});
equal(result.cid, list[1].cid);
result = col.remove({id: 6});
equal(col.length, 2);
equal(result.id, 6);
list = col.remove([{id: 2}, {id: 8}]);
equal(col.length, 1);
equal(list[0].get('id'), 2);
equal(list[1], null);
});
test("shift and pop", 2, function() {
var col = new Backbone.Collection([{a: 'a'}, {b: 'b'}, {c: 'c'}]);
equal(col.shift().get('a'), 'a');
equal(col.pop().get('c'), 'c');
});
test("slice", 2, function() {
var col = new Backbone.Collection([{a: 'a'}, {b: 'b'}, {c: 'c'}]);
var array = col.slice(1, 3);
equal(array.length, 2);
equal(array[0].get('b'), 'b');
});
test("events are unbound on remove", 3, function() {
var counter = 0;
var dj = new Backbone.Model();
var emcees = new Backbone.Collection([dj]);
emcees.on('change', function(){ counter++; });
dj.set({name : 'Kool'});
equal(counter, 1);
emcees.reset([]);
equal(dj.collection, undefined);
dj.set({name : 'Shadow'});
equal(counter, 1);
});
test("remove in multiple collections", 7, function() {
var modelData = {
id : 5,
title : 'Othello'
};
var passed = false;
var e = new Backbone.Model(modelData);
var f = new Backbone.Model(modelData);
f.on('remove', function() {
passed = true;
});
var colE = new Backbone.Collection([e]);
var colF = new Backbone.Collection([f]);
ok(e != f);
ok(colE.length === 1);
ok(colF.length === 1);
colE.remove(e);
equal(passed, false);
ok(colE.length === 0);
colF.remove(e);
ok(colF.length === 0);
equal(passed, true);
});
test("remove same model in multiple collection", 16, function() {
var counter = 0;
var e = new Backbone.Model({id: 5, title: 'Othello'});
e.on('remove', function(model, collection) {
counter++;
equal(e, model);
if (counter > 1) {
equal(collection, colE);
} else {
equal(collection, colF);
}
});
var colE = new Backbone.Collection([e]);
colE.on('remove', function(model, collection) {
equal(e, model);
equal(colE, collection);
});
var colF = new Backbone.Collection([e]);
colF.on('remove', function(model, collection) {
equal(e, model);
equal(colF, collection);
});
equal(colE, e.collection);
colF.remove(e);
ok(colF.length === 0);
ok(colE.length === 1);
equal(counter, 1);
equal(colE, e.collection);
colE.remove(e);
equal(null, e.collection);
ok(colE.length === 0);
equal(counter, 2);
});
test("model destroy removes from all collections", 3, function() {
var e = new Backbone.Model({id: 5, title: 'Othello'});
e.sync = function(method, model, options) { options.success(); };
var colE = new Backbone.Collection([e]);
var colF = new Backbone.Collection([e]);
e.destroy();
ok(colE.length === 0);
ok(colF.length === 0);
equal(undefined, e.collection);
});
test("Colllection: non-persisted model destroy removes from all collections", 3, function() {
var e = new Backbone.Model({title: 'Othello'});
e.sync = function(method, model, options) { throw "should not be called"; };
var colE = new Backbone.Collection([e]);
var colF = new Backbone.Collection([e]);
e.destroy();
ok(colE.length === 0);
ok(colF.length === 0);
equal(undefined, e.collection);
});
test("fetch", 4, function() {
var collection = new Backbone.Collection;
collection.url = '/test';
collection.fetch();
equal(this.syncArgs.method, 'read');
equal(this.syncArgs.model, collection);
equal(this.syncArgs.options.parse, true);
collection.fetch({parse: false});
equal(this.syncArgs.options.parse, false);
});
test("fetch with an error response triggers an error event", 1, function () {
var collection = new Backbone.Collection();
collection.on('error', function () {
ok(true);
});
collection.sync = function (method, model, options) { options.error(); };
collection.fetch();
});
test("#3283 - fetch with an error response calls error with context", 1, function () {
var collection = new Backbone.Collection();
var obj = {};
var options = {
context: obj,
error: function() {
equal(this, obj);
}
};
collection.sync = function (method, model, options) {
options.error.call(options.context);
};
collection.fetch(options);
});
test("ensure fetch only parses once", 1, function() {
var collection = new Backbone.Collection;
var counter = 0;
collection.parse = function(models) {
counter++;
return models;
};
collection.url = '/test';
collection.fetch();
this.syncArgs.options.success([]);
equal(counter, 1);
});
test("create", 4, function() {
var collection = new Backbone.Collection;
collection.url = '/test';
var model = collection.create({label: 'f'}, {wait: true});
equal(this.syncArgs.method, 'create');
equal(this.syncArgs.model, model);
equal(model.get('label'), 'f');
equal(model.collection, collection);
});
test("create with validate:true enforces validation", 3, function() {
var ValidatingModel = Backbone.Model.extend({
validate: function(attrs) {
return "fail";
}
});
var ValidatingCollection = Backbone.Collection.extend({
model: ValidatingModel
});
var col = new ValidatingCollection();
col.on('invalid', function (collection, error, options) {
equal(error, "fail");
equal(options.validationError, 'fail');
});
equal(col.create({"foo":"bar"}, {validate:true}), false);
});
test("create will pass extra options to success callback", 1, function () {
var Model = Backbone.Model.extend({
sync: function (method, model, options) {
_.extend(options, {specialSync: true});
return Backbone.Model.prototype.sync.call(this, method, model, options);
}
});
var Collection = Backbone.Collection.extend({
model: Model,
url: '/test'
});
var collection = new Collection;
var success = function (model, response, options) {
ok(options.specialSync, "Options were passed correctly to callback");
};
collection.create({}, {success: success});
this.ajaxSettings.success();
});
test("create with wait:true should not call collection.parse", 0, function() {
var Collection = Backbone.Collection.extend({
url: '/test',
parse: function () {
ok(false);
}
});
var collection = new Collection;
collection.create({}, {wait: true});
this.ajaxSettings.success();
});
test("a failing create returns model with errors", function() {
var ValidatingModel = Backbone.Model.extend({
validate: function(attrs) {
return "fail";
}
});
var ValidatingCollection = Backbone.Collection.extend({
model: ValidatingModel
});
var col = new ValidatingCollection();
var m = col.create({"foo":"bar"});
equal(m.validationError, 'fail');
equal(col.length, 1);
});
test("initialize", 1, function() {
var Collection = Backbone.Collection.extend({
initialize: function() {
this.one = 1;
}
});
var coll = new Collection;
equal(coll.one, 1);
});
test("toJSON", 1, function() {
equal(JSON.stringify(col), '[{"id":3,"label":"a"},{"id":2,"label":"b"},{"id":1,"label":"c"},{"id":0,"label":"d"}]');
});
test("where and findWhere", 8, function() {
var model = new Backbone.Model({a: 1});
var coll = new Backbone.Collection([
model,
{a: 1},
{a: 1, b: 2},
{a: 2, b: 2},
{a: 3}
]);
equal(coll.where({a: 1}).length, 3);
equal(coll.where({a: 2}).length, 1);
equal(coll.where({a: 3}).length, 1);
equal(coll.where({b: 1}).length, 0);
equal(coll.where({b: 2}).length, 2);
equal(coll.where({a: 1, b: 2}).length, 1);
equal(coll.findWhere({a: 1}), model);
equal(coll.findWhere({a: 4}), void 0);
});
test("Underscore methods", 19, function() {
equal(col.map(function(model){ return model.get('label'); }).join(' '), 'a b c d');
equal(col.some(function(model){ return model.id === 100; }), false);
equal(col.some(function(model){ return model.id === 0; }), true);
equal(col.indexOf(b), 1);
equal(col.size(), 4);
equal(col.rest().length, 3);
ok(!_.includes(col.rest(), a));
ok(_.includes(col.rest(), d));
ok(!col.isEmpty());
ok(!_.includes(col.without(d), d));
var wrapped = col.chain();
equal(wrapped.map('id').max().value(), 3);
equal(wrapped.map('id').min().value(), 0);
deepEqual(wrapped
.filter(function(o){ return o.id % 2 === 0; })
.map(function(o){ return o.id * 2; })
.value(),
[4, 0]);
deepEqual(col.difference([c, d]), [a, b]);
ok(col.includes(col.sample()));
var first = col.first();
deepEqual(col.groupBy(function(model){ return model.id; })[first.id], [first]);
deepEqual(col.countBy(function(model){ return model.id; }), {0: 1, 1: 1, 2: 1, 3: 1});
deepEqual(col.sortBy(function(model){ return model.id; })[0], col.at(3));
ok(col.indexBy('id')[first.id] === first);
});
test("Underscore methods with object-style and property-style iteratee", 26, function () {
var model = new Backbone.Model({a: 4, b: 1, e: 3});
var coll = new Backbone.Collection([
{a: 1, b: 1},
{a: 2, b: 1, c: 1},
{a: 3, b: 1},
model
]);
equal(coll.find({a: 0}), undefined);
deepEqual(coll.find({a: 4}), model);
equal(coll.find('d'), undefined);
deepEqual(coll.find('e'), model);
equal(coll.filter({a: 0}), false);
deepEqual(coll.filter({a: 4}), [model]);
equal(coll.some({a: 0}), false);
equal(coll.some({a: 1}), true);
equal(coll.reject({a: 0}).length, 4);
deepEqual(coll.reject({a: 4}), _.without(coll.models, model));
equal(coll.every({a: 0}), false);
equal(coll.every({b: 1}), true);
deepEqual(coll.partition({a: 0})[0], []);
deepEqual(coll.partition({a: 0})[1], coll.models);
deepEqual(coll.partition({a: 4})[0], [model]);
deepEqual(coll.partition({a: 4})[1], _.without(coll.models, model));
deepEqual(coll.map({a: 2}), [false, true, false, false]);
deepEqual(coll.map('a'), [1, 2, 3, 4]);
deepEqual(coll.sortBy('a')[3], model);
deepEqual(coll.sortBy('e')[0], model);
deepEqual(coll.countBy({a: 4}), {'false': 3, 'true': 1});
deepEqual(coll.countBy('d'), {'undefined': 4});
equal(coll.findIndex({b: 1}), 0);
equal(coll.findIndex({b: 9}), -1);
equal(coll.findLastIndex({b: 1}), 3);
equal(coll.findLastIndex({b: 9}), -1);
});
test("reset", 16, function() {
var resetCount = 0;
var models = col.models;
col.on('reset', function() { resetCount += 1; });
col.reset([]);
equal(resetCount, 1);
equal(col.length, 0);
equal(col.last(), null);
col.reset(models);
equal(resetCount, 2);
equal(col.length, 4);
equal(col.last(), d);
col.reset(_.map(models, function(m){ return m.attributes; }));
equal(resetCount, 3);
equal(col.length, 4);
ok(col.last() !== d);
ok(_.isEqual(col.last().attributes, d.attributes));
col.reset();
equal(col.length, 0);
equal(resetCount, 4);
var f = new Backbone.Model({id: 20, label : 'f'});
col.reset([undefined, f]);
equal(col.length, 2);
equal(resetCount, 5);
col.reset(new Array(4));
equal(col.length, 4);
equal(resetCount, 6);
});
test ("reset with different values", function(){
var col = new Backbone.Collection({id: 1});
col.reset({id: 1, a: 1});
equal(col.get(1).get('a'), 1);
});
test("same references in reset", function() {
var model = new Backbone.Model({id: 1});
var collection = new Backbone.Collection({id: 1});
collection.reset(model);
equal(collection.get(1), model);
});
test("reset passes caller options", 3, function() {
var Model = Backbone.Model.extend({
initialize: function(attrs, options) {
this.model_parameter = options.model_parameter;
}
});
var col = new (Backbone.Collection.extend({ model: Model }))();
col.reset([{ astring: "green", anumber: 1 }, { astring: "blue", anumber: 2 }], { model_parameter: 'model parameter' });
equal(col.length, 2);
col.each(function(model) {
equal(model.model_parameter, 'model parameter');
});
});
test("reset does not alter options by reference", 2, function() {
var col = new Backbone.Collection([{id:1}]);
var origOpts = {};
col.on("reset", function(col, opts){
equal(origOpts.previousModels, undefined);
equal(opts.previousModels[0].id, 1);
});
col.reset([], origOpts);
});
test("trigger custom events on models", 1, function() {
var fired = null;
a.on("custom", function() { fired = true; });
a.trigger("custom");
equal(fired, true);
});
test("add does not alter arguments", 2, function(){
var attrs = {};
var models = [attrs];
new Backbone.Collection().add(models);
equal(models.length, 1);
ok(attrs === models[0]);
});
test("#714: access `model.collection` in a brand new model.", 2, function() {
var collection = new Backbone.Collection;
collection.url = '/test';
var Model = Backbone.Model.extend({
set: function(attrs) {
equal(attrs.prop, 'value');
equal(this.collection, collection);
return this;
}
});
collection.model = Model;
collection.create({prop: 'value'});
});
test("#574, remove its own reference to the .models array.", 2, function() {
var col = new Backbone.Collection([
{id: 1}, {id: 2}, {id: 3}, {id: 4}, {id: 5}, {id: 6}
]);
equal(col.length, 6);
col.remove(col.models);
equal(col.length, 0);
});
test("#861, adding models to a collection which do not pass validation, with validate:true", 2, function() {
var Model = Backbone.Model.extend({
validate: function(attrs) {
if (attrs.id == 3) return "id can't be 3";
}
});
var Collection = Backbone.Collection.extend({
model: Model
});
var collection = new Collection;
collection.on("invalid", function() { ok(true); });
collection.add([{id: 1}, {id: 2}, {id: 3}, {id: 4}, {id: 5}, {id: 6}], {validate:true});
deepEqual(collection.pluck("id"), [1, 2, 4, 5, 6]);
});
test("Invalid models are discarded with validate:true.", 5, function() {
var collection = new Backbone.Collection;
collection.on('test', function() { ok(true); });
collection.model = Backbone.Model.extend({
validate: function(attrs){ if (!attrs.valid) return 'invalid'; }
});
var model = new collection.model({id: 1, valid: true});
collection.add([model, {id: 2}], {validate:true});
model.trigger('test');
ok(collection.get(model.cid));
ok(collection.get(1));
ok(!collection.get(2));
equal(collection.length, 1);
});
test("multiple copies of the same model", 3, function() {
var col = new Backbone.Collection();
var model = new Backbone.Model();
col.add([model, model]);
equal(col.length, 1);
col.add([{id: 1}, {id: 1}]);
equal(col.length, 2);
equal(col.last().id, 1);
});
test("#964 - collection.get return inconsistent", 2, function() {
var c = new Backbone.Collection();
ok(c.get(null) === undefined);
ok(c.get() === undefined);
});
test("#1112 - passing options.model sets collection.model", 2, function() {
var Model = Backbone.Model.extend({});
var c = new Backbone.Collection([{id: 1}], {model: Model});
ok(c.model === Model);
ok(c.at(0) instanceof Model);
});
test("null and undefined are invalid ids.", 2, function() {
var model = new Backbone.Model({id: 1});
var collection = new Backbone.Collection([model]);
model.set({id: null});
ok(!collection.get('null'));
model.set({id: 1});
model.set({id: undefined});
ok(!collection.get('undefined'));
});
test("falsy comparator", 4, function(){
var Col = Backbone.Collection.extend({
comparator: function(model){ return model.id; }
});
var col = new Col();
var colFalse = new Col(null, {comparator: false});
var colNull = new Col(null, {comparator: null});
var colUndefined = new Col(null, {comparator: undefined});
ok(col.comparator);
ok(!colFalse.comparator);
ok(!colNull.comparator);
ok(colUndefined.comparator);
});
test("#1355 - `options` is passed to success callbacks", 2, function(){
var m = new Backbone.Model({x:1});
var col = new Backbone.Collection();
var opts = {
opts: true,
success: function(collection, resp, options) {
ok(options.opts);
}
};
col.sync = m.sync = function( method, collection, options ){
options.success({});
};
col.fetch(opts);
col.create(m, opts);
});
test("#1412 - Trigger 'request' and 'sync' events.", 4, function() {
var collection = new Backbone.Collection;
collection.url = '/test';
Backbone.ajax = function(settings){ settings.success(); };
collection.on('request', function(obj, xhr, options) {
ok(obj === collection, "collection has correct 'request' event after fetching");
});
collection.on('sync', function(obj, response, options) {
ok(obj === collection, "collection has correct 'sync' event after fetching");
});
collection.fetch();
collection.off();
collection.on('request', function(obj, xhr, options) {
ok(obj === collection.get(1), "collection has correct 'request' event after one of its models save");
});
collection.on('sync', function(obj, response, options) {
ok(obj === collection.get(1), "collection has correct 'sync' event after one of its models save");
});
collection.create({id: 1});
collection.off();
});
test("#3283 - fetch, create calls success with context", 2, function() {
var collection = new Backbone.Collection;
collection.url = '/test';
Backbone.ajax = function(settings) {
settings.success.call(settings.context);
};
var obj = {};
var options = {
context: obj,
success: function() {
equal(this, obj);
}
};
collection.fetch(options);
collection.create({id: 1}, options);
});
test("#1447 - create with wait adds model.", 1, function() {
var collection = new Backbone.Collection;
var model = new Backbone.Model;
model.sync = function(method, model, options){ options.success(); };
collection.on('add', function(){ ok(true); });
collection.create(model, {wait: true});
});
test("#1448 - add sorts collection after merge.", 1, function() {
var collection = new Backbone.Collection([
{id: 1, x: 1},
{id: 2, x: 2}
]);
collection.comparator = function(model){ return model.get('x'); };
collection.add({id: 1, x: 3}, {merge: true});
deepEqual(collection.pluck('id'), [2, 1]);
});
test("#1655 - groupBy can be used with a string argument.", 3, function() {
var collection = new Backbone.Collection([{x: 1}, {x: 2}]);
var grouped = collection.groupBy('x');
strictEqual(_.keys(grouped).length, 2);
strictEqual(grouped[1][0].get('x'), 1);
strictEqual(grouped[2][0].get('x'), 2);
});
test("#1655 - sortBy can be used with a string argument.", 1, function() {
var collection = new Backbone.Collection([{x: 3}, {x: 1}, {x: 2}]);
var values = _.map(collection.sortBy('x'), function(model) {
return model.get('x');
});
deepEqual(values, [1, 2, 3]);
});
test("#1604 - Removal during iteration.", 0, function() {
var collection = new Backbone.Collection([{}, {}]);
collection.on('add', function() {
collection.at(0).destroy();
});
collection.add({}, {at: 0});
});
test("#1638 - `sort` during `add` triggers correctly.", function() {
var collection = new Backbone.Collection;
collection.comparator = function(model) { return model.get('x'); };
var added = [];
collection.on('add', function(model) {
model.set({x: 3});
collection.sort();
added.push(model.id);
});
collection.add([{id: 1, x: 1}, {id: 2, x: 2}]);
deepEqual(added, [1, 2]);
});
test("fetch parses models by default", 1, function() {
var model = {};
var Collection = Backbone.Collection.extend({
url: 'test',
model: Backbone.Model.extend({
parse: function(resp) {
strictEqual(resp, model);
}
})
});
new Collection().fetch();
this.ajaxSettings.success([model]);
});
test("`sort` shouldn't always fire on `add`", 1, function() {
var c = new Backbone.Collection([{id: 1}, {id: 2}, {id: 3}], {
comparator: 'id'
});
c.sort = function(){ ok(true); };
c.add([]);
c.add({id: 1});
c.add([{id: 2}, {id: 3}]);
c.add({id: 4});
});
test("#1407 parse option on constructor parses collection and models", 2, function() {
var model = {
namespace : [{id: 1}, {id:2}]
};
var Collection = Backbone.Collection.extend({
model: Backbone.Model.extend({
parse: function(model) {
model.name = 'test';
return model;
}
}),
parse: function(model) {
return model.namespace;
}
});
var c = new Collection(model, {parse:true});
equal(c.length, 2);
equal(c.at(0).get('name'), 'test');
});
test("#1407 parse option on reset parses collection and models", 2, function() {
var model = {
namespace : [{id: 1}, {id:2}]
};
var Collection = Backbone.Collection.extend({
model: Backbone.Model.extend({
parse: function(model) {
model.name = 'test';
return model;
}
}),
parse: function(model) {
return model.namespace;
}
});
var c = new Collection();
c.reset(model, {parse:true});
equal(c.length, 2);
equal(c.at(0).get('name'), 'test');
});
test("Reset includes previous models in triggered event.", 1, function() {
var model = new Backbone.Model();
var collection = new Backbone.Collection([model])
.on('reset', function(collection, options) {
deepEqual(options.previousModels, [model]);
});
collection.reset([]);
});
test("set", function() {
var m1 = new Backbone.Model();
var m2 = new Backbone.Model({id: 2});
var m3 = new Backbone.Model();
var c = new Backbone.Collection([m1, m2]);
// Test add/change/remove events
c.on('add', function(model) {
strictEqual(model, m3);
});
c.on('change', function(model) {
strictEqual(model, m2);
});
c.on('remove', function(model) {
strictEqual(model, m1);
});
// remove: false doesn't remove any models
c.set([], {remove: false});
strictEqual(c.length, 2);
// add: false doesn't add any models
c.set([m1, m2, m3], {add: false});
strictEqual(c.length, 2);
// merge: false doesn't change any models
c.set([m1, {id: 2, a: 1}], {merge: false});
strictEqual(m2.get('a'), void 0);
// add: false, remove: false only merges existing models
c.set([m1, {id: 2, a: 0}, m3, {id: 4}], {add: false, remove: false});
strictEqual(c.length, 2);
strictEqual(m2.get('a'), 0);
// default options add/remove/merge as appropriate
c.set([{id: 2, a: 1}, m3]);
strictEqual(c.length, 2);
strictEqual(m2.get('a'), 1);
// Test removing models not passing an argument
c.off('remove').on('remove', function(model) {
ok(model === m2 || model === m3);
});
c.set([]);
strictEqual(c.length, 0);
// Test null models on set doesn't clear collection
c.off();
c.set([{id: 1}]);
c.set();
strictEqual(c.length, 1);
});
test("set with only cids", 3, function() {
var m1 = new Backbone.Model;
var m2 = new Backbone.Model;
var c = new Backbone.Collection;
c.set([m1, m2]);
equal(c.length, 2);
c.set([m1]);
equal(c.length, 1);
c.set([m1, m1, m1, m2, m2], {remove: false});
equal(c.length, 2);
});
test("set with only idAttribute", 3, function() {
var m1 = { _id: 1 };
var m2 = { _id: 2 };
var col = Backbone.Collection.extend({
model: Backbone.Model.extend({
idAttribute: '_id'
})
});
var c = new col;
c.set([m1, m2]);
equal(c.length, 2);
c.set([m1]);
equal(c.length, 1);
c.set([m1, m1, m1, m2, m2], {remove: false});
equal(c.length, 2);
});
test("set + merge with default values defined", function() {
var Model = Backbone.Model.extend({
defaults: {
key: 'value'
}
});
var m = new Model({id: 1});
var col = new Backbone.Collection([m], {model: Model});
equal(col.first().get('key'), 'value');
col.set({id: 1, key: 'other'});
equal(col.first().get('key'), 'other');
col.set({id: 1, other: 'value'});
equal(col.first().get('key'), 'other');
equal(col.length, 1);
});
test('merge without mutation', function () {
var Model = Backbone.Model.extend({
initialize: function (attrs, options) {
if (attrs.child) {
this.set('child', new Model(attrs.child, options), options);
}
}
});
var Collection = Backbone.Collection.extend({model: Model});
var data = [{id: 1, child: {id: 2}}];
var collection = new Collection(data);
equal(collection.first().id, 1);
collection.set(data);
equal(collection.first().id, 1);
collection.set([{id: 2, child: {id: 2}}].concat(data));
deepEqual(collection.pluck('id'), [2, 1]);
});
test("`set` and model level `parse`", function() {
var Model = Backbone.Model.extend({});
var Collection = Backbone.Collection.extend({
model: Model,
parse: function (res) { return _.map(res.models, 'model'); }
});
var model = new Model({id: 1});
var collection = new Collection(model);
collection.set({models: [
{model: {id: 1}},
{model: {id: 2}}
]}, {parse: true});
equal(collection.first(), model);
});
test("`set` data is only parsed once", function() {
var collection = new Backbone.Collection();
collection.model = Backbone.Model.extend({
parse: function (data) {
equal(data.parsed, void 0);
data.parsed = true;
return data;
}
});
collection.set({}, {parse: true});
});
test('`set` matches input order in the absence of a comparator', function () {
var one = new Backbone.Model({id: 1});
var two = new Backbone.Model({id: 2});
var three = new Backbone.Model({id: 3});
var collection = new Backbone.Collection([one, two, three]);
collection.set([{id: 3}, {id: 2}, {id: 1}]);
deepEqual(collection.models, [three, two, one]);
collection.set([{id: 1}, {id: 2}]);
deepEqual(collection.models, [one, two]);
collection.set([two, three, one]);
deepEqual(collection.models, [two, three, one]);
collection.set([{id: 1}, {id: 2}], {remove: false});
deepEqual(collection.models, [two, three, one]);
collection.set([{id: 1}, {id: 2}, {id: 3}], {merge: false});
deepEqual(collection.models, [one, two, three]);
collection.set([three, two, one, {id: 4}], {add: false});
deepEqual(collection.models, [one, two, three]);
});
test("#1894 - Push should not trigger a sort", 0, function() {
var Collection = Backbone.Collection.extend({
comparator: 'id',
sort: function() { ok(false); }
});
new Collection().push({id: 1});
});
test("#2428 - push duplicate models, return the correct one", 1, function() {
var col = new Backbone.Collection;
var model1 = col.push({id: 101});
var model2 = col.push({id: 101})
ok(model2.cid == model1.cid);
});
test("`set` with non-normal id", function() {
var Collection = Backbone.Collection.extend({
model: Backbone.Model.extend({idAttribute: '_id'})
});
var collection = new Collection({_id: 1});
collection.set([{_id: 1, a: 1}], {add: false});
equal(collection.first().get('a'), 1);
});
test("#1894 - `sort` can optionally be turned off", 0, function() {
var Collection = Backbone.Collection.extend({
comparator: 'id',
sort: function() { ok(false); }
});
new Collection().add({id: 1}, {sort: false});
});
test("#1915 - `parse` data in the right order in `set`", function() {
var collection = new (Backbone.Collection.extend({
parse: function (data) {
strictEqual(data.status, 'ok');
return data.data;
}
}));
var res = {status: 'ok', data:[{id: 1}]};
collection.set(res, {parse: true});
});
asyncTest("#1939 - `parse` is passed `options`", 1, function () {
var collection = new (Backbone.Collection.extend({
url: '/',
parse: function (data, options) {
strictEqual(options.xhr.someHeader, 'headerValue');
return data;
}
}));
var ajax = Backbone.ajax;
Backbone.ajax = function (params) {
_.defer(params.success, []);
return {someHeader: 'headerValue'};
};
collection.fetch({
success: function () { start(); }
});
Backbone.ajax = ajax;
});
test("fetch will pass extra options to success callback", 1, function () {
var SpecialSyncCollection = Backbone.Collection.extend({
url: '/test',
sync: function (method, collection, options) {
_.extend(options, { specialSync: true });
return Backbone.Collection.prototype.sync.call(this, method, collection, options);
}
});
var collection = new SpecialSyncCollection();
var onSuccess = function (collection, resp, options) {
ok(options.specialSync, "Options were passed correctly to callback");
};
collection.fetch({ success: onSuccess });
this.ajaxSettings.success();
});
test("`add` only `sort`s when necessary", 2, function () {
var collection = new (Backbone.Collection.extend({
comparator: 'a'
}))([{id: 1}, {id: 2}, {id: 3}]);
collection.on('sort', function () { ok(true); });
collection.add({id: 4}); // do sort, new model
collection.add({id: 1, a: 1}, {merge: true}); // do sort, comparator change
collection.add({id: 1, b: 1}, {merge: true}); // don't sort, no comparator change
collection.add({id: 1, a: 1}, {merge: true}); // don't sort, no comparator change
collection.add(collection.models); // don't sort, nothing new
collection.add(collection.models, {merge: true}); // don't sort
});
test("`add` only `sort`s when necessary with comparator function", 3, function () {
var collection = new (Backbone.Collection.extend({
comparator: function(a, b) {
return a.get('a') > b.get('a') ? 1 : (a.get('a') < b.get('a') ? -1 : 0);
}
}))([{id: 1}, {id: 2}, {id: 3}]);
collection.on('sort', function () { ok(true); });
collection.add({id: 4}); // do sort, new model
collection.add({id: 1, a: 1}, {merge: true}); // do sort, model change
collection.add({id: 1, b: 1}, {merge: true}); // do sort, model change
collection.add({id: 1, a: 1}, {merge: true}); // don't sort, no model change
collection.add(collection.models); // don't sort, nothing new
collection.add(collection.models, {merge: true}); // don't sort
});
test("Attach options to collection.", 2, function() {
var Model = Backbone.Model;
var comparator = function(){};
var collection = new Backbone.Collection([], {
model: Model,
comparator: comparator
});
ok(collection.model === Model);
ok(collection.comparator === comparator);
});
test("`add` overrides `set` flags", function () {
var collection = new Backbone.Collection();
collection.once('add', function (model, collection, options) {
collection.add({id: 2}, options);
});
collection.set({id: 1});
equal(collection.length, 2);
});
test("#2606 - Collection#create, success arguments", 1, function() {
var collection = new Backbone.Collection;
collection.url = 'test';
collection.create({}, {
success: function(model, resp, options) {
strictEqual(resp, 'response');
}
});
this.ajaxSettings.success('response');
});
test("#2612 - nested `parse` works with `Collection#set`", function() {
var Job = Backbone.Model.extend({
constructor: function() {
this.items = new Items();
Backbone.Model.apply(this, arguments);
},
parse: function(attrs) {
this.items.set(attrs.items, {parse: true});
return _.omit(attrs, 'items');
}
});
var Item = Backbone.Model.extend({
constructor: function() {
this.subItems = new Backbone.Collection();
Backbone.Model.apply(this, arguments);
},
parse: function(attrs) {
this.subItems.set(attrs.subItems, {parse: true});
return _.omit(attrs, 'subItems');
}
});
var Items = Backbone.Collection.extend({
model: Item
});
var data = {
name: 'JobName',
id: 1,
items: [{
id: 1,
name: 'Sub1',
subItems: [
{id: 1, subName: 'One'},
{id: 2, subName: 'Two'}
]
}, {
id: 2,
name: 'Sub2',
subItems: [
{id: 3, subName: 'Three'},
{id: 4, subName: 'Four'}
]
}]
};
var newData = {
name: 'NewJobName',
id: 1,
items: [{
id: 1,
name: 'NewSub1',
subItems: [
{id: 1,subName: 'NewOne'},
{id: 2,subName: 'NewTwo'}
]
}, {
id: 2,
name: 'NewSub2',
subItems: [
{id: 3,subName: 'NewThree'},
{id: 4,subName: 'NewFour'}
]
}]
};
var job = new Job(data, {parse: true});
equal(job.get('name'), 'JobName');
equal(job.items.at(0).get('name'), 'Sub1');
equal(job.items.length, 2);
equal(job.items.get(1).subItems.get(1).get('subName'), 'One');
equal(job.items.get(2).subItems.get(3).get('subName'), 'Three');
job.set(job.parse(newData, {parse: true}));
equal(job.get('name'), 'NewJobName');
equal(job.items.at(0).get('name'), 'NewSub1');
equal(job.items.length, 2);
equal(job.items.get(1).subItems.get(1).get('subName'), 'NewOne');
equal(job.items.get(2).subItems.get(3).get('subName'), 'NewThree');
});
test('_addReference binds all collection events & adds to the lookup hashes', 9, function() {
var calls = {add: 0, remove: 0};
var Collection = Backbone.Collection.extend({
_addReference: function(model) {
Backbone.Collection.prototype._addReference.apply(this, arguments);
calls.add++;
equal(model, this._byId[model.id]);
equal(model, this._byId[model.cid]);
equal(model._events.all.length, 1);
},
_removeReference: function(model) {
Backbone.Collection.prototype._removeReference.apply(this, arguments);
calls.remove++;
equal(this._byId[model.id], void 0);
equal(this._byId[model.cid], void 0);
equal(model.collection, void 0);
equal(model._events, void 0);
}
});
var collection = new Collection();
var model = collection.add({id: 1});
collection.remove(model);
equal(calls.add, 1);
equal(calls.remove, 1);
});
test('Do not allow duplicate models to be `add`ed or `set`', function() {
var c = new Backbone.Collection();
c.add([{id: 1}, {id: 1}]);
equal(c.length, 1);
equal(c.models.length, 1);
c.set([{id: 1}, {id: 1}]);
equal(c.length, 1);
equal(c.models.length, 1);
});
test('#3020: #set with {add: false} should not throw.', 2, function() {
var collection = new Backbone.Collection;
collection.set([{id: 1}], {add: false});
strictEqual(collection.length, 0);
strictEqual(collection.models.length, 0);
});
test("create with wait, model instance, #3028", 1, function() {
var collection = new Backbone.Collection();
var model = new Backbone.Model({id: 1});
model.sync = function(){
equal(this.collection, collection);
};
collection.create(model, {wait: true});
});
test("modelId", function() {
var Stooge = Backbone.Model.extend();
var StoogeCollection = Backbone.Collection.extend({model: Stooge});
// Default to using `Collection::model::idAttribute`.
equal(StoogeCollection.prototype.modelId({id: 1}), 1);
Stooge.prototype.idAttribute = '_id';
equal(StoogeCollection.prototype.modelId({_id: 1}), 1);
});
test('Polymorphic models work with "simple" constructors', function () {
var A = Backbone.Model.extend();
var B = Backbone.Model.extend();
var C = Backbone.Collection.extend({
model: function (attrs) {
return attrs.type === 'a' ? new A(attrs) : new B(attrs);
}
});
var collection = new C([{id: 1, type: 'a'}, {id: 2, type: 'b'}]);
equal(collection.length, 2);
ok(collection.at(0) instanceof A);
equal(collection.at(0).id, 1);
ok(collection.at(1) instanceof B);
equal(collection.at(1).id, 2);
});
test('Polymorphic models work with "advanced" constructors', function () {
var A = Backbone.Model.extend({idAttribute: '_id'});
var B = Backbone.Model.extend({idAttribute: '_id'});
var C = Backbone.Collection.extend({
model: Backbone.Model.extend({
constructor: function (attrs) {
return attrs.type === 'a' ? new A(attrs) : new B(attrs);
},
idAttribute: '_id'
})
});
var collection = new C([{_id: 1, type: 'a'}, {_id: 2, type: 'b'}]);
equal(collection.length, 2);
ok(collection.at(0) instanceof A);
equal(collection.at(0), collection.get(1));
ok(collection.at(1) instanceof B);
equal(collection.at(1), collection.get(2));
C = Backbone.Collection.extend({
model: function (attrs) {
return attrs.type === 'a' ? new A(attrs) : new B(attrs);
},
modelId: function (attrs) {
return attrs.type + '-' + attrs.id;
}
});
collection = new C([{id: 1, type: 'a'}, {id: 1, type: 'b'}]);
equal(collection.length, 2);
ok(collection.at(0) instanceof A);
equal(collection.at(0), collection.get('a-1'));
ok(collection.at(1) instanceof B);
equal(collection.at(1), collection.get('b-1'));
});
test("#3039: adding at index fires with correct at", 3, function() {
var col = new Backbone.Collection([{at: 0}, {at: 4}]);
col.on('add', function(model, col, options) {
equal(model.get('at'), options.index);
});
col.add([{at: 1}, {at: 2}, {at: 3}], {at: 1});
});
test("#3039: index is not sent when at is not specified", 2, function() {
var col = new Backbone.Collection([{at: 0}]);
col.on('add', function(model, col, options) {
equal(undefined, options.index);
});
col.add([{at: 1}, {at: 2}]);
});
test('#3199 - Order changing should trigger a sort', 1, function() {
var one = new Backbone.Model({id: 1});
var two = new Backbone.Model({id: 2});
var three = new Backbone.Model({id: 3});
var collection = new Backbone.Collection([one, two, three]);
collection.on('sort', function() {
ok(true);
});
collection.set([{id: 3}, {id: 2}, {id: 1}]);
});
test('#3199 - Adding a model should trigger a sort', 1, function() {
var one = new Backbone.Model({id: 1});
var two = new Backbone.Model({id: 2});
var three = new Backbone.Model({id: 3});
var collection = new Backbone.Collection([one, two, three]);
collection.on('sort', function() {
ok(true);
});
collection.set([{id: 1}, {id: 2}, {id: 3}, {id: 0}]);
})
test('#3199 - Order not changing should not trigger a sort', 0, function() {
var one = new Backbone.Model({id: 1});
var two = new Backbone.Model({id: 2});
var three = new Backbone.Model({id: 3});
var collection = new Backbone.Collection([one, two, three]);
collection.on('sort', function() {
ok(false);
});
collection.set([{id: 1}, {id: 2}, {id: 3}]);
});
test("add supports negative indexes", 1, function() {
var collection = new Backbone.Collection([{id: 1}]);
collection.add([{id: 2}, {id: 3}], {at: -1});
collection.add([{id: 2.5}], {at: -2});
collection.add([{id: 0.5}], {at: -6});
equal(collection.pluck('id').join(','), "0.5,1,2,2.5,3");
});
test("#set accepts options.at as a string", 1, function() {
var collection = new Backbone.Collection([{id: 1}, {id: 2}]);
collection.add([{id: 3}], {at: '1'});
deepEqual(collection.pluck('id'), [1, 3, 2]);
});
test("adding multiple models triggers `update` event once", 1, function() {
var collection = new Backbone.Collection;
collection.on('update', function() { ok(true); });
collection.add([{id: 1}, {id: 2}, {id: 3}]);
});
test("removing models triggers `update` event once", 1, function() {
var collection = new Backbone.Collection([{id: 1}, {id: 2}, {id: 3}]);
collection.on('update', function() { ok(true); });
collection.remove([{id: 1}, {id: 2}]);
});
test("remove does not trigger `set` when nothing removed", 0, function() {
var collection = new Backbone.Collection([{id: 1}, {id: 2}]);
collection.on('update', function() { ok(false); });
collection.remove([{id: 3}]);
});
test("set triggers `set` event once", 1, function() {
var collection = new Backbone.Collection([{id: 1}, {id: 2}]);
collection.on('update', function() { ok(true); });
collection.set([{id: 1}, {id: 3}]);
});
test("set does not trigger `update` event when nothing added nor removed", 0, function() {
var collection = new Backbone.Collection([{id: 1}, {id: 2}]);
collection.on('update', function() { ok(false); });
collection.set([{id: 1}, {id: 2}]);
});
test("#3610 - invoke collects arguments", 3, function() {
var Model = Backbone.Model.extend({
method: function(a, b, c) {
equal(a, 1);
equal(b, 2);
equal(c, 3);
}
});
var Collection = Backbone.Collection.extend({
model: Model
});
var collection = new Collection([{id: 1}]);
collection.invoke('method', 1, 2, 3);
});
})();
|
/*
Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'div', 'cs', {
IdInputLabel: 'Id',
advisoryTitleInputLabel: 'Nápovědní titulek',
cssClassInputLabel: 'Třídy stylů',
edit: 'Změnit Div',
inlineStyleInputLabel: 'Vnitřní styly',
langDirLTRLabel: 'Zleva doprava (LTR)',
langDirLabel: 'Směr jazyka',
langDirRTLLabel: 'Zprava doleva (RTL)',
languageCodeInputLabel: ' Kód jazyka',
remove: 'Odstranit Div',
styleSelectLabel: 'Styly',
title: 'Vytvořit Div kontejner',
toolbar: 'Vytvořit Div kontejner'
} );
|
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
UI.Fragment = class {
/**
* @param {!Element} element
*/
constructor(element) {
this._element = element;
/** @type {!Map<string, !Element>} */
this._elementsById = new Map();
}
/**
* @return {!Element}
*/
element() {
return this._element;
}
/**
* @param {string} elementId
* @return {!Element}
*/
$(elementId) {
return this._elementsById.get(elementId);
}
/**
* @param {!Array<string>} strings
* @param {...*} values
* @return {!UI.Fragment}
*/
static build(strings, ...values) {
return UI.Fragment._render(UI.Fragment._template(strings), values);
}
/**
* @param {!Array<string>} strings
* @param {...*} values
* @return {!UI.Fragment}
*/
static cached(strings, ...values) {
let template = UI.Fragment._templateCache.get(strings);
if (!template) {
template = UI.Fragment._template(strings);
UI.Fragment._templateCache.set(strings, template);
}
return UI.Fragment._render(template, values);
}
/**
* @param {!Array<string>} strings
* @return {!UI.Fragment._Template}
* @suppressGlobalPropertiesCheck
*/
static _template(strings) {
let html = '';
let insideText = true;
for (let i = 0; i < strings.length - 1; i++) {
html += strings[i];
const close = strings[i].lastIndexOf('>');
const open = strings[i].indexOf('<', close + 1);
if (close !== -1 && open === -1)
insideText = true;
else if (open !== -1)
insideText = false;
html += insideText ? UI.Fragment._textMarker : UI.Fragment._attributeMarker(i);
}
html += strings[strings.length - 1];
const template = window.document.createElement('template');
template.innerHTML = html;
const walker = template.ownerDocument.createTreeWalker(
template.content, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT, null, false);
let valueIndex = 0;
const emptyTextNodes = [];
const binds = [];
const nodesToMark = [];
while (walker.nextNode()) {
const node = walker.currentNode;
if (node.nodeType === Node.ELEMENT_NODE && node.hasAttributes()) {
if (node.hasAttribute('$')) {
nodesToMark.push(node);
binds.push({elementId: node.getAttribute('$')});
node.removeAttribute('$');
}
const attributesToRemove = [];
for (let i = 0; i < node.attributes.length; i++) {
const name = node.attributes[i].name;
if (!UI.Fragment._attributeMarkerRegex.test(name) &&
!UI.Fragment._attributeMarkerRegex.test(node.attributes[i].value))
continue;
attributesToRemove.push(name);
nodesToMark.push(node);
const bind = {attr: {index: valueIndex}};
bind.attr.names = name.split(UI.Fragment._attributeMarkerRegex);
valueIndex += bind.attr.names.length - 1;
bind.attr.values = node.attributes[i].value.split(UI.Fragment._attributeMarkerRegex);
valueIndex += bind.attr.values.length - 1;
binds.push(bind);
}
for (let i = 0; i < attributesToRemove.length; i++)
node.removeAttribute(attributesToRemove[i]);
}
if (node.nodeType === Node.TEXT_NODE && node.data.indexOf(UI.Fragment._textMarker) !== -1) {
const texts = node.data.split(UI.Fragment._textMarkerRegex);
node.data = texts[texts.length - 1];
for (let i = 0; i < texts.length - 1; i++) {
if (texts[i])
node.parentNode.insertBefore(createTextNode(texts[i]), node);
const nodeToReplace = createElement('span');
nodesToMark.push(nodeToReplace);
binds.push({replaceNodeIndex: valueIndex++});
node.parentNode.insertBefore(nodeToReplace, node);
}
}
if (node.nodeType === Node.TEXT_NODE &&
(!node.previousSibling || node.previousSibling.nodeType === Node.ELEMENT_NODE) &&
(!node.nextSibling || node.nextSibling.nodeType === Node.ELEMENT_NODE) && /^\s*$/.test(node.data))
emptyTextNodes.push(node);
}
for (let i = 0; i < nodesToMark.length; i++)
nodesToMark[i].classList.add(UI.Fragment._class(i));
for (const emptyTextNode of emptyTextNodes)
emptyTextNode.remove();
return {template: template, binds: binds};
}
/**
* @param {!UI.Fragment._Template} template
* @param {!Array<*>} values
* @return {!UI.Fragment}
*/
static _render(template, values) {
const content = template.template.ownerDocument.importNode(template.template.content, true);
const resultElement =
/** @type {!Element} */ (content.firstChild === content.lastChild ? content.firstChild : content);
const result = new UI.Fragment(resultElement);
const boundElements = [];
for (let i = 0; i < template.binds.length; i++) {
const className = UI.Fragment._class(i);
const element = /** @type {!Element} */ (content.querySelector('.' + className));
element.classList.remove(className);
boundElements.push(element);
}
for (let bindIndex = 0; bindIndex < template.binds.length; bindIndex++) {
const bind = template.binds[bindIndex];
const element = boundElements[bindIndex];
if ('elementId' in bind) {
result._elementsById.set(/** @type {string} */ (bind.elementId), element);
} else if ('replaceNodeIndex' in bind) {
const value = values[/** @type {number} */ (bind.replaceNodeIndex)];
element.parentNode.replaceChild(this._nodeForValue(value), element);
} else if ('attr' in bind) {
if (bind.attr.names.length === 2 && bind.attr.values.length === 1 &&
typeof values[bind.attr.index] === 'function') {
values[bind.attr.index].call(null, element);
} else {
let name = bind.attr.names[0];
for (let i = 1; i < bind.attr.names.length; i++) {
name += values[bind.attr.index + i - 1];
name += bind.attr.names[i];
}
if (name) {
let value = bind.attr.values[0];
for (let i = 1; i < bind.attr.values.length; i++) {
value += values[bind.attr.index + bind.attr.names.length - 1 + i - 1];
value += bind.attr.values[i];
}
element.setAttribute(name, value);
}
}
} else {
throw new Error('Unexpected bind');
}
}
return result;
}
/**
* @param {*} value
* @return {!Node}
*/
static _nodeForValue(value) {
if (value instanceof Node)
return value;
if (value instanceof UI.Fragment)
return value._element;
if (Array.isArray(value)) {
const node = createDocumentFragment();
for (const v of value)
node.appendChild(this._nodeForValue(v));
return node;
}
return createTextNode('' + value);
}
};
/**
* @typedef {!{
* template: !Element,
* binds: !Array<!UI.Fragment._Bind>
* }}
*/
UI.Fragment._Template;
/**
* @typedef {!{
* elementId: (string|undefined),
*
* attr: (!{
* index: number,
* names: !Array<string>,
* values: !Array<string>
* }|undefined),
*
* replaceNodeIndex: (number|undefined)
* }}
*/
UI.Fragment._Bind;
UI.Fragment._textMarker = '{{template-text}}';
UI.Fragment._textMarkerRegex = /{{template-text}}/;
UI.Fragment._attributeMarker = index => 'template-attribute' + index;
UI.Fragment._attributeMarkerRegex = /template-attribute\d+/;
UI.Fragment._class = index => 'template-class-' + index;
UI.Fragment._templateCache = new Map();
/**
* @param {!Array<string>} strings
* @param {...*} vararg
* @return {!Element}
*/
UI.html = (strings, ...vararg) => {
return UI.Fragment.cached(strings, ...vararg).element();
};
|
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'use strict';
/**
* Additional parameters for resize operation.
*
*/
class PoolResizeOptions {
/**
* Create a PoolResizeOptions.
* @member {number} [timeout] The maximum time that the server can spend
* processing the request, in seconds. The default is 30 seconds. Default
* value: 30 .
* @member {uuid} [clientRequestId] The caller-generated request identity, in
* the form of a GUID with no decoration such as curly braces, e.g.
* 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0.
* @member {boolean} [returnClientRequestId] Whether the server should return
* the client-request-id in the response. Default value: false .
* @member {date} [ocpDate] The time the request was issued. Client libraries
* typically set this to the current system clock time; set it explicitly if
* you are calling the REST API directly.
* @member {string} [ifMatch] An ETag value associated with the version of
* the resource known to the client. The operation will be performed only if
* the resource's current ETag on the service exactly matches the value
* specified by the client.
* @member {string} [ifNoneMatch] An ETag value associated with the version
* of the resource known to the client. The operation will be performed only
* if the resource's current ETag on the service does not match the value
* specified by the client.
* @member {date} [ifModifiedSince] A timestamp indicating the last modified
* time of the resource known to the client. The operation will be performed
* only if the resource on the service has been modified since the specified
* time.
* @member {date} [ifUnmodifiedSince] A timestamp indicating the last
* modified time of the resource known to the client. The operation will be
* performed only if the resource on the service has not been modified since
* the specified time.
*/
constructor() {
}
/**
* Defines the metadata of PoolResizeOptions
*
* @returns {object} metadata of PoolResizeOptions
*
*/
mapper() {
return {
required: false,
type: {
name: 'Composite',
className: 'PoolResizeOptions',
modelProperties: {
timeout: {
required: false,
defaultValue: 30,
type: {
name: 'Number'
}
},
clientRequestId: {
required: false,
type: {
name: 'String'
}
},
returnClientRequestId: {
required: false,
defaultValue: false,
type: {
name: 'Boolean'
}
},
ocpDate: {
required: false,
type: {
name: 'DateTimeRfc1123'
}
},
ifMatch: {
required: false,
type: {
name: 'String'
}
},
ifNoneMatch: {
required: false,
type: {
name: 'String'
}
},
ifModifiedSince: {
required: false,
type: {
name: 'DateTimeRfc1123'
}
},
ifUnmodifiedSince: {
required: false,
type: {
name: 'DateTimeRfc1123'
}
}
}
}
};
}
}
module.exports = PoolResizeOptions;
|
var fs = require('fs');
var tasks = fs.readdirSync('./gulp/');
tasks.forEach(function(task) {
if(task.slice(-3) != '.js') return;
require('./gulp/' + task);
});
|
/**
* @fileoverview Tests for block-scoped-var rule
* @author Matt DuVall <http://www.mattduvall.com>
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
var eslint = require("../../../lib/eslint"),
ESLintTester = require("eslint-tester");
//------------------------------------------------------------------------------
// Tests
//------------------------------------------------------------------------------
var eslintTester = new ESLintTester(eslint);
eslintTester.addRuleTest("lib/rules/block-scoped-var", {
valid: [
"function f() { var a, b; { a = true; } b = a; }",
"var a; function f() { var b = a; }",
"function f(a) { }",
"!function(a) { };",
"!function f(a) { };",
"function f(a) { var b = a; }",
"!function f(a) { var b = a; };",
"function f() { var g = f; }",
"function f() { } function g() { var f = g; }",
"function f() { var hasOwnProperty; { hasOwnProperty; } }",
"function f(){ a; b; var a, b; }",
"function f(){ g(); function g(){} }",
{ code: "function myFunc(foo) { \"use strict\"; var { bar } = foo; bar.hello();}", ecmaFeatures: { destructuring: true } },
{ code: "function myFunc(foo) { \"use strict\"; var [ bar ] = foo; bar.hello();}", ecmaFeatures: { destructuring: true } },
{ code: "function myFunc(...foo) { return foo;}", ecmaFeatures: { restParams: true } },
{ code: "var f = () => { var g = f; }", ecmaFeatures: { arrowFunctions: true } },
{ code: "new Date", globals: {Date: false} },
{ code: "new Date", globals: {} },
{ code: "var eslint = require('eslint');", globals: {require: false} },
{ code: "var fun = function({x}) {return x;};", ecmaFeatures: { destructuring: true } },
{ code: "var fun = function([,x]) {return x;};", ecmaFeatures: { destructuring: true } },
"function f(a) { return a.b; }",
"var a = { \"foo\": 3 };",
"var a = { foo: 3 };",
"var a = { foo: 3, bar: 5 };",
"var a = { set foo(a){}, get bar(){} };",
"function f(a) { return arguments[0]; }",
"function f() { }; var a = f;",
"var a = f; function f() { };",
"function f(){ for(var i; i; i) i; }",
"function f(){ for(var a=0, b=1; a; b) a, b; }",
"function f(){ for(var a in {}) a; }",
"function f(){ switch(2) { case 1: var b = 2; b; break; default: b; break;} b; }",
"a:;",
{ code: "const React = require(\"react/addons\");const cx = React.addons.classSet;", globals: { require: false }, ecmaFeatures: { globalReturn: true, modules: true, blockBindings: true }},
{ code: "var v = 1; function x() { return v; };", ecmaFeatures: { globalReturn: true }},
{ code: "import * as y from \"./other.js\"; y();", ecmaFeatures: { modules: true }},
{ code: "import y from \"./other.js\"; y();", ecmaFeatures: { modules: true }},
{ code: "import {x as y} from \"./other.js\"; y();", ecmaFeatures: { modules: true }},
{ code: "class Test { myFunction() { return true; }}", ecmaFeatures: { classes: true }},
{ code: "class Test { get flag() { return true; }}", ecmaFeatures: { classes: true }},
{ code: "var Test = class { myFunction() { return true; }}", ecmaFeatures: { classes: true }},
{ code: "var doStuff; let {x: y} = {x: 1}; doStuff(y);", ecmaFeatures: { blockBindings: true, destructuring: true }},
{ code: "function foo({x: y}) { return y; }", ecmaFeatures: { blockBindings: true, destructuring: true }}
],
invalid: [
{ code: "var f = () => { x; }", ecmaFeatures: { arrowFunctions: true }, errors: [{ message: "\"x\" used outside of binding context.", type: "Identifier" }] },
{ code: "function f(){ x; }", errors: [{ message: "\"x\" used outside of binding context.", type: "Identifier" }] },
{ code: "function f(){ x; { var x; } }", errors: [{ message: "\"x\" used outside of binding context.", type: "Identifier" }] },
{ code: "function f(){ { var x; } x; }", errors: [{ message: "\"x\" used outside of binding context.", type: "Identifier" }] },
{ code: "function f() { var a; { var b = 0; } a = b; }", errors: [{ message: "\"b\" used outside of binding context.", type: "Identifier" }] },
{ code: "function f() { try { var a = 0; } catch (e) { var b = a; } }", errors: [{ message: "\"a\" used outside of binding context.", type: "Identifier" }] },
{ code: "var eslint = require('eslint');", globals: {}, errors: [{ message: "\"require\" used outside of binding context.", type: "Identifier" }] },
{ code: "function f(a) { return a[b]; }", errors: [{ message: "\"b\" used outside of binding context.", type: "Identifier" }] },
{ code: "function f() { return b.a; }", errors: [{ message: "\"b\" used outside of binding context.", type: "Identifier" }] },
{ code: "var a = { foo: bar };", errors: [{ message: "\"bar\" used outside of binding context.", type: "Identifier" }] },
{ code: "var a = { foo: foo };", errors: [{ message: "\"foo\" used outside of binding context.", type: "Identifier" }] },
{ code: "var a = { bar: 7, foo: bar };", errors: [{ message: "\"bar\" used outside of binding context.", type: "Identifier" }] },
{ code: "var a = arguments;", errors: [{ message: "\"arguments\" used outside of binding context.", type: "Identifier" }] },
{ code: "function x(){}; var a = arguments;", errors: [{ message: "\"arguments\" used outside of binding context.", type: "Identifier" }] },
{ code: "function z(b){}; var a = b;", errors: [{ message: "\"b\" used outside of binding context.", type: "Identifier" }] },
{ code: "function z(){var b;}; var a = b;", errors: [{ message: "\"b\" used outside of binding context.", type: "Identifier" }] },
{ code: "function f(){ try{}catch(e){} e }", errors: [{ message: "\"e\" used outside of binding context.", type: "Identifier" }] },
{ code: "a:b;", errors: [{ message: "\"b\" used outside of binding context.", type: "Identifier" }] },
{
code: "function a() { for(var b in {}) { var c = b; } c; }",
errors: [{ message: "\"c\" used outside of binding context.", type: "Identifier" }]
},
{
code: "function a() { for(var b of {}) { var c = b;} c; }",
ecmaFeatures: { forOf: true },
errors: [{ message: "\"c\" used outside of binding context.", type: "Identifier" }]
}
]
});
|
/*!
* jQuery.scrollFix.js
* @ desc: 滚动固定在某个位置的jQuery插件
* @ version: v2.0.2
* @ link: https://github.com/mengqing723/jQuery-scrollFix.git
* @ date: 2016/10/26
*/
;(function (factory) {
if (typeof define === 'function' && define.amd) {
define(['jquery'], factory);
} else if (typeof exports === 'object' && exports) {
module.exports = factory;
} else {
factory(jQuery);
}
}(function ($) {
$.fn.scrollFix = function(options) {
return this.each(function() {
var defaults = {
top: 0, // 浮动对象 到顶部的高度
bottom: 0, // 浮动对象 到停靠对象(startObj)的间距
zindex: 999, // 浮动对象 的z-index索引值
startObj: null, // 滑到 startObj 位置时开始浮动固定,默认为浮动对象
position: 'top', // 滑到 startObj 顶端|底端 开始浮动固定 ('top'|'bottom')
endObj: null, // 滑到 endObj 顶部时取消固定并继续跟随滚动
endPos: 0, // 浮动对象 到停止对象(endObj)的间距
fixClass: 'fixed', // 浮动固定后添加 class 样式
fixFn: function() {}, // 浮动固定后回调
fixEndFn: function() {}, // 浮动固定结束后回调
endFn: function() {} // 浮动结束后回调
}
var opts = $.extend({}, defaults, options);
var $this = $(this), // 当前对象
$startObj = opts.startObj === null ? $this : $(opts.startObj), // 滚动到 startObj 开始浮动固定
isEnd = opts.endObj === null ? false : true; // 是否结束浮动固定
var objStyle = $this.attr('style') ? $this.attr('style') : '', // 默认样式
objWidth = $this.width(); // 默认宽度
var startHeight = (opts.position === 'top') ? 0 : $startObj.outerHeight(); // (顶部|底部) 开始浮动
var startFix = $startObj.offset().top + startHeight - opts.bottom; // 滚动距离为 startFix 开始固定浮动
var endFix = isEnd ? parseInt($(opts.endObj).offset().top - opts.top - opts.endPos - $this.outerHeight()) : 0; // 滚动距离为 endFix 结束固定浮动
var endFixTop = endFix + opts.top; // 变为跟随滚动后(fixed -> absolute)到顶部的距离
var methods = {
fixed: function(top) {
$this.css({position: 'fixed', top: top + 'px', zIndex: opts.zindex, width: '100%'})
.addClass(opts.fixClass);
opts.fixFn();
},
absolute: function(top) {
$this.css({position: 'absolute', top: top + 'px', zIndex: opts.zindex, width: '100%'});
opts.fixEndFn();
},
default: function() {
$this.attr('style', objStyle)
.removeClass(opts.fixClass);
opts.endFn();
}
}
$(window).scroll(function(event) {
var scrollTop = $(this).scrollTop();
if(scrollTop > startFix) {
if(isEnd) {
if(scrollTop > endFix) {
methods.absolute(endFixTop);
} else {
methods.fixed(opts.top);
}
} else {
methods.fixed(opts.top);
}
} else {
methods.default();
}
}).trigger('scroll');
});
}
}));
|
import moment from 'moment';
function durationHelper(params, hash) {
if (params.length > 2) {
throw new TypeError('ember-moment: Invalid Number of arguments, at most 2');
}
let time = moment.duration(...params);
if (hash.locale) {
time = time.locale(hash.locale);
}
return time.humanize();
}
export default durationHelper;
|
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2013 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* Create a new `Tile` object. Tiles live inside of Tilesets and are rendered via TilemapLayers.
*
* @class Phaser.Tile
* @classdesc A Tile is a single representation of a tile within a Tilemap.
* @constructor
* @param {Phaser.Tileset} tileset - The tileset this tile belongs to.
* @param {number} index - The index of this tile type in the core map data.
* @param {number} x - The x coordinate of this tile.
* @param {number} y - The y coordinate of this tile.
* @param {number} width - Width of the tile.
* @param {number} height - Height of the tile.
*/
Phaser.Tile = function (tileset, index, x, y, width, height) {
/**
* @property {Phaser.Tileset} tileset - The tileset this tile belongs to.
*/
this.tileset = tileset;
/**
* @property {number} index - The index of this tile within the tileset.
*/
this.index = index;
/**
* @property {number} width - The width of the tile in pixels.
*/
this.width = width;
/**
* @property {number} height - The height of the tile in pixels.
*/
this.height = height;
/**
* @property {number} x - The top-left corner of the tile within the tileset.
*/
this.x = x;
/**
* @property {number} y - The top-left corner of the tile within the tileset.
*/
this.y = y;
// Any extra meta data info we need here
/**
* @property {number} mass - The virtual mass of the tile.
* @default
*/
this.mass = 1.0;
/**
* @property {boolean} collideNone - Indicating this Tile doesn't collide at all.
* @default
*/
this.collideNone = true;
/**
* @property {boolean} collideLeft - Indicating collide with any object on the left.
* @default
*/
this.collideLeft = false;
/**
* @property {boolean} collideRight - Indicating collide with any object on the right.
* @default
*/
this.collideRight = false;
/**
* @property {boolean} collideUp - Indicating collide with any object on the top.
* @default
*/
this.collideUp = false;
/**
* @property {boolean} collideDown - Indicating collide with any object on the bottom.
* @default
*/
this.collideDown = false;
/**
* @property {boolean} separateX - Enable separation at x-axis.
* @default
*/
this.separateX = true;
/**
* @property {boolean} separateY - Enable separation at y-axis.
* @default
*/
this.separateY = true;
/**
* @property {boolean} collisionCallback - Tilemap collision callback.
* @default
*/
this.collisionCallback = null;
/**
* @property {boolean} collisionCallback - Tilemap collision callback.
* @default
*/
this.collisionCallbackContext = this;
};
Phaser.Tile.prototype = {
/**
* Set callback to be called when this tilemap collides.
*
* @method Phaser.Tile#setCollisionCallback
* @param {Function} callback - Callback function.
* @param {object} context - Callback will be called with this context.
*/
setCollisionCallback: function (callback, context) {
this.collisionCallbackContext = context;
this.collisionCallback = callback;
},
/**
* Clean up memory.
* @method Phaser.Tile#destroy
*/
destroy: function () {
this.tileset = null;
},
/**
* Set collision settings on this tile.
* @method Phaser.Tile#setCollision
* @param {boolean} left - Indicating collide with any object on the left.
* @param {boolean} right - Indicating collide with any object on the right.
* @param {boolean} up - Indicating collide with any object on the top.
* @param {boolean} down - Indicating collide with any object on the bottom.
*/
setCollision: function (left, right, up, down) {
this.collideLeft = left;
this.collideRight = right;
this.collideUp = up;
this.collideDown = down;
if (left || right || up || down)
{
this.collideNone = false;
}
else
{
this.collideNone = true;
}
},
/**
* Reset collision status flags.
* @method Phaser.Tile#resetCollision
*/
resetCollision: function () {
this.collideNone = true;
this.collideLeft = false;
this.collideRight = false;
this.collideUp = false;
this.collideDown = false;
}
};
/**
* @name Phaser.Tile#bottom
* @property {number} bottom - The sum of the y and height properties.
* @readonly
*/
Object.defineProperty(Phaser.Tile.prototype, "bottom", {
get: function () {
return this.y + this.height;
}
});
/**
* @name Phaser.Tile#right
* @property {number} right - The sum of the x and width properties.
* @readonly
*/
Object.defineProperty(Phaser.Tile.prototype, "right", {
get: function () {
return this.x + this.width;
}
});
|
// @flow
import express from "express";
import getProcessForPort from "react-dev-utils/getProcessForPort";
import chalk from "chalk";
import createDB from "../db";
import createAPIServer from "../api";
import log from "../utils/log";
const debug = require("debug")("phenomic:core:commands:start");
async function createDevServer({ config }: { config: PhenomicConfig }) {
debug("creating dev server");
const devServer = express();
await Promise.all(
config.plugins.map(async plugin => {
if (plugin.addDevServerMiddlewares)
debug("adding dev server middlewares for " + plugin.name);
if (plugin.addDevServerMiddlewares) {
return (await plugin.addDevServerMiddlewares()).map(async m => {
const resolved = await m;
if (resolved) devServer.use(resolved);
else
debug(
"A middleware hasn't returned anything for " + plugin.name,
", skipping",
m,
);
});
}
}),
);
return devServer;
}
async function start(config: PhenomicConfig) {
log("️⚡️ Starting development server...");
process.env.NODE_ENV = process.env.NODE_ENV || "development";
process.env.BABEL_ENV = process.env.BABEL_ENV || "development";
process.env.PHENOMIC_ENV = "development";
process.env.PHENOMIC_RESTAPI_PORT = String(config.port);
process.env.PHENOMIC_SOCKET_PORT = String(config.socketPort);
debug("starting phenomic server");
const db = createDB(config.db);
const renderers = config.plugins.filter(p => p.getRoutes);
const renderer: PhenomicPlugin = renderers[0];
const transformers = config.plugins.filter(plugin => plugin.transform);
// collectors
await Promise.all(
config.plugins.map(p => p.collect && p.collect({ db, transformers })),
);
const phenomicServer = createAPIServer({
db,
plugins: config.plugins,
rootPath: config.baseUrl.pathname + "phenomic",
});
const bundlerServer = await createDevServer({ config });
bundlerServer.use(phenomicServer);
// $FlowFixMe flow is lost with async function for express
bundlerServer.get("*", function(req, res) {
res.type(".html");
if (typeof renderer.renderDevServer !== "function") {
res.end(
"Phenomic renderer requires a 'renderDevServer' function to be exposed",
);
} else {
res.end(
renderer.renderDevServer({
assets: res.locals.assets,
location: req.originalUrl,
}),
);
}
});
const server = bundlerServer.listen(config.port);
if (server) {
server.on("error", err => {
if (err.errno === "EADDRINUSE") {
const existingProcess = getProcessForPort(err.port);
log(
chalk.yellow(
`Something is already running on port ${err.port}. ${
existingProcess ? `Probably:\n${existingProcess}\n` : ""
}`,
),
);
} else {
log(err);
}
process.exit(1);
});
}
log.success(
`🔗 Development server ready on http://localhost:${config.port}` +
config.baseUrl.pathname,
);
}
export default start;
|
var should = require('should'),
// Stuff we are testing
helpers = require('../../../server/helpers');
describe('{{twitter_url}} helper', function () {
var options = {data: {blog: {}}};
beforeEach(function () {
options.data.blog = {twitter: ''};
});
it('should output the twitter url for @blog, if no other twitter username is provided', function () {
options.data.blog = {twitter: '@hey'};
helpers.twitter_url.call({}, options).should.equal('https://twitter.com/hey');
});
it('should output the twitter url for the local object, if it has one', function () {
options.data.blog = {twitter: '@hey'};
helpers.twitter_url.call({twitter: '@youthere'}, options).should.equal('https://twitter.com/youthere');
});
it('should output the twitter url for the provided username when it is explicitly passed in', function () {
options.data.blog = {twitter: '@hey'};
helpers.twitter_url.call({twitter: '@youthere'}, '@iseeyouoverthere', options)
.should.equal('https://twitter.com/iseeyouoverthere');
});
it('should return null if there are no twitter usernames', function () {
should.equal(helpers.twitter_url(options), null);
});
});
|
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.hola_jwplayer_hls = f()}})(function(){var define,module,exports;return (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){
var Hls = window.Hls = require('@hola.org/hls.js').default;
var provider = module.exports = require('@hola.org/jwplayer-hlsjs');
provider.Hls = Hls;
provider.version = '1.0.31';
provider.hls_version = provider.Hls.version;
provider.provider_version = provider.VERSION;
},{"@hola.org/hls.js":26,"@hola.org/jwplayer-hlsjs":42}],2:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
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 _events = require('../events');
var _events2 = _interopRequireDefault(_events);
var _eventHandler = require('../event-handler');
var _eventHandler2 = _interopRequireDefault(_eventHandler);
var _bufferHelper = require('../helper/buffer-helper');
var _bufferHelper2 = _interopRequireDefault(_bufferHelper);
var _errors = require('../errors');
var _logger = require('../utils/logger');
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; } /*
* simple ABR Controller
* - compute next level based on last fragment bw heuristics
* - implement an abandon rules triggered if we have less than 2 frag buffered and if computed bw shows that we risk buffer stalling
*/
var AbrController = function (_EventHandler) {
_inherits(AbrController, _EventHandler);
function AbrController(hls) {
_classCallCheck(this, AbrController);
var _this = _possibleConstructorReturn(this, (AbrController.__proto__ || Object.getPrototypeOf(AbrController)).call(this, hls, _events2.default.FRAG_LOADING, _events2.default.FRAG_LOAD_PROGRESS, _events2.default.FRAG_LOADED, _events2.default.ERROR));
_this.lastLoadedFragLevel = 0;
_this._autoLevelCapping = -1;
_this._nextAutoLevel = -1;
_this.hls = hls;
_this.onCheck = _this.abandonRulesCheck.bind(_this);
return _this;
}
_createClass(AbrController, [{
key: 'destroy',
value: function destroy() {
this.clearTimer();
_eventHandler2.default.prototype.destroy.call(this);
}
}, {
key: 'onFragLoading',
value: function onFragLoading(data) {
if (!this.timer) {
this.timer = setInterval(this.onCheck, 100);
}
this.fragCurrent = data.frag;
}
}, {
key: 'onFragLoadProgress',
value: function onFragLoadProgress(data) {
var stats = data.stats;
// only update stats if first frag loading
// if same frag is loaded multiple times, it might be in browser cache, and loaded quickly
// and leading to wrong bw estimation
if (stats.aborted === undefined && data.frag.loadCounter === 1) {
this.lastfetchduration = (performance.now() - stats.trequest) / 1000;
this.lastbw = stats.loaded * 8 / this.lastfetchduration;
//console.log(`fetchDuration:${this.lastfetchduration},bw:${(this.lastbw/1000).toFixed(0)}/${stats.aborted}`);
}
}
}, {
key: 'abandonRulesCheck',
value: function abandonRulesCheck() {
/*
monitor fragment retrieval time...
we compute expected time of arrival of the complete fragment.
we compare it to expected time of buffer starvation
*/
var hls = this.hls,
v = hls.media,
frag = this.fragCurrent;
// if loader has been destroyed or loading has been aborted, stop timer and return
if (!frag.loader || frag.loader.stats && frag.loader.stats.aborted) {
_logger.logger.warn('frag loader destroy or aborted, disarm abandonRulesCheck');
this.clearTimer();
return;
}
/* only monitor frag retrieval time if
(video not paused OR first fragment being loaded(ready state === HAVE_NOTHING = 0)) AND autoswitching enabled AND not lowest level (=> means that we have several levels) */
if (v && (!v.paused || !v.readyState) && frag.autoLevel && frag.level) {
var requestDelay = performance.now() - frag.trequest;
// monitor fragment load progress after half of expected fragment duration,to stabilize bitrate
if (requestDelay > 500 * frag.duration) {
var loadRate = Math.max(1, frag.loaded * 1000 / requestDelay); // byte/s; at least 1 byte/s to avoid division by zero
if (frag.expectedLen < frag.loaded) {
frag.expectedLen = frag.loaded;
}
var pos = v.currentTime;
var fragLoadedDelay = (frag.expectedLen - frag.loaded) / loadRate;
var bufferStarvationDelay = _bufferHelper2.default.bufferInfo(v, pos, hls.config.maxBufferHole).end - pos;
// consider emergency switch down only if we have less than 2 frag buffered AND
// time to finish loading current fragment is bigger than buffer starvation delay
// ie if we risk buffer starvation if bw does not increase quickly
if (bufferStarvationDelay < 2 * frag.duration && fragLoadedDelay > bufferStarvationDelay) {
var fragLevelNextLoadedDelay = void 0,
nextLoadLevel = void 0;
// lets iterate through lower level and try to find the biggest one that could avoid rebuffering
// we start from current level - 1 and we step down , until we find a matching level
for (nextLoadLevel = frag.level - 1; nextLoadLevel >= 0; 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)
fragLevelNextLoadedDelay = frag.duration * hls.levels[nextLoadLevel].bitrate / (8 * 0.8 * loadRate);
_logger.logger.log('fragLoadedDelay/bufferStarvationDelay/fragLevelNextLoadedDelay[' + nextLoadLevel + '] :' + fragLoadedDelay.toFixed(1) + '/' + bufferStarvationDelay.toFixed(1) + '/' + fragLevelNextLoadedDelay.toFixed(1));
if (fragLevelNextLoadedDelay < bufferStarvationDelay) {
// we found a lower level that be rebuffering free with current estimated bw !
break;
}
}
// only emergency switch down if it takes less time to load new fragment at lowest level instead
// of finishing loading current one ...
if (fragLevelNextLoadedDelay < fragLoadedDelay) {
// ensure nextLoadLevel is not negative
nextLoadLevel = Math.max(0, nextLoadLevel);
// force next load level in auto mode
hls.nextLoadLevel = nextLoadLevel;
// abort fragment loading ...
_logger.logger.warn('loading too slow, abort fragment loading and switch to level ' + nextLoadLevel);
//abort fragment loading
frag.loader.abort();
this.clearTimer();
hls.trigger(_events2.default.FRAG_LOAD_EMERGENCY_ABORTED, { frag: frag });
}
}
}
}
}
}, {
key: 'onFragLoaded',
value: function onFragLoaded(data) {
// stop monitoring bw once frag loaded
this.clearTimer();
// store level id after successful fragment load
this.lastLoadedFragLevel = data.frag.level;
// reset forced auto level value so that next level will be selected
this._nextAutoLevel = -1;
}
}, {
key: 'onError',
value: function onError(data) {
// stop timer in case of frag loading error
switch (data.details) {
case _errors.ErrorDetails.FRAG_LOAD_ERROR:
case _errors.ErrorDetails.FRAG_LOAD_TIMEOUT:
this.clearTimer();
break;
default:
break;
}
}
}, {
key: 'clearTimer',
value: function clearTimer() {
if (this.timer) {
clearInterval(this.timer);
this.timer = null;
}
}
/** Return the capping/max level value that could be used by automatic level selection algorithm **/
}, {
key: 'autoLevelCapping',
get: function get() {
return this._autoLevelCapping;
}
/** set the capping/max level value that could be used by automatic level selection algorithm **/
,
set: function set(newLevel) {
this._autoLevelCapping = newLevel;
}
}, {
key: 'nextAutoLevel',
get: function get() {
var lastbw = this.lastbw,
hls = this.hls,
adjustedbw,
i,
maxAutoLevel;
if (this._autoLevelCapping === -1 && hls.levels && hls.levels.length) {
maxAutoLevel = hls.levels.length - 1;
} else {
maxAutoLevel = this._autoLevelCapping;
}
// in case next auto level has been forced, return it straight-away (but capped)
if (this._nextAutoLevel !== -1) {
return Math.min(this._nextAutoLevel, maxAutoLevel);
}
// 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.
for (i = 0; i <= maxAutoLevel; i++) {
// 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 <= this.lastLoadedFragLevel) {
adjustedbw = 0.8 * lastbw;
} else {
adjustedbw = 0.7 * lastbw;
}
if (adjustedbw < hls.levels[i].bitrate) {
return Math.max(0, i - 1);
}
}
return i - 1;
},
set: function set(nextLevel) {
this._nextAutoLevel = nextLevel;
}
}]);
return AbrController;
}(_eventHandler2.default);
exports.default = AbrController;
},{"../errors":20,"../event-handler":21,"../events":22,"../helper/buffer-helper":24,"../utils/logger":38}],3:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
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 _events = require('../events');
var _events2 = _interopRequireDefault(_events);
var _eventHandler = require('../event-handler');
var _eventHandler2 = _interopRequireDefault(_eventHandler);
var _logger = require('../utils/logger');
var _errors = require('../errors');
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; } /*
* Buffer Controller
*/
var BufferController = function (_EventHandler) {
_inherits(BufferController, _EventHandler);
function BufferController(hls) {
_classCallCheck(this, BufferController);
// the value that we have set mediasource.duration to
// (the actual duration may be tweaked slighly by the browser)
var _this = _possibleConstructorReturn(this, (BufferController.__proto__ || Object.getPrototypeOf(BufferController)).call(this, hls, _events2.default.MEDIA_ATTACHING, _events2.default.MEDIA_DETACHING, _events2.default.BUFFER_RESET, _events2.default.BUFFER_APPENDING, _events2.default.BUFFER_CODECS, _events2.default.BUFFER_EOS, _events2.default.BUFFER_FLUSHING, _events2.default.FRAG_PARSING_DATA, _events2.default.FRAG_APPENDING, _events2.default.LEVEL_UPDATED));
_this._msDuration = null;
// the value that we want to set mediaSource.duration to
_this._levelDuration = null;
// Source Buffer listeners
_this.onsbue = _this.onSBUpdateEnd.bind(_this);
_this.onsbe = _this.onSBUpdateError.bind(_this);
_this.tracks = {};
return _this;
}
_createClass(BufferController, [{
key: 'destroy',
value: function destroy() {
_eventHandler2.default.prototype.destroy.call(this);
}
}, {
key: 'onFragParsingData',
value: function onFragParsingData(data) {
var type = data.type;
var audioTrack = this.tracks.audio;
// 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). At the time of change we issue
// `SourceBuffer.abort()` and adjusting `SourceBuffer.timestampOffset` if `SourceBuffer.updating` is false or awaiting `updateend`
// event if SB is in updating state.
// More info here: https://github.com/dailymotion/hls.js/issues/332#issuecomment-257986486
if (type === 'audio' && audioTrack && audioTrack.container === 'audio/mpeg') {
// Chrome audio mp3 track
var audioBuffer = this.sourceBuffer.audio;
var delta = Math.abs(audioBuffer.timestampOffset - data.startPTS);
// adjust timestamp offset if time delta is greater than 100ms
if (delta > 0.1) {
var updating = audioBuffer.updating;
try {
audioBuffer.abort();
} catch (err) {
updating = true;
_logger.logger.warn('can not abort audio buffer: ' + err);
}
if (!updating) {
_logger.logger.warn('change mpeg audio timestamp offset from ' + audioBuffer.timestampOffset + ' to ' + data.startPTS);
audioBuffer.timestampOffset = data.startPTS;
} else {
this.audioTimestampOffset = data.startPTS;
}
}
}
}
}, {
key: 'onMediaAttaching',
value: function onMediaAttaching(data) {
var media = this.media = data.media;
if (media) {
// setup the media source
var ms = this.mediaSource = new MediaSource();
//Media Source listeners
this.onmso = this.onMediaSourceOpen.bind(this);
this.onmse = this.onMediaSourceEnded.bind(this);
this.onmsc = this.onMediaSourceClose.bind(this);
ms.addEventListener('sourceopen', this.onmso);
ms.addEventListener('sourceended', this.onmse);
ms.addEventListener('sourceclose', this.onmsc);
// link video and media Source
var url = URL.createObjectURL(ms);
_logger.logger.log('set object url ' + url);
media.src = url;
}
}
}, {
key: 'onMediaDetaching',
value: function onMediaDetaching() {
_logger.logger.log('media source detaching');
var ms = this.mediaSource;
if (ms) {
if (ms.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
ms.endOfStream();
} catch (err) {
_logger.logger.warn('onMediaDetaching:' + err.message + ' while calling endOfStream');
}
}
ms.removeEventListener('sourceopen', this.onmso);
ms.removeEventListener('sourceended', this.onmse);
ms.removeEventListener('sourceclose', this.onmsc);
try {
// unlink MediaSource from video tag
this.media.src = '';
this.media.removeAttribute('src');
} catch (err) {
_logger.logger.warn('onMediaDetaching:' + err.message + ' while unlinking video.src');
}
this.mediaSource = null;
this.media = null;
this.pendingTracks = null;
this.tracks = {};
this.sourceBuffer = {};
this.flushRange = [];
this.segments = [];
this.appended = 0;
}
this.onmso = this.onmse = this.onmsc = null;
this.waitForAppended = false;
this.hls.trigger(_events2.default.MEDIA_DETACHED);
}
}, {
key: 'onMediaSourceOpen',
value: function onMediaSourceOpen() {
_logger.logger.log('media source opened');
this.hls.trigger(_events2.default.MEDIA_ATTACHED, { media: this.media });
// once received, don't listen anymore to sourceopen event
this.mediaSource.removeEventListener('sourceopen', this.onmso);
// if any buffer codecs pending, treat it here.
var pendingTracks = this.pendingTracks;
if (pendingTracks) {
this.onBufferCodecs(pendingTracks);
this.pendingTracks = null;
this.doAppending();
}
}
}, {
key: 'onMediaSourceClose',
value: function onMediaSourceClose() {
_logger.logger.log('media source closed');
}
}, {
key: 'onMediaSourceEnded',
value: function onMediaSourceEnded() {
_logger.logger.log('media source ended');
}
}, {
key: 'onFragAppending',
value: function onFragAppending() {
var segments = this.segments || [];
if (!segments.length && !this.isSbUpdating()) {
this.hls.trigger(_events2.default.FRAG_APPENDED);
} else {
this.waitForAppended = true;
}
}
}, {
key: 'isSbUpdating',
value: function isSbUpdating() {
var sourceBuffer = this.sourceBuffer;
if (!sourceBuffer) {
return;
}
for (var type in sourceBuffer) {
if (sourceBuffer[type].updating) {
return true;
}
}
}
}, {
key: 'dump',
value: function dump(video) {
var str = '',
b = video.buffered,
len = b.length;
for (var i = 0; i < len; i++) {
str += '[' + b.start(i) + ',' + b.end(i) + ']';
}
return str;
}
}, {
key: 'clear',
value: function clear(video, keepSec) {
var st,
sb = this.sourceBuffer,
end = video.currentTime - keepSec;
var b = video.buffered;
if (end <= 0 || this.isSbUpdating() || !b.length) {
return;
}
st = b.start(0);
if (st < end) {
_logger.logger.log('video buffered: ' + this.dump(this.media) + ' removing: [' + st + ',' + end + ']');
for (var type in sb) {
sb[type].remove(st, end);
}
}
}
}, {
key: 'onSBUpdateEnd',
value: function onSBUpdateEnd() {
// update timestampOffset
if (this.audioTimestampOffset) {
var audioBuffer = this.sourceBuffer.audio;
if (audioBuffer && !audioBuffer.updating) {
_logger.logger.warn('change mpeg audio timestamp offset from ' + audioBuffer.timestampOffset + ' to ' + this.audioTimestampOffset);
audioBuffer.timestampOffset = this.audioTimestampOffset;
delete this.audioTimestampOffset;
}
}
if (this._needsFlush) {
this.doFlush();
}
if (this._needsEos) {
this.onBufferEos();
}
_logger.logger.log('sb updateend');
this.updateMediaElementDuration();
this.doAppending();
if (this.waitForAppended && !this.segments.length && !this.isSbUpdating()) {
this.hls.trigger(_events2.default.FRAG_APPENDED);
this.waitForAppended = false;
}
var keep = void 0;
if ((keep = this.hls.config.keepBuffered) && this.media) {
try {
this.clear(this.media, keep);
} catch (err) {
_logger.logger.log(err);
}
}
}
}, {
key: 'onSBUpdateError',
value: function onSBUpdateError(event) {
var err = this.lastSegment ? 'last segment type:' + this.lastSegment.type + ',size:' + this.lastSegment.data.length + ')' : '';
_logger.logger.error('onSBUpdateError: sourceBuffer error:' + event + ' ' + err);
this.lastSegment = undefined;
this.printDump();
// according to http://www.w3.org/TR/media-source/#sourcebuffer-append-error
// this error might not always be fatal (it is fatal if decode error is set, in that case
// it will be followed by a mediaElement error ...)
this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.BUFFER_APPENDING_ERROR, fatal: false });
// we don't need to do more than that, as accordin to the spec, updateend will be fired just after
}
}, {
key: 'onBufferReset',
value: function onBufferReset() {
var sourceBuffer = this.sourceBuffer,
segments = this.segments || [];
_logger.logger.log('onBufferReset: pending segments:' + segments.length);
for (var type in sourceBuffer) {
var sb = sourceBuffer[type];
try {
this.mediaSource.removeSourceBuffer(sb);
sb.removeEventListener('updateend', this.onsbue);
sb.removeEventListener('error', this.onsbe);
} catch (err) {}
}
this.sourceBuffer = {};
this.flushRange = [];
this.appended = 0;
this.dumpSegments = undefined;
}
}, {
key: 'isTrackChanged',
value: function isTrackChanged(tracks) {
var track = void 0,
sb = this.sourceBuffer;
if (sb.video && !tracks.video || !sb.video && sb.audio && tracks.video) {
return true;
}
if (sb.audio && (track = tracks.audio)) {
var prev = this.tracks.audio;
var codec = track.levelCodec || track.codec;
var isMp3 = track.container === 'audio/mpeg' || prev.container === 'audio/mpeg' || codec === 'mp3' || prev.codec === 'mp3';
if ((track.container !== prev.container || prev.codec !== codec) && isMp3) {
return true;
}
}
}
}, {
key: 'onBufferCodecs',
value: function onBufferCodecs(tracks) {
var mediaSource = this.mediaSource;
// delay sourcebuffer creation if media source not opened yet
if (!mediaSource || mediaSource.readyState !== 'open') {
this.pendingTracks = tracks;
return;
}
var sourceBuffer = this.sourceBuffer;
if (this.isTrackChanged(tracks)) {
var media = this.media;
this.hls.detachMedia();
this.hls.attachMedia(media);
return;
}
for (var trackName in tracks) {
if (!sourceBuffer[trackName]) {
var track = tracks[trackName];
// use levelCodec as first priority
var codec = track.levelCodec || track.codec;
var mimeType = track.container + ';codecs=' + codec;
_logger.logger.log('creating sourceBuffer with mimeType:' + mimeType);
try {
var sb = sourceBuffer[trackName] = mediaSource.addSourceBuffer(mimeType);
sb.addEventListener('updateend', this.onsbue);
sb.addEventListener('error', this.onsbe);
this.tracks[trackName] = { codec: codec, container: track.container };
} catch (err) {
_logger.logger.error('error while trying to add sourceBuffer:' + err.message);
this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.BUFFER_ADD_CODEC_ERROR, fatal: false, err: err, mimeType: mimeType });
}
}
}
}
}, {
key: 'onBufferAppending',
value: function onBufferAppending(data) {
this.segments = this.segments || [];
this.segments.push(data);
this.doAppending();
}
}, {
key: 'onBufferAppendFail',
value: function onBufferAppendFail(data) {
var err = this.lastSegment ? 'last segment type:' + this.lastSegment.type + ',size:' + this.lastSegment.data.length + ')' : '';
_logger.logger.error('onBufferAppendFail:sourceBuffer error:' + data.event + ' ' + err);
this.lastSegment = undefined;
this.printDump();
// according to http://www.w3.org/TR/media-source/#sourcebuffer-append-error
// this error might not always be fatal (it is fatal if decode error is set, in that case
// it will be followed by a mediaElement error ...)
this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.BUFFER_APPENDING_ERROR, fatal: false, frag: this.fragCurrent });
}
}, {
key: 'onBufferEos',
value: function onBufferEos() {
var sb = this.sourceBuffer,
mediaSource = this.mediaSource;
if (!mediaSource || mediaSource.readyState !== 'open') {
return;
}
if (!(sb.audio && sb.audio.updating || sb.video && sb.video.updating)) {
_logger.logger.log('all media data available, signal endOfStream() to MediaSource and stop loading fragment');
//Notify the media element that it now has all of the media data
mediaSource.endOfStream();
this._needsEos = false;
} else {
this._needsEos = true;
}
}
}, {
key: 'onBufferFlushing',
value: function onBufferFlushing(data) {
this.flushRange.push({ start: data.startOffset, end: data.endOffset });
// attempt flush immediatly
this.flushBufferCounter = 0;
this.doFlush();
}
}, {
key: 'onLevelUpdated',
value: function onLevelUpdated(event) {
var details = event.details;
if (details.fragments.length === 0) {
return;
}
this._levelDuration = details.totalduration + details.fragments[0].start;
this.updateMediaElementDuration();
}
// https://github.com/dailymotion/hls.js/issues/355
}, {
key: 'updateMediaElementDuration',
value: function updateMediaElementDuration() {
var media = this.media,
mediaSource = this.mediaSource,
levelDuration = this._levelDuration;
if (levelDuration === null || !media || !mediaSource || media.readyState === 0 || mediaSource.readyState !== 'open') {
return;
}
for (var i = 0; i < mediaSource.sourceBuffers.length; i++) {
if (mediaSource.sourceBuffers[i].updating) {
// can't set duration whilst a buffer is updating
return;
}
}
if (this._msDuration === null) {
// initialise to the value that the media source is reporting
this._msDuration = mediaSource.duration;
}
var duration = media.duration;
// levelDuration was the last value we set.
// not using mediaSource.duration as the browser may tweak this value
// only update mediasource duration if its value increase, this is to avoid
// flushing already buffered portion when switching between quality level
if (levelDuration > this._msDuration && levelDuration > duration || duration === Infinity || isNaN(duration)) {
_logger.logger.log('Updating mediasource duration to ' + levelDuration.toFixed(3));
this._msDuration = mediaSource.duration = levelDuration;
}
}
}, {
key: 'doFlush',
value: function doFlush() {
// loop through all buffer ranges to flush
while (this.flushRange.length) {
var range = this.flushRange[0];
// flushBuffer will abort any buffer append in progress and flush Audio/Video Buffer
if (this.flushBuffer(range.start, range.end)) {
// range flushed, remove from flush array
this.flushRange.shift();
this.flushBufferCounter = 0;
} else {
this._needsFlush = true;
// avoid looping, wait for SB update end to retrigger a flush
return;
}
}
if (this.flushRange.length === 0) {
// everything flushed
this._needsFlush = false;
// let's recompute this.appended, which is used to avoid flush looping
var appended = 0;
var sourceBuffer = this.sourceBuffer;
for (var type in sourceBuffer) {
appended += sourceBuffer[type].buffered.length;
}
this.appended = appended;
this.hls.trigger(_events2.default.BUFFER_FLUSHED);
}
}
}, {
key: 'dumpSegment',
value: function dumpSegment(segment) {
var i = void 0,
len = segment.data.length;
var info = 'queue:' + this.segments.length + 'type:' + segment.type + ',size:' + len + ',buf:[';
for (i = 0, len = Math.min(len, 10); i < len; i++) {
if (i) {
info += ',';
}
info += segment.data[i];
}
info += '..]';
if (!this.dumpSegments) {
this.dumpSegments = [info];
} else {
this.dumpSegments.push(info);
}
if (this.dumpSegments.length > 10) {
this.dumpSegments.shift();
}
}
}, {
key: 'printDump',
value: function printDump() {
if (this.dumpSegments && this.dumpSegments.length) {
_logger.logger.error(this.dumpSegments.join('|'));
}
}
}, {
key: 'doAppending',
value: function doAppending() {
var hls = this.hls,
sourceBuffer = this.sourceBuffer,
segments = this.segments;
if (sourceBuffer && Object.keys(sourceBuffer).length) {
if (!this.media) {
return;
}
if (this.media.error) {
this.segments = [];
_logger.logger.error('trying to append although a media error occured, flush segment and abort');
return;
}
if (this.isSbUpdating()) {
_logger.logger.log('sb update in progress');
return;
}
if (segments.length) {
var segment = segments.shift();
this.dumpSegment(segment);
try {
_logger.logger.log('appending ' + segment.type + ' SB, size:' + segment.data.length);
if (sourceBuffer[segment.type]) {
this.lastSegment = segment;
sourceBuffer[segment.type].appendBuffer(segment.data);
this.appendError = 0;
this.appended++;
} else {
// in case we don't have any source buffer matching with this segment type,
// it means that Mediasource fails to create sourcebuffer
// discard this segment, and trigger update end
this.onSBUpdateEnd();
}
} catch (err) {
// in case any error occured while appending, put back segment in segments table
_logger.logger.error('error while trying to append buffer: ' + err.message);
segments.unshift(segment);
var event = { type: _errors.ErrorTypes.MEDIA_ERROR };
if (err.code !== 22) {
if (this.appendError) {
this.appendError++;
} else {
this.appendError = 1;
}
event.details = _errors.ErrorDetails.BUFFER_APPEND_ERROR;
event.frag = this.fragCurrent;
event.reason = err.message + ' (type:' + segment.type + ',size:' + segment.data.length + ')';
/* with UHD content, we could get loop of quota exceeded error until
browser is able to evict some data from sourcebuffer. retrying help recovering this
*/
if (this.appendError > hls.config.appendErrorMaxRetry) {
_logger.logger.log('fail ' + hls.config.appendErrorMaxRetry + ' times to append segment in sourceBuffer');
this.segments = [];
event.fatal = true;
hls.trigger(_events2.default.ERROR, event);
return;
} else {
event.fatal = false;
hls.trigger(_events2.default.ERROR, event);
}
} else {
// QuotaExceededError: http://www.w3.org/TR/html5/infrastructure.html#quotaexceedederror
// let's stop appending any segments, and report BUFFER_FULL_ERROR error
this.segments = [];
event.details = _errors.ErrorDetails.BUFFER_FULL_ERROR;
hls.trigger(_events2.default.ERROR, event);
}
}
}
}
}
/*
flush specified buffered range,
return true once range has been flushed.
as sourceBuffer.remove() is asynchronous, flushBuffer will be retriggered on sourceBuffer update end
*/
}, {
key: 'flushBuffer',
value: function flushBuffer(startOffset, endOffset) {
var sb, i, bufStart, bufEnd, flushStart, flushEnd;
_logger.logger.log('flushBuffer,pos/start/end: ' + this.media.currentTime + '/' + startOffset + '/' + endOffset);
// safeguard to avoid infinite looping : don't try to flush more than the nb of appended segments
if (this.flushBufferCounter < this.appended && this.sourceBuffer) {
for (var type in this.sourceBuffer) {
sb = this.sourceBuffer[type];
if (!sb.updating) {
for (i = 0; i < sb.buffered.length; i++) {
bufStart = sb.buffered.start(i);
bufEnd = sb.buffered.end(i);
// workaround firefox not able to properly flush multiple buffered range.
if (navigator.userAgent.toLowerCase().indexOf('firefox') !== -1 && endOffset === Number.POSITIVE_INFINITY) {
flushStart = startOffset;
flushEnd = endOffset;
} else {
flushStart = Math.max(bufStart, startOffset);
flushEnd = Math.min(bufEnd, endOffset);
}
/* sometimes sourcebuffer.remove() does not flush
the exact expected time range.
to avoid rounding issues/infinite loop,
only flush buffer range of length greater than 500ms.
*/
if (Math.min(flushEnd, bufEnd) - flushStart > 0.5) {
this.flushBufferCounter++;
_logger.logger.log('flush ' + type + ' [' + flushStart + ',' + flushEnd + '], of [' + bufStart + ',' + bufEnd + '], pos:' + this.media.currentTime);
sb.remove(flushStart, flushEnd);
return false;
}
}
} else {
//logger.log('abort ' + type + ' append in progress');
// this will abort any appending in progress
//sb.abort();
_logger.logger.warn('cannot flush, sb updating in progress');
return false;
}
}
} else {
_logger.logger.warn('abort flushing too many retries');
}
_logger.logger.log('buffer flushed');
// everything flushed !
return true;
}
}]);
return BufferController;
}(_eventHandler2.default);
exports.default = BufferController;
},{"../errors":20,"../event-handler":21,"../events":22,"../utils/logger":38}],4:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
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 _events = require('../events');
var _events2 = _interopRequireDefault(_events);
var _eventHandler = require('../event-handler');
var _eventHandler2 = _interopRequireDefault(_eventHandler);
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; } /*
* cap stream level to media size dimension controller
*/
var CapLevelController = function (_EventHandler) {
_inherits(CapLevelController, _EventHandler);
function CapLevelController(hls) {
_classCallCheck(this, CapLevelController);
return _possibleConstructorReturn(this, (CapLevelController.__proto__ || Object.getPrototypeOf(CapLevelController)).call(this, hls, _events2.default.FPS_DROP_LEVEL_CAPPING, _events2.default.MEDIA_ATTACHING, _events2.default.MANIFEST_PARSED));
}
_createClass(CapLevelController, [{
key: 'destroy',
value: function destroy() {
if (this.hls.config.capLevelToPlayerSize) {
this.media = this.restrictedLevels = null;
this.autoLevelCapping = Number.POSITIVE_INFINITY;
if (this.timer) {
this.timer = clearInterval(this.timer);
}
}
}
}, {
key: 'onFpsDropLevelCapping',
value: function onFpsDropLevelCapping(data) {
if (!this.restrictedLevels) {
this.restrictedLevels = [];
}
if (!this.isLevelRestricted(data.droppedLevel)) {
this.restrictedLevels.push(data.droppedLevel);
}
}
}, {
key: 'onMediaAttaching',
value: function onMediaAttaching(data) {
this.media = data.media instanceof HTMLVideoElement ? data.media : null;
}
}, {
key: 'onManifestParsed',
value: function onManifestParsed(data) {
if (this.hls.config.capLevelToPlayerSize) {
this.autoLevelCapping = Number.POSITIVE_INFINITY;
this.levels = data.levels;
this.hls.firstLevel = this.getMaxLevel(data.firstLevel);
clearInterval(this.timer);
this.timer = setInterval(this.detectPlayerSize.bind(this), 1000);
this.detectPlayerSize();
}
}
}, {
key: 'detectPlayerSize',
value: function detectPlayerSize() {
if (this.media) {
var levelsLength = this.levels ? this.levels.length : 0;
if (levelsLength) {
this.hls.autoLevelCapping = this.getMaxLevel(levelsLength - 1);
if (this.hls.autoLevelCapping > this.autoLevelCapping) {
// 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.hls.streamController.nextLevelSwitch();
}
this.autoLevelCapping = this.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)
*/
}, {
key: 'getMaxLevel',
value: function getMaxLevel(capLevelIndex) {
var result = 0,
i = void 0,
level = void 0,
mWidth = this.mediaWidth,
mHeight = this.mediaHeight,
lWidth = 0,
lHeight = 0;
for (i = 0; i <= capLevelIndex; i++) {
level = this.levels[i];
if (this.isLevelRestricted(i)) {
break;
}
result = i;
lWidth = level.width;
lHeight = level.height;
if (mWidth <= lWidth || mHeight <= lHeight) {
break;
}
}
return result;
}
}, {
key: 'isLevelRestricted',
value: function isLevelRestricted(level) {
return this.restrictedLevels && this.restrictedLevels.indexOf(level) !== -1 ? true : false;
}
}, {
key: 'contentScaleFactor',
get: function get() {
var pixelRatio = 1;
try {
pixelRatio = window.devicePixelRatio;
} catch (e) {}
return pixelRatio;
}
}, {
key: 'mediaWidth',
get: function get() {
var width = void 0;
if (this.media) {
width = this.media.width || this.media.clientWidth || this.media.offsetWidth;
width *= this.contentScaleFactor;
}
return width;
}
}, {
key: 'mediaHeight',
get: function get() {
var height = void 0;
if (this.media) {
height = this.media.height || this.media.clientHeight || this.media.offsetHeight;
height *= this.contentScaleFactor;
}
return height;
}
}]);
return CapLevelController;
}(_eventHandler2.default);
exports.default = CapLevelController;
},{"../event-handler":21,"../events":22}],5:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
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 _events = require('../events');
var _events2 = _interopRequireDefault(_events);
var _eventHandler = require('../event-handler');
var _eventHandler2 = _interopRequireDefault(_eventHandler);
var _logger = require('../utils/logger');
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; } /*
* FPS Controller
*/
var FPSController = function (_EventHandler) {
_inherits(FPSController, _EventHandler);
function FPSController(hls) {
_classCallCheck(this, FPSController);
return _possibleConstructorReturn(this, (FPSController.__proto__ || Object.getPrototypeOf(FPSController)).call(this, hls, _events2.default.MEDIA_ATTACHING));
}
_createClass(FPSController, [{
key: 'destroy',
value: function destroy() {
if (this.timer) {
clearInterval(this.timer);
}
this.isVideoPlaybackQualityAvailable = false;
}
}, {
key: 'onMediaAttaching',
value: function onMediaAttaching(data) {
if (this.hls.config.capLevelOnFPSDrop) {
this.video = data.media instanceof HTMLVideoElement ? data.media : null;
if (typeof this.video.getVideoPlaybackQuality === 'function') {
this.isVideoPlaybackQualityAvailable = true;
}
clearInterval(this.timer);
this.timer = setInterval(this.checkFPSInterval.bind(this), this.hls.config.fpsDroppedMonitoringPeriod);
}
}
}, {
key: 'checkFPS',
value: function checkFPS(video, decodedFrames, droppedFrames) {
var currentTime = performance.now();
if (decodedFrames) {
if (this.lastTime) {
var currentPeriod = currentTime - this.lastTime,
currentDropped = droppedFrames - this.lastDroppedFrames,
currentDecoded = decodedFrames - this.lastDecodedFrames,
droppedFPS = 1000 * currentDropped / currentPeriod;
this.hls.trigger(_events2.default.FPS_DROP, { currentDropped: currentDropped, currentDecoded: currentDecoded, totalDroppedFrames: droppedFrames });
if (droppedFPS > 0) {
//logger.log('checkFPS : droppedFPS/decodedFPS:' + droppedFPS/(1000 * currentDecoded / currentPeriod));
if (currentDropped > this.hls.config.fpsDroppedMonitoringThreshold * currentDecoded) {
var currentLevel = this.hls.currentLevel;
_logger.logger.warn('drop FPS ratio greater than max allowed value for currentLevel: ' + currentLevel);
if (currentLevel > 0 && (this.hls.autoLevelCapping === -1 || this.hls.autoLevelCapping >= currentLevel)) {
currentLevel = currentLevel - 1;
this.hls.trigger(_events2.default.FPS_DROP_LEVEL_CAPPING, { level: currentLevel, droppedLevel: this.hls.currentLevel });
this.hls.autoLevelCapping = currentLevel;
this.hls.streamController.nextLevelSwitch();
}
}
}
}
this.lastTime = currentTime;
this.lastDroppedFrames = droppedFrames;
this.lastDecodedFrames = decodedFrames;
}
}
}, {
key: 'checkFPSInterval',
value: function checkFPSInterval() {
if (this.video) {
if (this.isVideoPlaybackQualityAvailable) {
var videoPlaybackQuality = this.video.getVideoPlaybackQuality();
this.checkFPS(this.video, videoPlaybackQuality.totalVideoFrames, videoPlaybackQuality.droppedVideoFrames);
} else {
this.checkFPS(this.video, this.video.webkitDecodedFrameCount, this.video.webkitDroppedFrameCount);
}
}
}
}]);
return FPSController;
}(_eventHandler2.default);
exports.default = FPSController;
},{"../event-handler":21,"../events":22,"../utils/logger":38}],6:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
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 _events = require('../events');
var _events2 = _interopRequireDefault(_events);
var _eventHandler = require('../event-handler');
var _eventHandler2 = _interopRequireDefault(_eventHandler);
var _levelHelper = require('../helper/level-helper');
var _levelHelper2 = _interopRequireDefault(_levelHelper);
var _logger = require('../utils/logger');
var _errors = require('../errors');
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; } /*
* Level Controller
*/
var LevelController = function (_EventHandler) {
_inherits(LevelController, _EventHandler);
function LevelController(hls) {
_classCallCheck(this, LevelController);
var _this = _possibleConstructorReturn(this, (LevelController.__proto__ || Object.getPrototypeOf(LevelController)).call(this, hls, _events2.default.MANIFEST_LOADED, _events2.default.LEVEL_LOADED, _events2.default.ERROR));
_this.ontick = _this.tick.bind(_this);
_this._manualLevel = _this._autoLevelCapping = -1;
return _this;
}
_createClass(LevelController, [{
key: 'destroy',
value: function destroy() {
if (this.timer) {
clearTimeout(this.timer);
this.timer = null;
}
this._manualLevel = -1;
}
}, {
key: 'clearLevelDetails',
value: function clearLevelDetails() {
// clean up live level details to force reload them, and reset load errors
if (this._levels) {
this._levels.forEach(function (level) {
level.loadError = 0;
var levelDetails = level.details;
if (levelDetails && levelDetails.live) {
level.details = undefined;
}
});
}
}
}, {
key: 'startLoad',
value: function startLoad() {
this.canload = true;
// speed up live playlist refresh
if (_levelHelper2.default.isLive(this._level, this._levels)) {
this.tick();
}
}
}, {
key: 'stopLoad',
value: function stopLoad() {
this.canload = false;
}
}, {
key: 'isVideoLevel',
value: function isVideoLevel(level) {
return level.videoCodec || !level.audioCodec && (level.bitrate > 64000 || level.width || level.height);
}
}, {
key: 'onManifestLoaded',
value: function onManifestLoaded(data) {
var _this2 = this;
var levels0 = [],
levels = [],
bitrateStart,
bitrateSet = {},
videoCodecFound = false,
audioCodecFound = false,
hls = this.hls,
i,
brokenmp4inmp3 = /chrome|firefox/.test(navigator.userAgent.toLowerCase()),
checkSupported = function checkSupported(type, codec) {
return MediaSource.isTypeSupported(type + '/mp4;codecs=' + codec);
};
// regroup redundant level together
data.levels.forEach(function (level) {
if (_this2.isVideoLevel(level)) {
videoCodecFound = true;
}
// erase audio codec info if browser does not support mp4a.40.34. demuxer will autodetect codec and fallback to mpeg/audio
if (brokenmp4inmp3 && level.audioCodec && level.audioCodec.indexOf('mp4a.40.34') !== -1) {
level.audioCodec = undefined;
}
if (level.audioCodec || level.attrs && level.attrs.AUDIO) {
audioCodecFound = true;
}
var redundantLevelId = bitrateSet[level.bitrate];
if (redundantLevelId === undefined) {
bitrateSet[level.bitrate] = levels0.length;
level.url = [level.url];
level.urlId = 0;
levels0.push(level);
} else {
levels0[redundantLevelId].url.push(level.url);
}
});
// remove audio-only level if we also have levels with audio+video codecs signalled
if (videoCodecFound && audioCodecFound) {
levels0.forEach(function (level) {
if (_this2.isVideoLevel(level)) {
levels.push(level);
}
});
} else {
levels = levels0;
}
// only keep level with supported audio/video codecs
levels = levels.filter(function (level) {
var audioCodec = level.audioCodec,
videoCodec = level.videoCodec;
return (!audioCodec || checkSupported('audio', audioCodec)) && (!videoCodec || checkSupported('video', videoCodec));
});
if (levels.length) {
// 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 (i = 0; i < levels.length; i++) {
if (levels[i].bitrate === bitrateStart) {
this._firstLevel = i;
_logger.logger.log('manifest loaded,' + levels.length + ' level(s) found, first bitrate:' + bitrateStart);
break;
}
}
hls.trigger(_events2.default.MANIFEST_PARSED, { levels: this._levels, firstLevel: this._firstLevel, stats: data.stats });
} else {
hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.MANIFEST_INCOMPATIBLE_CODECS_ERROR, fatal: true, url: hls.url, reason: 'no level with compatible codecs found in manifest' });
}
return;
}
}, {
key: 'setLevelInternal',
value: function setLevelInternal(newLevel) {
var levels = this._levels;
// check if level idx is valid
if (newLevel >= 0 && newLevel < levels.length) {
// stopping live reloading timer if any
if (this.timer) {
clearTimeout(this.timer);
this.timer = null;
}
if (this._level !== newLevel) {
_logger.logger.log('switching to level ' + newLevel);
this._level = newLevel;
this.hls.trigger(_events2.default.LEVEL_SWITCH, { level: newLevel });
}
var level = levels[newLevel];
// check if we need to load playlist for this level
if (!level.details || level.details.live === true) {
// level not retrieved yet, or live playlist we need to (re)load it
_logger.logger.log('(re)loading playlist for level ' + newLevel);
var urlId = level.urlId;
this.hls.trigger(_events2.default.LEVEL_LOADING, { url: level.url[urlId], level: newLevel, id: urlId });
}
} else {
// invalid level id given, trigger error
this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.OTHER_ERROR, details: _errors.ErrorDetails.LEVEL_SWITCH_ERROR, level: newLevel, fatal: false, reason: 'invalid level idx' });
}
}
}, {
key: 'onError',
value: function onError(data) {
if (data.fatal) {
return;
}
var details = data.details,
hls = this.hls,
levelId = void 0,
level = void 0,
levelError = false;
// try to recover not fatal errors
switch (details) {
case _errors.ErrorDetails.FRAG_LOAD_ERROR:
case _errors.ErrorDetails.FRAG_LOAD_TIMEOUT:
case _errors.ErrorDetails.FRAG_LOOP_LOADING_ERROR:
case _errors.ErrorDetails.KEY_LOAD_ERROR:
case _errors.ErrorDetails.KEY_LOAD_TIMEOUT:
levelId = data.frag.level;
break;
case _errors.ErrorDetails.LEVEL_LOAD_ERROR:
case _errors.ErrorDetails.LEVEL_LOAD_TIMEOUT:
levelId = data.level;
levelError = true;
break;
default:
break;
}
/* try to switch to a redundant stream if any available.
* if no redundant stream available, emergency switch down (if in auto mode and current level not 0)
* otherwise, we cannot recover this network error ...
* don't raise FRAG_LOAD_ERROR and FRAG_LOAD_TIMEOUT as fatal, as it is handled by mediaController
*/
if (levelId !== undefined) {
level = this._levels[levelId];
if (level.urlId < level.url.length - 1) {
level.urlId++;
if (this.hls.config.clearLevelDetailsOnSwitching) {
level.details = undefined;
}
_logger.logger.warn('level controller,' + details + ' for level ' + levelId + ': switching to redundant stream id ' + level.urlId);
} else {
// we could try to recover if in auto mode and current level not lowest level (0)
var recoverable = this._manualLevel === -1 && levelId;
if (recoverable) {
_logger.logger.warn('level controller,' + details + ': emergency switch-down for next fragment');
hls.abrController.nextAutoLevel = 0;
} else if (level && level.details && level.details.live) {
_logger.logger.warn('level controller,' + details + ' on live stream, discard');
if (levelError) {
// reset this._level so that another call to set level() will retrigger a frag load
this._level = undefined;
}
// FRAG_LOAD_ERROR and FRAG_LOAD_TIMEOUT are handled by mediaController
} else if (details !== _errors.ErrorDetails.FRAG_LOAD_ERROR && details !== _errors.ErrorDetails.FRAG_LOAD_TIMEOUT) {
_logger.logger.error('cannot recover ' + details + ' error');
this._level = undefined;
// stopping live reloading timer if any
if (this.timer) {
clearTimeout(this.timer);
this.timer = null;
}
// redispatch same error but with fatal set to true
data.fatal = true;
hls.trigger(_events2.default.ERROR, data);
}
}
}
}
}, {
key: 'onLevelLoaded',
value: function onLevelLoaded(data) {
// only process level loaded events matching with expected level
if (data.level === this._level) {
var newDetails = data.details;
// if current playlist is a live playlist, arm a timer to reload it
if (newDetails.live) {
var reloadInterval = 1000 * (newDetails.averagetargetduration ? newDetails.averagetargetduration : newDetails.targetduration),
curLevel = this._levels[data.level],
curDetails = curLevel.details;
if (curDetails && newDetails.endSN === curDetails.endSN) {
// 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.
reloadInterval /= 2;
_logger.logger.log('same live playlist, reload twice faster');
}
// decrement reloadInterval with level loading delay
reloadInterval -= performance.now() - data.stats.trequest;
// in any case, don't reload more than every second
reloadInterval = Math.max(1000, Math.round(reloadInterval));
_logger.logger.log('live playlist, reload in ' + reloadInterval + ' ms');
this.timer = setTimeout(this.ontick, reloadInterval);
} else {
this.timer = null;
}
}
}
}, {
key: 'tick',
value: function tick() {
var levelId = this._level;
if (levelId !== undefined && this.canload) {
var level = this._levels[levelId],
urlId = level.urlId;
this.hls.trigger(_events2.default.LEVEL_LOADING, { url: level.url[urlId], level: levelId, id: urlId });
}
}
}, {
key: 'levels',
get: function get() {
return this._levels;
}
}, {
key: 'level',
get: function get() {
return this._level;
},
set: function set(newLevel) {
var levels = this._levels;
if (levels && levels.length > newLevel) {
if (this._level !== newLevel || levels[newLevel].details === undefined) {
this.setLevelInternal(newLevel);
}
}
}
}, {
key: 'manualLevel',
get: function get() {
return this._manualLevel;
},
set: function set(newLevel) {
this._manualLevel = 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() {
return this._startLevel === undefined ? this._firstLevel : this._startLevel;
},
set: function set(newLevel) {
this._startLevel = newLevel;
}
}, {
key: 'nextLoadLevel',
get: function get() {
if (this._manualLevel !== -1) {
return this._manualLevel;
} else {
return this.hls.abrController.nextAutoLevel;
}
},
set: function set(nextLevel) {
this.level = nextLevel;
if (this._manualLevel === -1) {
this.hls.abrController.nextAutoLevel = nextLevel;
}
}
}]);
return LevelController;
}(_eventHandler2.default);
exports.default = LevelController;
},{"../errors":20,"../event-handler":21,"../events":22,"../helper/level-helper":25,"../utils/logger":38}],7:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
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 _demuxer = require('../demux/demuxer');
var _demuxer2 = _interopRequireDefault(_demuxer);
var _events = require('../events');
var _events2 = _interopRequireDefault(_events);
var _eventHandler = require('../event-handler');
var _eventHandler2 = _interopRequireDefault(_eventHandler);
var _logger = require('../utils/logger');
var _binarySearch = require('../utils/binary-search');
var _binarySearch2 = _interopRequireDefault(_binarySearch);
var _bufferHelper = require('../helper/buffer-helper');
var _bufferHelper2 = _interopRequireDefault(_bufferHelper);
var _levelHelper = require('../helper/level-helper');
var _levelHelper2 = _interopRequireDefault(_levelHelper);
var _errors = require('../errors');
var _browser = require('../utils/browser');
var _browser2 = _interopRequireDefault(_browser);
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; } /*
* Stream Controller
*/
var State = {
STOPPED: 'STOPPED',
STARTING: 'STARTING',
IDLE: 'IDLE',
PAUSED: 'PAUSED',
KEY_LOADING: 'KEY_LOADING',
FRAG_LOADING: 'FRAG_LOADING',
FRAG_LOADING_WAITING_RETRY: 'FRAG_LOADING_WAITING_RETRY',
WAITING_LEVEL: 'WAITING_LEVEL',
PARSING: 'PARSING',
PARSED: 'PARSED',
ENDED: 'ENDED',
ERROR: 'ERROR'
};
var StreamController = function (_EventHandler) {
_inherits(StreamController, _EventHandler);
function StreamController(hls) {
_classCallCheck(this, StreamController);
var _this = _possibleConstructorReturn(this, (StreamController.__proto__ || Object.getPrototypeOf(StreamController)).call(this, hls, _events2.default.MEDIA_ATTACHED, _events2.default.MEDIA_DETACHING, _events2.default.MANIFEST_LOADING, _events2.default.MANIFEST_PARSED, _events2.default.LEVEL_LOADED, _events2.default.LEVEL_PTS_UPDATED, _events2.default.KEY_LOADED, _events2.default.FRAG_CHUNK_LOADED, _events2.default.FRAG_LOADED, _events2.default.FRAG_LOAD_EMERGENCY_ABORTED, _events2.default.FRAG_PARSING_INIT_SEGMENT, _events2.default.FRAG_PARSING_DATA, _events2.default.FRAG_PARSED, _events2.default.FRAG_APPENDED, _events2.default.ERROR, _events2.default.BUFFER_FLUSHED, _events2.default.DEMUXER_QUEUE_EMPTY));
_this.config = hls.config;
_this.audioCodecSwap = false;
_this.ticks = 0;
_this.ontick = _this.tick.bind(_this);
_this.noMediaCount = 0;
return _this;
}
_createClass(StreamController, [{
key: 'destroy',
value: function destroy() {
this.stopLoad();
delete this.fragPreviousSaved;
if (this.timer) {
clearInterval(this.timer);
this.timer = null;
}
_eventHandler2.default.prototype.destroy.call(this);
this.state = State.STOPPED;
}
}, {
key: 'startLoad',
value: function startLoad() {
var startPosition = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
if (this.levels) {
var media = this.media,
lastCurrentTime = this.lastCurrentTime;
this.stopLoad();
if (!this.demuxer) {
this.demuxer = new _demuxer2.default(this.hls);
this.fragParsing = null;
}
if (!this.timer) {
this.timer = setInterval(this.ontick, 100);
}
if (this.fragPreviousSaved) {
this.fragPrevious = this.fragPreviousSaved;
delete this.fragPrevious;
}
this.level = -1;
this.fragLoadError = 0;
if (media && lastCurrentTime > 0) {
var lastLevel = this.hls.loadLevel;
if (_levelHelper2.default.isLive(lastLevel, this.levels)) {
this.level = lastLevel;
this.waitLiveLevel = true;
}
_logger.logger.log('configure startPosition @' + lastCurrentTime);
this.state = this.level === -1 ? State.IDLE : State.WAITING_LEVEL;
} else {
this.lastCurrentTime = this.startPosition ? this.startPosition : startPosition;
_logger.logger.log('configure lastCurrentTime @' + this.lastCurrentTime + ' start:' + this.startPosition + ',' + startPosition);
this.state = State.STARTING;
}
this.nextLoadPosition = this.startPosition = this.lastCurrentTime;
this.tick();
} else {
_logger.logger.warn('cannot start loading as manifest not parsed yet');
this.state = State.STOPPED;
}
}
}, {
key: 'onDemuxerQueueEmpty',
value: function onDemuxerQueueEmpty() {
this.fragParsing = null;
}
}, {
key: 'stopLoad',
value: function stopLoad() {
var frag = this.fragCurrent;
if (frag) {
if (frag.loader) {
frag.loader.abort();
}
this.fragCurrent = null;
}
this.fragPreviousSaved = this.fragPrevious || this.fragPreviousSaved;
this.fragPrevious = null;
if (this.state === State.PARSING && this.demuxer && this.config.enableWorker) {
this.fragParsing = frag;
this.demuxer.waitQueue();
}
this.state = State.STOPPED;
}
}, {
key: 'tick',
value: function tick() {
this.ticks++;
if (this.ticks === 1) {
this.doTick();
if (this.ticks > 1) {
setTimeout(this.tick, 1);
}
this.ticks = 0;
}
}
}, {
key: 'doTick',
value: function doTick() {
switch (this.state) {
case State.STARTING:
var hls = this.hls;
// determine load level
var startLevel = hls.startLevel;
if (startLevel === -1) {
startLevel = 0;
}
// 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.state = State.WAITING_LEVEL;
this.loadedmetadata = false;
break;
case State.IDLE:
if (!this.media) {
if (this.noMediaCount++ % 20 === 0) {
var media = this.hls.bufferController.media || {};
var ms = this.hls.bufferController.mediaSource || {};
_logger.logger.log('no media ' + media + ' src=' + media.src + ' ms_state=' + ms.readyState);
}
} else {
if (this.noMediaCount) {
_logger.logger.log('media is set to ' + this.media.src);
}
this.noMediaCount = 0;
}
// when this returns false there was an error and we shall return immediatly
// from current tick
if (!this._doTickIdle()) {
return;
}
break;
case State.WAITING_LEVEL:
var level = this.levels[this.level];
// check if playlist is already loaded
if (level && level.details && !this.waitLiveLevel) {
this.state = State.IDLE;
}
break;
case State.FRAG_LOADING:
try {
if (this.levels[this.level].details.live && this.fragCurrent.sn < this.levels[this.level].details.startSN) {
_logger.logger.log('live playlist slided forward loading segments: reload');
this.state = State.IDLE;
}
} catch (e) {}
break;
case State.FRAG_LOADING_WAITING_RETRY:
var now = 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.seeking) {
_logger.logger.log('mediaController: retryDate reached, switch back to IDLE state');
this.state = State.IDLE;
}
break;
case State.ERROR:
case State.PAUSED:
case State.STOPPED:
case State.PARSING:
case State.PARSED:
case State.ENDED:
break;
default:
break;
}
// check buffer
this._checkBuffer();
// check/update current fragment
this._checkFragmentChanged();
}
// Ironically the "idle" state is the on we do the most logic in it seems ....
// NOTE: Maybe we could rather schedule a check for buffer length after half of the currently
// played segment, or on pause/play/seek instead of naively checking every 100ms?
}, {
key: '_doTickIdle',
value: function _doTickIdle() {
var hls = this.hls,
config = hls.config;
// if video not attached AND
// start fragment already requested OR start frag prefetch disable
// exit loop
// => if media not attached but start frag prefetch is enabled and start frag not requested yet, we will not exit loop
if (this.levelLastLoaded !== undefined && !this.media && (this.startFragRequested || !config.startFragPrefetch)) {
return true;
}
// if we have not yet loaded any fragment, start loading from start position
var pos = this.loadedmetadata ? this.media.currentTime : this.nextLoadPosition;
// determine next load level
var level = hls.nextLoadLevel;
// 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 = void 0;
if (this.levels[level].hasOwnProperty('bitrate')) {
maxBufLen = Math.max(8 * config.maxBufferSize / this.levels[level].bitrate, config.maxBufferLength);
maxBufLen = Math.min(maxBufLen, config.maxMaxBufferLength);
} else {
maxBufLen = config.maxBufferLength;
}
// determine next candidate fragment to be loaded, based on current position and end of buffer position
// ensure up to `config.maxMaxBufferLength` of buffer upfront
var bufferInfo = _bufferHelper2.default.bufferInfo(this.media, pos, config.maxBufferHole),
bufferLen = bufferInfo.len;
// Stay idle if we are still with buffer margins
if (bufferLen >= maxBufLen) {
return true;
}
// if buffer length is less than maxBufLen try to load a new fragment ...
_logger.logger.trace('buffer length of ' + bufferLen.toFixed(3) + ' is below max of ' + maxBufLen.toFixed(3) + '. checking for more payload ...');
// set next load level : this will trigger a playlist load if needed
this.level = hls.nextLoadLevel = level;
var levelDetails = this.levels[level].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 (typeof levelDetails === 'undefined' || levelDetails.live && this.levelLastLoaded !== level) {
this.state = State.WAITING_LEVEL;
return true;
}
// if we have the levelDetails for the selected variant, lets continue enrichen our stream (load keys/fragments or trigger EOS, etc..)
return this._fetchPayloadOrEos({ pos: pos, bufferInfo: bufferInfo, levelDetails: levelDetails });
}
}, {
key: '_fetchPayloadOrEos',
value: function _fetchPayloadOrEos(_ref) {
var pos = _ref.pos,
bufferInfo = _ref.bufferInfo,
levelDetails = _ref.levelDetails;
var fragPrevious = this.fragPrevious,
level = this.level,
fragments = levelDetails.fragments,
fragLen = fragments.length;
// empty playlist
if (fragLen === 0) {
return false;
}
// find fragment index, contiguous with end of buffer position
var start = fragments[0].start,
end = fragments[fragLen - 1].start + fragments[fragLen - 1].duration,
bufferEnd = bufferInfo.end,
frag = void 0;
// in case of live playlist we need to ensure that requested position is not located before playlist start
if (levelDetails.live) {
frag = this._ensureFragmentAtLivePoint({ levelDetails: levelDetails, bufferEnd: bufferEnd, start: start, end: end, fragPrevious: fragPrevious, fragments: fragments, fragLen: fragLen });
// if it explicitely returns null don't load any fragment and exit function now
if (frag === null) {
return false;
}
} else {
// VoD playlist: if bufferEnd before start of playlist, load first fragment
if (bufferEnd < start) {
frag = fragments[0];
}
}
if (!frag) {
frag = this._findFragment({ start: start, fragPrevious: fragPrevious, fragLen: fragLen, fragments: fragments, bufferEnd: bufferEnd, end: end, levelDetails: levelDetails });
}
if (frag) {
return this._loadFragmentOrKey({ frag: frag, level: level, levelDetails: levelDetails, pos: pos, bufferEnd: bufferEnd });
}
return true;
}
}, {
key: '_ensureFragmentAtLivePoint',
value: function _ensureFragmentAtLivePoint(_ref2) {
var levelDetails = _ref2.levelDetails,
bufferEnd = _ref2.bufferEnd,
start = _ref2.start,
end = _ref2.end,
fragPrevious = _ref2.fragPrevious,
fragments = _ref2.fragments,
fragLen = _ref2.fragLen;
var config = this.hls.config,
media = this.media;
var frag = void 0;
// check if requested position is within seekable boundaries :
//logger.log(`start/pos/bufEnd/seeking:${start.toFixed(3)}/${pos.toFixed(3)}/${bufferEnd.toFixed(3)}/${this.media.seeking}`);
var maxLatency = config.liveMaxLatencyDuration !== undefined ? config.liveMaxLatencyDuration : config.liveMaxLatencyDurationCount * levelDetails.targetduration;
if (bufferEnd < Math.max(start - config.maxFragLookUpTolerance, end - maxLatency)) {
var liveSyncPosition = this.computeLivePosition(start, levelDetails);
_logger.logger.log('buffer end: ' + bufferEnd.toFixed(3) + ' is located too far from the end of live sliding playlist, reset currentTime to : ' + liveSyncPosition.toFixed(3));
bufferEnd = liveSyncPosition;
if (media && media.readyState && media.duration > liveSyncPosition) {
media.currentTime = liveSyncPosition;
}
}
// if end of buffer greater than live edge, don't load any fragment
// this could happen if live playlist intermittently slides in the past.
// level 1 loaded [182580161,182580167]
// level 1 loaded [182580162,182580169]
// Loading 182580168 of [182580162 ,182580169],level 1 ..
// Loading 182580169 of [182580162 ,182580169],level 1 ..
// level 1 loaded [182580162,182580168] <============= here we should have bufferEnd > end. in that case break to avoid reloading 182580168
// level 1 loaded [182580164,182580171]
//
if (levelDetails.PTSKnown && bufferEnd > end && media && media.readyState) {
return null;
}
if (this.startFragRequested && !levelDetails.PTSKnown) {
/* we are switching level on live playlist, but we don't have any PTS info for that quality level ...
try to load frag matching with next SN.
even if SN are not synchronized between playlists, loading this frag will help us
compute playlist sliding and find the right one after in case it was not the right consecutive one */
if (fragPrevious) {
var targetSN = fragPrevious.sn + 1;
if (targetSN >= levelDetails.startSN && targetSN <= levelDetails.endSN) {
frag = fragments[targetSN - levelDetails.startSN];
_logger.logger.log('live playlist, switching playlist, load frag with next SN: ' + frag.sn);
}
}
if (!frag) {
/* we have no idea about which fragment should be loaded.
so let's load mid fragment. it will help computing playlist sliding and find the right one
*/
frag = fragments[Math.min(fragLen - 1, Math.round(fragLen / 2))];
_logger.logger.log('live playlist, switching playlist, unknown, load middle frag : ' + frag.sn);
}
}
return frag;
}
}, {
key: '_findFragment',
value: function _findFragment(_ref3) {
var start = _ref3.start,
fragPrevious = _ref3.fragPrevious,
fragLen = _ref3.fragLen,
fragments = _ref3.fragments,
bufferEnd = _ref3.bufferEnd,
end = _ref3.end,
levelDetails = _ref3.levelDetails,
holaSeek = _ref3.holaSeek;
var config = this.hls.config;
var frag = void 0,
foundFrag = void 0,
maxFragLookUpTolerance = config.maxFragLookUpTolerance,
media = this.media,
seekFlag = media && media.seeking || holaSeek;
if (bufferEnd < end - (fragments[fragLen - 1].PTSDTSshift || 0) - 0.05) {
if (bufferEnd > end - maxFragLookUpTolerance || seekFlag) {
maxFragLookUpTolerance = 0;
}
foundFrag = _binarySearch2.default.search(fragments, function (candidate) {
// 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}`);
// if we are in seek, the condition will always be false
if (candidate.lastGop - maxFragLookUpTolerance < bufferEnd && candidate.lastGop + maxFragLookUpTolerance > bufferEnd) {
return 1;
}
// if we are in seek, the condition will always be false
if (candidate.firstGop - maxFragLookUpTolerance < bufferEnd && candidate.firstGop + maxFragLookUpTolerance > bufferEnd) {
return 0;
}
if (candidate.start + candidate.duration - candidate.PTSDTSshift - maxFragLookUpTolerance <= bufferEnd) {
return 1;
}
// if maxFragLookUpTolerance will have negative value then don't return -1 for first element
if (candidate.start - candidate.PTSDTSshift - maxFragLookUpTolerance > bufferEnd && candidate.start) {
return candidate.sn > levelDetails.startSN ? -1 : 0;
}
return 0;
});
} else {
// reach end of playlist
foundFrag = fragments[fragLen - 1];
}
if (foundFrag) {
frag = foundFrag;
start = foundFrag.start;
_logger.logger.log('find SN matching with pos:' + bufferEnd + ':' + frag.sn);
if (fragPrevious && frag.sn === fragPrevious.sn) {
if (frag.sn < levelDetails.endSN) {
var deltaPTS = fragPrevious.deltaPTS,
curSNIdx = frag.sn - levelDetails.startSN;
// if there is a significant delta between audio and video, larger than max allowed hole,
// and if previous remuxed fragment did not start with a keyframe. (fragPrevious.dropped)
// let's try to load previous fragment again to get last keyframe
// then we will reload again current fragment (that way we should be able to fill the buffer hole ...)
if (this.loadedmetadata && deltaPTS && deltaPTS > config.maxSeekHole && fragPrevious.dropped && (!media || !_bufferHelper2.default.isBuffered(media, bufferEnd))) {
frag = fragments[curSNIdx - 1];
_logger.logger.warn('SN just loaded, with large PTS gap between audio and video, maybe frag is not starting with a keyframe ? load previous one to try to overcome this');
// decrement previous frag load counter to avoid frag loop loading error when next fragment will get reloaded
fragPrevious.loadCounter--;
} else {
frag = fragments[curSNIdx + 1];
_logger.logger.log('SN just loaded, load next one: ' + frag.sn);
}
} else {
// have we reached end of VOD playlist ?
if (!levelDetails.live) {
// Finalize the media stream
this.hls.trigger(_events2.default.BUFFER_EOS);
// We might be loading the last fragment but actually the media
// is currently processing a seek command and waiting for new data to resume at another point.
// Going to ended state while media is seeking can spawn an infinite buffering broken state.
if (!this.media.seeking) {
this.state = State.ENDED;
}
}
frag = null;
}
}
}
return frag;
}
}, {
key: '_loadFragmentOrKey',
value: function _loadFragmentOrKey(_ref4) {
var frag = _ref4.frag,
level = _ref4.level,
levelDetails = _ref4.levelDetails,
pos = _ref4.pos,
bufferEnd = _ref4.bufferEnd;
var hls = this.hls,
config = hls.config;
//logger.log('loading frag ' + i +',pos/bufEnd:' + pos.toFixed(3) + '/' + bufferEnd.toFixed(3));
if (frag.decryptdata.uri != null && frag.decryptdata.key == null) {
_logger.logger.log('Loading key for ' + frag.sn + ' of [' + levelDetails.startSN + ' ,' + levelDetails.endSN + '],level ' + level);
this.state = State.KEY_LOADING;
hls.trigger(_events2.default.KEY_LOADING, { frag: frag });
} else {
_logger.logger.log('Loading ' + frag.sn + ' of [' + levelDetails.startSN + ' ,' + levelDetails.endSN + '],level ' + level + ', currentTime:' + pos + ',bufferEnd:' + bufferEnd.toFixed(3));
frag.autoLevel = hls.autoLevelEnabled;
if (this.levels.length > 1) {
frag.expectedLen = Math.round(frag.duration * this.levels[level].bitrate / 8);
frag.trequest = performance.now();
}
// ensure that we are not reloading the same fragments in loop ...
if (this.fragLoadIdx !== undefined) {
this.fragLoadIdx++;
} else {
this.fragLoadIdx = 0;
}
if (frag.loadCounter) {
frag.loadCounter++;
var maxThreshold = config.fragLoadingLoopThreshold;
// if this frag has already been loaded 3 times, and if it has been reloaded recently
if (frag.loadCounter > maxThreshold && Math.abs(this.fragLoadIdx - frag.loadIdx) < maxThreshold) {
hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.FRAG_LOOP_LOADING_ERROR, fatal: false, frag: frag });
return false;
}
} else {
frag.loadCounter = 1;
}
frag.loadIdx = this.fragLoadIdx;
this.fragCurrent = frag;
this.fragCurrent.loaded = false;
this.startFragRequested = true;
this.nextLoadPosition = frag.start + frag.duration;
this.fragTimeOffset = frag.start;
// lazy demuxer init, as this could take some time ... do it during frag loading
if (!this.demuxer) {
this.demuxer = new _demuxer2.default(hls, 'main');
}
this.state = State.FRAG_LOADING;
hls.trigger(_events2.default.FRAG_LOADING, { frag: frag });
return true;
}
}
}, {
key: 'getBufferRange',
value: function getBufferRange(position) {
return _binarySearch2.default.search(this.bufferRange, function (range) {
if (position < range.start) {
return -1;
} else if (position > range.end) {
return 1;
}
return 0;
});
}
}, {
key: 'followingBufferRange',
value: function followingBufferRange(range) {
if (range) {
// try to get range of next fragment (500ms after this range)
return this.getBufferRange(range.end + 0.5);
}
return null;
}
}, {
key: '_checkFragmentChanged',
value: function _checkFragmentChanged() {
var currentTime,
video = this.media;
if (video && video.seeking === false) {
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 (currentTime > video.playbackRate * this.lastCurrentTime) {
this.lastCurrentTime = currentTime;
}
}
}
/*
on immediate level switch :
- pause playback if playing
- cancel any pending load request
- and trigger a buffer flush
*/
}, {
key: 'immediateLevelSwitch',
value: function immediateLevelSwitch() {
_logger.logger.log('immediateLevelSwitch');
if (!this.immediateSwitch) {
this.immediateSwitch = true;
this.previouslyPaused = this.media.paused;
this.media.pause();
}
var fragCurrent = this.fragCurrent;
if (fragCurrent && fragCurrent.loader) {
fragCurrent.loader.abort();
}
this.fragCurrent = null;
// increase fragment load Index to avoid frag loop loading error after buffer flush
this.fragLoadIdx += 2 * this.config.fragLoadingLoopThreshold;
this.state = State.PAUSED;
// flush everything
this.hls.trigger(_events2.default.BUFFER_FLUSHING, { startOffset: 0, endOffset: Number.POSITIVE_INFINITY });
}
/*
on immediate level switch end, after new fragment has been buffered :
- nudge video decoder by slightly adjusting video currentTime
- resume the playback if needed
*/
}, {
key: 'immediateLevelSwitchEnd',
value: function immediateLevelSwitchEnd() {
var media = this.media;
if (media && media.buffered.length) {
this.immediateSwitch = false;
if (_bufferHelper2.default.isBuffered(media, media.currentTime)) {
// only nudge if currentTime is buffered
media.currentTime -= 0.0001;
}
if (!this.previouslyPaused) {
media.play();
}
}
}
}, {
key: 'nextLevelSwitch',
value: function nextLevelSwitch() {
/* 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
*/
var media = this.media;
// ensure that media is defined and that metadata are available (to retrieve currentTime)
if (media && media.readyState) {
var fetchdelay = void 0,
currentRange = void 0,
nextRange = void 0;
// increase fragment load Index to avoid frag loop loading error after buffer flush
this.fragLoadIdx += 2 * this.config.fragLoadingLoopThreshold;
currentRange = this.getBufferRange(media.currentTime);
if (currentRange && currentRange.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.state = State.PAUSED;
this.hls.trigger(_events2.default.BUFFER_FLUSHING, { startOffset: 0, endOffset: currentRange.start - 1 });
}
if (!media.paused) {
// add a safety delay of 1s
var nextLevelId = this.hls.nextLoadLevel,
nextLevel = this.levels[nextLevelId],
fragLastKbps = this.fragLastKbps;
if (fragLastKbps && this.fragCurrent) {
fetchdelay = this.fragCurrent.duration * nextLevel.bitrate / (1000 * fragLastKbps) + 1;
} else {
fetchdelay = 0;
}
} else {
fetchdelay = 0;
}
//logger.log('fetchdelay:'+fetchdelay);
// find buffer range that will be reached once new fragment will be fetched
nextRange = this.getBufferRange(media.currentTime + fetchdelay);
if (nextRange) {
// we can flush buffer range following this one without stalling playback
nextRange = this.followingBufferRange(nextRange);
if (nextRange) {
// if we are here, we can also cancel any loading/demuxing in progress, as they are useless
var fragCurrent = this.fragCurrent;
if (fragCurrent && fragCurrent.loader) {
fragCurrent.loader.abort();
}
this.fragCurrent = null;
// flush position is the start position of this new buffer
this.state = State.PAUSED;
this.hls.trigger(_events2.default.BUFFER_FLUSHING, { startOffset: nextRange.start, endOffset: Number.POSITIVE_INFINITY });
}
}
}
}
}, {
key: 'onMediaAttached',
value: function onMediaAttached(data) {
var media = this.media = data.media;
this.onvseeking = this.onMediaSeeking.bind(this);
this.onvseeked = this.onMediaSeeked.bind(this);
this.onvended = this.onMediaEnded.bind(this);
media.addEventListener('seeking', this.onvseeking);
media.addEventListener('seeked', this.onvseeked);
media.addEventListener('ended', this.onvended);
if (this.demuxer) {
this.demuxer.destroy();
this.demuxer = new _demuxer2.default(this.hls);
this.fragParsing = null;
}
if (this.levels && this.config.autoStartLoad) {
this.hls.startLoad();
}
}
}, {
key: 'onMediaDetaching',
value: function onMediaDetaching() {
var media = this.media;
if (media && media.ended || this.state === State.ENDED) {
_logger.logger.log('MSE detaching and video ended, reset startPosition');
this.startPosition = this.lastCurrentTime = 0;
}
// reset fragment loading counter on MSE detaching to avoid reporting FRAG_LOOP_LOADING_ERROR after error recovery
var levels = this.levels;
if (levels) {
// reset fragment load counter
levels.forEach(function (level) {
if (level.details) {
level.details.fragments.forEach(function (fragment) {
fragment.loadCounter = undefined;
});
}
});
}
// remove video listeners
if (media) {
media.removeEventListener('seeking', this.onvseeking);
media.removeEventListener('seeked', this.onvseeked);
media.removeEventListener('ended', this.onvended);
this.onvseeking = this.onvseeked = this.onvended = null;
}
this.media = null;
this.loadedmetadata = false;
this.stopLoad();
this.fragParsing = null;
}
}, {
key: 'onMediaSeeking',
value: function onMediaSeeking() {
var currentTime = this.media.currentTime;
_logger.logger.log('media seeking to ' + currentTime);
var fragCurrent = this.fragCurrent;
if (this.state === State.FRAG_LOADING) {
// check if currently loaded fragment is inside buffer.
//if outside, cancel fragment loading, otherwise do nothing
if (_bufferHelper2.default.bufferInfo(this.media, currentTime, 0).len === 0) {
_logger.logger.log('seeking outside of buffer while fragment load in progress, cancel fragment load');
if (fragCurrent) {
if (fragCurrent.loader) {
fragCurrent.loader.abort();
}
this.fragCurrent = null;
}
this.fragPrevious = null;
// switch to IDLE state to load new fragment
this.state = State.IDLE;
}
} else if (this.state === State.ENDED) {
// switch to IDLE state to check for potential new fragment
this.state = State.IDLE;
} else if (this.state === State.PARSING && fragCurrent && !fragCurrent.loaded) {
_logger.logger.log('mediaController: no final chunk, switch back to IDLE state');
this.state = State.IDLE;
}
if (this.media) {
this.lastCurrentTime = currentTime;
}
// avoid reporting fragment loop loading error in case user is seeking several times on same position
if (this.fragLoadIdx !== undefined) {
this.fragLoadIdx += 2 * this.config.fragLoadingLoopThreshold;
}
// in case seeking occurs although no media buffered, adjust startPosition and nextLoadPosition to seek target
if (!this.loadedmetadata) {
this.nextLoadPosition = this.startPosition = currentTime;
if (this.fragCurrent && (this.fragCurrent.start > currentTime || this.fragCurrent.start + this.fragCurrent.duration < currentTime)) {
this.seekDuringFirst = true;
}
}
// tick to speed up processing
this.tick();
}
}, {
key: 'onMediaSeeked',
value: function onMediaSeeked() {
_logger.logger.log('media seeked to ' + this.media.currentTime);
// tick to speed up FRAGMENT_PLAYING triggering
this.tick();
}
}, {
key: 'onMediaEnded',
value: function onMediaEnded() {
_logger.logger.log('media ended');
// reset startPosition and lastCurrentTime to restart playback @ stream beginning
this.startPosition = this.lastCurrentTime = 0;
}
}, {
key: 'onManifestLoading',
value: function onManifestLoading() {
// reset buffer on manifest loading
_logger.logger.log('trigger BUFFER_RESET');
this.hls.trigger(_events2.default.BUFFER_RESET);
this.bufferRange = [];
this.stalled = false;
this.startPosition = this.lastCurrentTime = 0;
this.fragParsing = null;
delete this.fragPreviousSaved;
}
}, {
key: 'onManifestParsed',
value: function onManifestParsed(data) {
var aac = false,
heaac = false,
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;
if (this.audioCodecSwitch) {
_logger.logger.log('both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC');
}
this.levels = data.levels;
this.startLevelLoaded = false;
this.startFragRequested = false;
if (this.demuxer) {
this.demuxer.destroy();
this.demuxer = new _demuxer2.default(this.hls);
this.fragParsing = null;
}
if (this.config.autoStartLoad) {
this.hls.startLoad();
}
}
}, {
key: 'onLevelLoaded',
value: function onLevelLoaded(data) {
var newDetails = data.details,
newLevelId = data.level,
curLevel = this.levels[newLevelId],
duration = newDetails.totalduration,
sliding = 0,
lastDetails = this.levelLastLoaded !== undefined && this.levels[this.levelLastLoaded] && this.levels[this.levelLastLoaded].details;
_logger.logger.log('level ' + newLevelId + ' loaded [' + newDetails.startSN + ',' + newDetails.endSN + '],duration:' + duration);
if (newDetails.live) {
var curDetails = curLevel.details;
if (lastDetails && _levelHelper2.default.canMerge(lastDetails, newDetails)) {
curDetails = lastDetails;
} else if (curDetails && !_levelHelper2.default.canMerge(curDetails, newDetails)) {
curDetails = undefined;
this.hls.clearLevelDetails();
}
if (curDetails) {
// we already have details for that level, merge them
_levelHelper2.default.mergeDetails(curDetails, newDetails);
sliding = newDetails.fragments[0].start;
if (newDetails.PTSKnown) {
_logger.logger.log('live playlist sliding:' + sliding.toFixed(3));
} else {
_logger.logger.log('live playlist - outdated PTS, unknown sliding');
}
} else {
newDetails.PTSKnown = false;
_logger.logger.log('live playlist - first load, unknown sliding');
}
} else {
newDetails.PTSKnown = false;
if (lastDetails) {
_levelHelper2.default.mergeDetails(lastDetails, newDetails);
}
}
// override level info
this.levelLastLoaded = newLevelId;
curLevel.details = newDetails;
this.hls.trigger(_events2.default.LEVEL_UPDATED, { details: newDetails, level: newLevelId });
// compute start position
if (this.startFragRequested === false) {
// if live playlist, set start position to be fragment N-this.config.liveSyncDurationCount (usually 3)
if (newDetails.live) {
this.startPosition = this.computeLivePosition(sliding, newDetails);
_logger.logger.log('configure startPosition to ' + this.startPosition);
}
this.nextLoadPosition = this.startPosition;
}
// only switch batck to IDLE state if we were waiting for level to start downloading a new fragment
if (this.state === State.WAITING_LEVEL) {
this.waitLiveLevel = false;
this.state = State.IDLE;
}
//trigger handler right now
this.tick();
}
}, {
key: 'onKeyLoaded',
value: function onKeyLoaded() {
if (this.state === State.KEY_LOADING) {
this.state = State.IDLE;
this.tick();
}
}
}, {
key: 'onFragChunkLoaded',
value: function onFragChunkLoaded(data) {
var fragCurrent = this.fragCurrent;
if ((this.state === State.FRAG_LOADING || this.state === State.PARSING) && fragCurrent && data.frag.level === fragCurrent.level && data.frag.sn === fragCurrent.sn) {
_logger.logger.log('Loaded chunk ' + data.payload.byteLength + ' of frag ' + fragCurrent.sn + ' of level ' + fragCurrent.level);
this.state = State.PARSING;
// transmux the MPEG-TS data to ISO-BMFF segments
this.stats = data.stats;
var level = fragCurrent.level,
fragLevel = this.levels[level],
details = fragLevel.details,
duration = details.totalduration,
start = this.fragTimeOffset,
sn = fragCurrent.sn,
audioCodec = this.config.defaultAudioCodec || fragLevel.audioCodec;
if (this.audioCodecSwap) {
_logger.logger.log('swapping playlist audio codec');
if (audioCodec === undefined) {
audioCodec = this.lastAudioCodec;
}
if (audioCodec) {
if (audioCodec.indexOf('mp4a.40.5') !== -1) {
audioCodec = 'mp4a.40.2';
} else {
audioCodec = 'mp4a.40.5';
}
}
}
_logger.logger.log('Demuxing ' + sn + ' of [' + details.startSN + ' ,' + details.endSN + '],level ' + level + ', cc ' + fragCurrent.cc);
var demuxer = this.demuxer;
if (demuxer) {
// time Offset is accurate if level PTS is known, or if playlist is not sliding (not live) and if media is not seeking (this is to overcome potential timestamp drifts between playlists and fragments)
var media = this.media;
var mediaSeeking = media && media.seeking;
var accurateTimeOffset = !mediaSeeking && (details.PTSKnown || !details.live);
demuxer.push(data.payload, audioCodec, fragLevel.videoCodec, start, fragCurrent.cc, level, sn, duration, fragCurrent.decryptdata, accurateTimeOffset, details.endSN);
}
if (data.payload.final) {
fragCurrent.loaded = true;
}
}
}
}, {
key: 'onFragLoaded',
value: function onFragLoaded() {
_logger.logger.log('Loaded ' + this.fragCurrent.sn + ' of level ' + this.fragCurrent.level);
this.fragLoadError = 0;
}
}, {
key: 'onFragParsingInitSegment',
value: function onFragParsingInitSegment(data) {
if (this.state === State.PARSING) {
var tracks = data.tracks,
trackName,
track;
// include levelCodec in audio and video tracks
track = tracks.audio;
if (track) {
var audioCodec = this.levels[this.level].audioCodec,
ua = navigator.userAgent.toLowerCase();
if (audioCodec && this.audioCodecSwap) {
_logger.logger.log('swapping playlist audio codec');
if (audioCodec.indexOf('mp4a.40.5') !== -1) {
audioCodec = 'mp4a.40.2';
} else {
audioCodec = 'mp4a.40.5';
}
}
// in case AAC and HE-AAC audio codecs are signalled in manifest
// force HE-AAC , as it seems that most browsers prefers that way,
// except for mono streams OR on FF
// these conditions might need to be reviewed ...
if (this.audioCodecSwitch) {
// don't force HE-AAC if mono stream
if (track.metadata.channelCount !== 1 &&
// don't force HE-AAC if firefox
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 && track.container !== 'audio/mpeg') {
audioCodec = 'mp4a.40.2';
_logger.logger.log('Android: force audio codec to ' + audioCodec);
}
track.levelCodec = audioCodec;
}
track = tracks.video;
if (track) {
track.levelCodec = this.levels[this.level].videoCodec;
}
// if remuxer specify that a unique track needs to generated,
// let's merge all tracks together
if (data.unique) {
var mergedTrack = {
codec: '',
levelCodec: ''
};
for (trackName in data.tracks) {
track = tracks[trackName];
mergedTrack.container = track.container;
if (mergedTrack.codec) {
mergedTrack.codec += ',';
mergedTrack.levelCodec += ',';
}
if (track.codec) {
mergedTrack.codec += track.codec;
}
if (track.levelCodec) {
mergedTrack.levelCodec += track.levelCodec;
}
}
tracks = { audiovideo: mergedTrack };
}
this.hls.trigger(_events2.default.BUFFER_CODECS, tracks);
if (this.state !== State.STOPPED) {
// loop through tracks that are going to be provided to bufferController
for (trackName in tracks) {
track = tracks[trackName];
var initSegment = track.initSegment;
_logger.logger.log('track:' + trackName + ',container:' + track.container + ',codecs[level/parsed]=[' + track.levelCodec + '/' + track.codec + ']' + (initSegment ? ',init:' + initSegment.length : ''));
if (initSegment) {
this.hls.trigger(_events2.default.BUFFER_APPENDING, { type: trackName, data: initSegment });
}
}
}
//trigger handler right now
this.tick();
}
}
}, {
key: 'onFragParsingData',
value: function onFragParsingData(data) {
if (this.state === State.PARSING || this.fragParsing) {
this.tparse2 = Date.now();
var frag = this.fragCurrent || this.fragParsing;
_logger.logger.log('parsed ' + data.type + ',PTS:[' + data.startPTS.toFixed(3) + ',' + data.endPTS.toFixed(3) + '],DTS:[' + data.startDTS.toFixed(3) + '/' + data.endDTS.toFixed(3) + '],nb:' + data.nb + ',dropped:' + (data.dropped || 0) + ',deltaPTS:' + (data.deltaPTS || 0));
var hls = this.hls;
// has remuxer dropped video frames located before first keyframe ?
if (data.type === 'video') {
frag.dropped = data.dropped;
if (data.deltaPTS) {
if (isNaN(frag.deltaPTS)) {
frag.deltaPTS = data.deltaPTS;
} else {
frag.deltaPTS = Math.max(data.deltaPTS, frag.deltaPTS);
}
}
}
[data.data1, data.data2].forEach(function (buffer) {
if (buffer) {
hls.trigger(_events2.default.BUFFER_APPENDING, { type: data.type, data: buffer });
}
});
//trigger handler right now
this.tick();
} else {
_logger.logger.warn('not in PARSING state but ' + this.state + ', ignoring FRAG_PARSING_DATA event');
}
}
}, {
key: 'onFragParsed',
value: function onFragParsed(data) {
if (this.state === State.PARSING) {
var frag = this.fragCurrent,
level = this.levels[frag.level];
this.stats.tparsed = performance.now();
this.state = State.PARSED;
_logger.logger.log('parsed frag sn:' + frag.sn + ',PTS:[' + (data.startPTS ? data.startPTS.toFixed(3) : 'none') + ',' + (data.endPTS ? data.endPTS.toFixed(3) : 'none') + '],PTSDTSshift:' + (data.PTSDTSshift ? data.PTSDTSshift.toFixed(3) : 'none') + ',lastGopPTS:' + (data.lastGopPTS ? data.lastGopPTS.toFixed(3) : 'none'));
if (data.startPTS !== undefined && data.endPTS !== undefined) {
var drift = _levelHelper2.default.updateFragPTS(level.details, frag.sn, data.startPTS, data.endPTS, data.PTSDTSshift, data.lastGopPTS);
this.hls.trigger(_events2.default.LEVEL_PTS_UPDATED, { details: level.details, level: frag.level, drift: drift });
} else {
// forse reload of prev fragment if video samples not found
frag.dropped = 1;
frag.deltaPTS = this.config.maxSeekHole + 1;
}
this.hls.trigger(_events2.default.FRAG_APPENDING);
}
}
}, {
key: 'onFragAppended',
value: function onFragAppended() {
var _this2 = this;
//trigger handler right now
if (this.state === State.PARSED) {
this._checkBuffer(true);
var frag = this.fragCurrent;
if (frag) {
_logger.logger.log('media buffered : ' + this.timeRangesToString(this.media.buffered));
// filter potentially evicted bufferRange. this is to avoid memleak on live streams
var bufferRange = this.bufferRange.filter(function (range) {
return _bufferHelper2.default.isBuffered(_this2.media, (range.start + range.end) / 2);
});
// push new range
bufferRange.push({ type: frag.type, start: frag.startPTS, end: frag.endPTS, frag: frag });
// sort, as we use BinarySearch for lookup in getBufferRange ...
this.bufferRange = bufferRange.sort(function (a, b) {
return a.start - b.start;
});
this.fragPrevious = frag;
var stats = this.stats;
stats.tbuffered = performance.now();
this.fragLastKbps = Math.round(8 * stats.length / (stats.tbuffered - stats.tfirst));
this.hls.trigger(_events2.default.FRAG_BUFFERED, { stats: stats, frag: frag });
this.state = State.IDLE;
}
this.tick();
} else {
_logger.logger.warn('not in PARSED state but ' + this.state);
}
}
}, {
key: 'onError',
value: function onError(data) {
switch (data.details) {
case _errors.ErrorDetails.FRAG_LOAD_ERROR:
case _errors.ErrorDetails.FRAG_LOAD_TIMEOUT:
if (!data.fatal) {
var loadError = (this.fragLoadError || 0) + 1;
if (loadError <= this.config.fragLoadingMaxRetry) {
this.fragLoadError = loadError;
// reset load counter to avoid frag loop loading error
data.frag.loadCounter = 0;
// exponential backoff capped to 64s
var delay = Math.min(Math.pow(2, loadError - 1) * this.config.fragLoadingRetryDelay, 64000);
_logger.logger.warn('mediaController: frag loading failed, retry in ' + delay + ' ms');
this.retryDate = performance.now() + delay;
// retry loading state
this.state = State.FRAG_LOADING_WAITING_RETRY;
} else {
_logger.logger.error('mediaController: ' + data.details + ' reaches max retry, redispatch as fatal ...');
// redispatch same error but with fatal set to true
data.fatal = true;
this.hls.trigger(_events2.default.ERROR, data);
this.state = State.ERROR;
}
}
break;
case _errors.ErrorDetails.FRAG_LOOP_LOADING_ERROR:
case _errors.ErrorDetails.LEVEL_LOAD_ERROR:
case _errors.ErrorDetails.LEVEL_LOAD_TIMEOUT:
case _errors.ErrorDetails.KEY_LOAD_ERROR:
case _errors.ErrorDetails.KEY_LOAD_TIMEOUT:
// when in ERROR state, don't switch back to IDLE state in case a non-fatal error is received
if (this.state !== State.ERROR) {
// if fatal error, stop processing, otherwise move to IDLE to retry loading
this.state = data.fatal ? State.ERROR : State.IDLE;
_logger.logger.warn('mediaController: ' + data.details + ' while loading frag,switch to ' + this.state + ' state ...');
}
break;
case _errors.ErrorDetails.BUFFER_FULL_ERROR:
// trigger a smooth level switch to empty buffers
// also reduce max buffer length as it might be too high. we do this to avoid loop flushing ...
this.config.maxMaxBufferLength /= 2;
_logger.logger.warn('reduce max buffer length to ' + this.config.maxMaxBufferLength + 's and trigger a nextLevelSwitch to flush old buffer and fix QuotaExceededError');
this.nextLevelSwitch();
break;
default:
break;
}
}
}, {
key: '_checkBuffer',
value: function _checkBuffer(appended) {
var media = this.media;
if (media && media.readyState) {
var currentTime;
currentTime = media.currentTime;
// adjust currentTime to start position on loaded metadata
if (!this.loadedmetadata && media.buffered.length && appended) {
if (this.seekDuringFirst) {
this.seekDuringFirst = null;
return;
}
this.loadedmetadata = true;
// 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
var startPosition = this.startPosition,
startPositionBuffered = _bufferHelper2.default.isBuffered(media, startPosition);
if (currentTime !== this.startPosition || !startPositionBuffered) {
_logger.logger.log('target start position:' + startPosition);
// if startPosition not buffered, let's seek to buffered.start(0)
if (!startPositionBuffered) {
// XXX pavelki: fix case when we asked to seek during the first
// segment loading
for (var i = 0; i < media.buffered.length; i++) {
if (media.buffered.start(i) > startPosition) {
startPosition = media.buffered.start(i);
break;
}
}
if (_browser2.default.isSafari()) {
startPosition += 0.001;
}
_logger.logger.log('target start position not buffered, seek to buffered.start(' + i + ') ' + startPosition);
}
_logger.logger.log('adjust currentTime from ' + currentTime + ' to ' + startPosition);
media.currentTime = startPosition;
}
} else {
var hls = this.hls;
var bufferInfo = _bufferHelper2.default.bufferInfo(media, currentTime, 0),
expectedPlaying = !(media.paused || // not playing when media is paused
media.ended || // not playing when media is ended
media.buffered.length === 0),
// not playing if nothing buffered
jumpThreshold = 0.5,
// tolerance needed as some browsers stalls playback before reaching buffered range end
playheadMoving = currentTime !== this.lastCurrentTime,
config = this.config;
if (playheadMoving) {
// played moving, but was previously stalled => now not stuck anymore
if (this.stallReported) {
var dur = Math.round(performance.now() - this.stalled);
_logger.logger.warn('playback not stuck anymore @' + currentTime + ', after ' + dur + 'ms');
hls.trigger(_events2.default.BUF_STATISTICS, { bufNotStalled: { ts: currentTime, dur: dur, lowBuf: this.stallLowBuf } });
this.stallLowBuf = this.stallReported = false;
}
this.stalled = undefined;
this.nudgeRetry = 0;
} else {
// playhead not moving
if (expectedPlaying) {
// playhead not moving BUT media expected to play
var tnow = performance.now();
if (!this.stalled) {
// stall just detected, store current time
this.stalled = tnow;
this.stallLowBuf = this.stallReported = false;
} else {
// playback already stalled, check stalling duration
// if stalling for more than a given threshold, let's try to recover
var stalledDuration = tnow - this.stalled;
var bufferLen = bufferInfo.len;
var nudgeRetry = this.nudgeRetry || 0;
// have we reached stall deadline ?
if (bufferLen <= jumpThreshold && stalledDuration > config.lowBufferWatchdogPeriod * 1000) {
// report stalled error once
if (!this.stallReported) {
this.stallReported = true;
this.stallLowBuf = true;
_logger.logger.warn('playback stalling in low buffer @' + currentTime);
hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.BUFFER_STALLED_ERROR, fatal: false, buffer: bufferLen });
hls.trigger(_events2.default.BUF_STATISTICS, { bufStalledLow: { ts: currentTime } });
}
// if buffer len is below threshold, try to jump to start of next buffer range if close
// no buffer available @ currentTime, check if next buffer is close (within a config.maxSeekHole second range)
var nextBufferStart = bufferInfo.nextStart,
delta = nextBufferStart - currentTime;
if (nextBufferStart && delta < config.maxSeekHole && delta > 0) {
this.nudgeRetry = ++nudgeRetry;
var nudgeOffset = nudgeRetry * config.nudgeOffset;
// next buffer is close ! adjust currentTime to nextBufferStart
// this will ensure effective video decoding
_logger.logger.log('adjust currentTime from ' + media.currentTime + ' to next buffered @ ' + nextBufferStart + ' + nudge ' + nudgeOffset);
media.currentTime = nextBufferStart + nudgeOffset;
// reset stalled so to rearm watchdog timer
this.stalled = undefined;
hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.BUFFER_SEEK_OVER_HOLE, fatal: false, hole: nextBufferStart + nudgeOffset - currentTime });
hls.trigger(_events2.default.BUF_STATISTICS, { bufSeekOverHole: { ts: currentTime } });
}
} else if (bufferLen > jumpThreshold && stalledDuration > config.highBufferWatchdogPeriod * 1000) {
if (this.stallReported && this.stallLowBuf) {
// reset stalled so to rearm watchdog timer
this.stalled = undefined;
} else {
// report stalled error once
if (!this.stallReported) {
this.stallReported = true;
_logger.logger.warn('playback stalling in high buffer @' + currentTime);
hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.BUFFER_STALLED_ERROR, fatal: false, buffer: bufferLen });
hls.trigger(_events2.default.BUF_STATISTICS, { bufStalledHigh: { ts: currentTime } });
}
// reset stalled so to rearm watchdog timer
this.stalled = undefined;
this.nudgeRetry = ++nudgeRetry;
if (nudgeRetry < config.nudgeMaxRetry) {
var _currentTime = media.currentTime;
var targetTime = _currentTime + nudgeRetry * config.nudgeOffset;
_logger.logger.log('adjust currentTime from ' + _currentTime + ' to ' + targetTime);
// playback stalled in buffered area ... let's nudge currentTime to try to overcome this
media.currentTime = targetTime;
hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.BUFFER_NUDGE_ON_STALL, fatal: false });
hls.trigger(_events2.default.BUF_STATISTICS, { bufNudge: { ts: _currentTime } });
} else {
_logger.logger.error('still stuck in high buffer @' + currentTime + ' after ' + config.nudgeMaxRetry + ', raise fatal error');
hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.BUFFER_STALLED_ERROR, fatal: true });
}
}
}
}
}
}
}
}
}
}, {
key: 'onFragLoadEmergencyAborted',
value: function onFragLoadEmergencyAborted() {
this.state = State.IDLE;
this.tick();
}
}, {
key: 'onBufferFlushed',
value: function onBufferFlushed() {
var _this3 = this;
// after successful buffer flushing, filter flushed fragments from bufferRange
this.bufferRange = this.bufferRange.filter(function (range) {
return _bufferHelper2.default.isBuffered(_this3.media, (range.start + range.end) / 2);
});
// handle end of immediate switching if needed
if (this.immediateSwitch) {
this.immediateLevelSwitchEnd();
}
// move to IDLE once flush complete. this should trigger new fragment loading
this.state = State.IDLE;
// reset reference to frag
this.fragPrevious = null;
}
}, {
key: 'onLevelPtsUpdated',
value: function onLevelPtsUpdated(lu) {
if (!this.levels || this.levels[lu.level].details.live) {
return;
}
for (var level = 0; level < this.levels.length; level++) {
if (level !== lu.level && this.levels[level].details) {
_levelHelper2.default.mergeDetails(this.levels[lu.level].details, this.levels[level].details);
}
}
}
}, {
key: 'swapAudioCodec',
value: function swapAudioCodec() {
this.audioCodecSwap = !this.audioCodecSwap;
}
}, {
key: 'timeRangesToString',
value: function timeRangesToString(r) {
if (!r) {
return '[]';
}
var log = '',
len = r.length;
for (var i = 0; i < len; i++) {
log += '[' + r.start(i) + ',' + r.end(i) + ']';
}
return log;
}
}, {
key: 'computeLivePosition',
value: function computeLivePosition(sliding, levelDetails) {
var targetLatency = this.config.liveSyncDuration !== undefined ? this.config.liveSyncDuration : this.config.liveSyncDurationCount * levelDetails.targetduration;
return sliding + Math.max(0, levelDetails.totalduration - targetLatency);
}
}, {
key: 'state',
set: function set(nextState) {
if (this.state !== nextState) {
var previousState = this.state;
this._state = nextState;
_logger.logger.log('engine state transition from ' + previousState + ' to ' + nextState);
if (nextState === 'IDLE') {
var media = this.media || {};
_logger.logger.log('media ' + media + ' ct=' + media.currentTime + ' dur=' + media.duration + ' buf=' + this.timeRangesToString(media.buffered) + ' err=' + media.error);
}
this.hls.trigger(_events2.default.STREAM_STATE_TRANSITION, { previousState: previousState, nextState: nextState });
}
},
get: function get() {
return this._state;
}
}, {
key: 'currentLevel',
get: function get() {
if (this.media) {
var range = this.getBufferRange(this.media.currentTime);
if (range) {
return range.frag.level;
}
}
return -1;
}
}, {
key: 'nextBufferRange',
get: function get() {
if (this.media) {
// first get end range of current fragment
return this.followingBufferRange(this.getBufferRange(this.media.currentTime));
} else {
return null;
}
}
}, {
key: 'nextLevel',
get: function get() {
var range = this.nextBufferRange;
if (range) {
return range.frag.level;
} else {
return -1;
}
}
}]);
return StreamController;
}(_eventHandler2.default);
exports.default = StreamController;
},{"../demux/demuxer":16,"../errors":20,"../event-handler":21,"../events":22,"../helper/buffer-helper":24,"../helper/level-helper":25,"../utils/binary-search":34,"../utils/browser":35,"../utils/logger":38}],8:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
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 _events = require('../events');
var _events2 = _interopRequireDefault(_events);
var _eventHandler = require('../event-handler');
var _eventHandler2 = _interopRequireDefault(_eventHandler);
var _cea608Parser = require('../utils/cea-608-parser');
var _cea608Parser2 = _interopRequireDefault(_cea608Parser);
var _cues = require('../utils/cues');
var _cues2 = _interopRequireDefault(_cues);
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; } /*
* Timeline Controller
*/
var TimelineController = function (_EventHandler) {
_inherits(TimelineController, _EventHandler);
function TimelineController(hls) {
_classCallCheck(this, TimelineController);
var _this = _possibleConstructorReturn(this, (TimelineController.__proto__ || Object.getPrototypeOf(TimelineController)).call(this, hls, _events2.default.MEDIA_ATTACHING, _events2.default.MEDIA_DETACHING, _events2.default.FRAG_PARSING_USERDATA, _events2.default.MANIFEST_LOADING, _events2.default.FRAG_LOADED, _events2.default.LEVEL_SWITCH));
_this.hls = hls;
_this.config = hls.config;
_this.enabled = true;
if (_this.config.enableCEA708Captions) {
var self = _this;
var channel1 = {
'newCue': function newCue(startTime, endTime, screen) {
if (!self.textTrack1) {
self.textTrack1 = self.createTextTrack('captions', 'Unknown CC1', 'en');
// self.textTrack1.mode = 'showing';
}
_cues2.default.newCue(self.textTrack1, startTime, endTime, screen);
}
};
var channel2 = {
'newCue': function newCue(startTime, endTime, screen) {
if (!self.textTrack2) {
self.textTrack2 = self.createTextTrack('captions', 'Unknown CC2', 'es');
}
_cues2.default.newCue(self.textTrack2, startTime, endTime, screen);
}
};
_this.cea608Parser = new _cea608Parser2.default(0, channel1, channel2);
}
return _this;
}
_createClass(TimelineController, [{
key: 'clearCurrentCues',
value: function clearCurrentCues(track, pts) {
if (!track || !track.cues) {
return;
}
for (var i = track.cues.length - 1; track.cues[i].startTime >= pts && i > -1; i--) {
track.removeCue(track.cues[i]);
}
}
}, {
key: 'createTextTrack',
value: function createTextTrack(kind, label, lang) {
if (this.media) {
return this.media.addTextTrack(kind, label, lang);
}
}
}, {
key: 'destroy',
value: function destroy() {
_eventHandler2.default.prototype.destroy.call(this);
}
}, {
key: 'onMediaAttaching',
value: function onMediaAttaching(data) {
this.media = data.media;
}
}, {
key: 'onMediaDetaching',
value: function onMediaDetaching() {}
}, {
key: 'onManifestLoading',
value: function onManifestLoading() {
this.lastPts = Number.NEGATIVE_INFINITY;
}
}, {
key: 'onLevelSwitch',
value: function onLevelSwitch() {
if (this.hls.currentLevel.closedCaptions === 'NONE') {
this.enabled = false;
} else {
this.enabled = true;
}
}
}, {
key: 'onFragLoaded',
value: function onFragLoaded(data) {
var pts = data.frag.start;
// if this is a frag for a previously loaded timerange, remove all captions
// TODO: consider just removing captions for the timerange
if (pts < this.lastPts) {
this.clearCurrentCues(this.textTrack1, pts);
this.clearCurrentCues(this.textTrack2, pts);
}
this.lastPts = pts;
}
}, {
key: 'onFragParsingUserdata',
value: function onFragParsingUserdata(data) {
// push all of the CEA-708 messages into the interpreter
// immediately. It will create the proper timestamps based on our PTS value
if (this.enabled) {
for (var i = 0; i < data.samples.length; i++) {
var ccdatas = this.extractCea608Data(data.samples[i].bytes);
this.cea608Parser.addData(data.samples[i].pts, ccdatas);
}
}
}
}, {
key: 'extractCea608Data',
value: function extractCea608Data(byteArray) {
var count = byteArray[0] & 31;
var position = 2;
var tmpByte, ccbyte1, ccbyte2, ccValid, ccType;
var actualCCBytes = [];
for (var j = 0; j < count; j++) {
tmpByte = byteArray[position++];
ccbyte1 = 0x7F & byteArray[position++];
ccbyte2 = 0x7F & byteArray[position++];
ccValid = (4 & tmpByte) === 0 ? false : true;
ccType = 3 & tmpByte;
if (ccbyte1 === 0 && ccbyte2 === 0) {
continue;
}
if (ccValid) {
if (ccType === 0) // || ccType === 1
{
actualCCBytes.push(ccbyte1);
actualCCBytes.push(ccbyte2);
}
}
}
return actualCCBytes;
}
}]);
return TimelineController;
}(_eventHandler2.default);
exports.default = TimelineController;
},{"../event-handler":21,"../events":22,"../utils/cea-608-parser":36,"../utils/cues":37}],9:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/*
*
* This file contains an adaptation of the AES decryption algorithm
* from the Standford Javascript Cryptography Library. That work is
* covered by the following copyright and permissions notice:
*
* Copyright 2009-2010 Emily Stark, Mike Hamburg, Dan Boneh.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation
* are those of the authors and should not be interpreted as representing
* official policies, either expressed or implied, of the authors.
*/
var AES = function () {
/**
* Schedule out an AES key for both encryption and decryption. This
* is a low-level class. Use a cipher mode to do bulk encryption.
*
* @constructor
* @param key {Array} The key as an array of 4, 6 or 8 words.
*/
function AES(key) {
_classCallCheck(this, AES);
/**
* The expanded S-box and inverse S-box tables. These will be computed
* on the client so that we don't have to send them down the wire.
*
* There are two tables, _tables[0] is for encryption and
* _tables[1] is for decryption.
*
* The first 4 sub-tables are the expanded S-box with MixColumns. The
* last (_tables[01][4]) is the S-box itself.
*
* @private
*/
this._tables = [[[], [], [], [], []], [[], [], [], [], []]];
this._precompute();
var i,
j,
tmp,
encKey,
decKey,
sbox = this._tables[0][4],
decTable = this._tables[1],
keyLen = key.length,
rcon = 1;
if (keyLen !== 4 && keyLen !== 6 && keyLen !== 8) {
throw new Error('Invalid aes key size=' + keyLen);
}
encKey = key.slice(0);
decKey = [];
this._key = [encKey, decKey];
// schedule encryption keys
for (i = keyLen; i < 4 * keyLen + 28; i++) {
tmp = encKey[i - 1];
// apply sbox
if (i % keyLen === 0 || keyLen === 8 && i % keyLen === 4) {
tmp = sbox[tmp >>> 24] << 24 ^ sbox[tmp >> 16 & 255] << 16 ^ sbox[tmp >> 8 & 255] << 8 ^ sbox[tmp & 255];
// shift rows and add rcon
if (i % keyLen === 0) {
tmp = tmp << 8 ^ tmp >>> 24 ^ rcon << 24;
rcon = rcon << 1 ^ (rcon >> 7) * 283;
}
}
encKey[i] = encKey[i - keyLen] ^ tmp;
}
// schedule decryption keys
for (j = 0; i; j++, i--) {
tmp = encKey[j & 3 ? i : i - 4];
if (i <= 4 || j < 4) {
decKey[j] = tmp;
} else {
decKey[j] = decTable[0][sbox[tmp >>> 24]] ^ decTable[1][sbox[tmp >> 16 & 255]] ^ decTable[2][sbox[tmp >> 8 & 255]] ^ decTable[3][sbox[tmp & 255]];
}
}
}
/**
* Expand the S-box tables.
*
* @private
*/
_createClass(AES, [{
key: '_precompute',
value: function _precompute() {
var encTable = this._tables[0],
decTable = this._tables[1],
sbox = encTable[4],
sboxInv = decTable[4],
i,
x,
xInv,
d = [],
th = [],
x2,
x4,
x8,
s,
tEnc,
tDec;
// Compute double and third tables
for (i = 0; i < 256; i++) {
th[(d[i] = i << 1 ^ (i >> 7) * 283) ^ i] = i;
}
for (x = xInv = 0; !sbox[x]; x ^= x2 || 1, xInv = th[xInv] || 1) {
// Compute sbox
s = xInv ^ xInv << 1 ^ xInv << 2 ^ xInv << 3 ^ xInv << 4;
s = s >> 8 ^ s & 255 ^ 99;
sbox[x] = s;
sboxInv[s] = x;
// Compute MixColumns
x8 = d[x4 = d[x2 = d[x]]];
tDec = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100;
tEnc = d[s] * 0x101 ^ s * 0x1010100;
for (i = 0; i < 4; i++) {
encTable[i][x] = tEnc = tEnc << 24 ^ tEnc >>> 8;
decTable[i][s] = tDec = tDec << 24 ^ tDec >>> 8;
}
}
// Compactify. Considerable speedup on Firefox.
for (i = 0; i < 5; i++) {
encTable[i] = encTable[i].slice(0);
decTable[i] = decTable[i].slice(0);
}
}
/**
* Decrypt 16 bytes, specified as four 32-bit words.
* @param encrypted0 {number} the first word to decrypt
* @param encrypted1 {number} the second word to decrypt
* @param encrypted2 {number} the third word to decrypt
* @param encrypted3 {number} the fourth word to decrypt
* @param out {Int32Array} the array to write the decrypted words
* into
* @param offset {number} the offset into the output array to start
* writing results
* @return {Array} The plaintext.
*/
}, {
key: 'decrypt',
value: function decrypt(encrypted0, encrypted1, encrypted2, encrypted3, out, offset) {
var key = this._key[1],
// state variables a,b,c,d are loaded with pre-whitened data
a = encrypted0 ^ key[0],
b = encrypted3 ^ key[1],
c = encrypted2 ^ key[2],
d = encrypted1 ^ key[3],
a2,
b2,
c2,
nInnerRounds = key.length / 4 - 2,
// key.length === 2 ?
i,
kIndex = 4,
table = this._tables[1],
// load up the tables
table0 = table[0],
table1 = table[1],
table2 = table[2],
table3 = table[3],
sbox = table[4];
// Inner rounds. Cribbed from OpenSSL.
for (i = 0; i < nInnerRounds; i++) {
a2 = table0[a >>> 24] ^ table1[b >> 16 & 255] ^ table2[c >> 8 & 255] ^ table3[d & 255] ^ key[kIndex];
b2 = table0[b >>> 24] ^ table1[c >> 16 & 255] ^ table2[d >> 8 & 255] ^ table3[a & 255] ^ key[kIndex + 1];
c2 = table0[c >>> 24] ^ table1[d >> 16 & 255] ^ table2[a >> 8 & 255] ^ table3[b & 255] ^ key[kIndex + 2];
d = table0[d >>> 24] ^ table1[a >> 16 & 255] ^ table2[b >> 8 & 255] ^ table3[c & 255] ^ key[kIndex + 3];
kIndex += 4;
a = a2;b = b2;c = c2;
}
// Last round.
for (i = 0; i < 4; i++) {
out[(3 & -i) + offset] = sbox[a >>> 24] << 24 ^ sbox[b >> 16 & 255] << 16 ^ sbox[c >> 8 & 255] << 8 ^ sbox[d & 255] ^ key[kIndex++];
a2 = a;a = b;b = c;c = d;d = a2;
}
}
}]);
return AES;
}();
exports.default = AES;
},{}],10:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
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; }; }(); /*
*
* This file contains an adaptation of the AES decryption algorithm
* from the Standford Javascript Cryptography Library. That work is
* covered by the following copyright and permissions notice:
*
* Copyright 2009-2010 Emily Stark, Mike Hamburg, Dan Boneh.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation
* are those of the authors and should not be interpreted as representing
* official policies, either expressed or implied, of the authors.
*/
var _aes = require('./aes');
var _aes2 = _interopRequireDefault(_aes);
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"); } }
var AES128Decrypter = function () {
function AES128Decrypter(key, initVector) {
_classCallCheck(this, AES128Decrypter);
this.key = key;
this.iv = new Uint32Array(initVector);
}
/**
* Convert network-order (big-endian) bytes into their little-endian
* representation.
*/
_createClass(AES128Decrypter, [{
key: 'ntoh',
value: function ntoh(word) {
return word << 24 | (word & 0xff00) << 8 | (word & 0xff0000) >> 8 | word >>> 24;
}
/**
* Decrypt bytes using AES-128 with CBC and PKCS#7 padding.
* @param encrypted {Uint8Array} the encrypted bytes
* @param key {Uint32Array} the bytes of the decryption key
* @param initVector {Uint32Array} the initialization vector (IV) to
* use for the first round of CBC.
* @return {Uint8Array} the decrypted bytes
*
* @see http://en.wikipedia.org/wiki/Advanced_Encryption_Standard
* @see http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Cipher_Block_Chaining_.28CBC.29
* @see https://tools.ietf.org/html/rfc2315
*/
}, {
key: 'doDecrypt',
value: function doDecrypt(encrypted, key, initVector) {
var
// word-level access to the encrypted bytes
encrypted32 = new Int32Array(encrypted.buffer, encrypted.byteOffset, encrypted.byteLength >> 2),
decipher = new _aes2.default(Array.prototype.slice.call(key)),
// byte and word-level access for the decrypted output
decrypted = new Uint8Array(encrypted.byteLength),
decrypted32 = new Int32Array(decrypted.buffer),
// temporary variables for working with the IV, encrypted, and
// decrypted data
init0,
init1,
init2,
init3,
encrypted0,
encrypted1,
encrypted2,
encrypted3,
// iteration variable
wordIx;
// pull out the words of the IV to ensure we don't modify the
// passed-in reference and easier access
init0 = ~~initVector[0];
init1 = ~~initVector[1];
init2 = ~~initVector[2];
init3 = ~~initVector[3];
// decrypt four word sequences, applying cipher-block chaining (CBC)
// to each decrypted block
for (wordIx = 0; wordIx < encrypted32.length; wordIx += 4) {
// convert big-endian (network order) words into little-endian
// (javascript order)
encrypted0 = ~~this.ntoh(encrypted32[wordIx]);
encrypted1 = ~~this.ntoh(encrypted32[wordIx + 1]);
encrypted2 = ~~this.ntoh(encrypted32[wordIx + 2]);
encrypted3 = ~~this.ntoh(encrypted32[wordIx + 3]);
// decrypt the block
decipher.decrypt(encrypted0, encrypted1, encrypted2, encrypted3, decrypted32, wordIx);
// XOR with the IV, and restore network byte-order to obtain the
// plaintext
decrypted32[wordIx] = this.ntoh(decrypted32[wordIx] ^ init0);
decrypted32[wordIx + 1] = this.ntoh(decrypted32[wordIx + 1] ^ init1);
decrypted32[wordIx + 2] = this.ntoh(decrypted32[wordIx + 2] ^ init2);
decrypted32[wordIx + 3] = this.ntoh(decrypted32[wordIx + 3] ^ init3);
// setup the IV for the next round
init0 = encrypted0;
init1 = encrypted1;
init2 = encrypted2;
init3 = encrypted3;
}
return decrypted;
}
}, {
key: 'localDecrypt',
value: function localDecrypt(encrypted, key, initVector, decrypted) {
var bytes = this.doDecrypt(encrypted, key, initVector);
decrypted.set(bytes, encrypted.byteOffset);
}
}, {
key: 'decrypt',
value: function decrypt(encrypted) {
var step = 4 * 8000,
//encrypted32 = new Int32Array(encrypted.buffer),
encrypted32 = new Int32Array(encrypted),
decrypted = new Uint8Array(encrypted.byteLength),
i = 0;
// split up the encryption job and do the individual chunks asynchronously
var key = this.key;
var initVector = this.iv;
this.localDecrypt(encrypted32.subarray(i, i + step), key, initVector, decrypted);
for (i = step; i < encrypted32.length; i += step) {
initVector = new Uint32Array([this.ntoh(encrypted32[i - 4]), this.ntoh(encrypted32[i - 3]), this.ntoh(encrypted32[i - 2]), this.ntoh(encrypted32[i - 1])]);
this.localDecrypt(encrypted32.subarray(i, i + step), key, initVector, decrypted);
}
return decrypted;
}
}]);
return AES128Decrypter;
}();
exports.default = AES128Decrypter;
},{"./aes":9}],11:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
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; }; }(); /*
* AES128 decryption.
*/
var _aes128Decrypter = require('./aes128-decrypter');
var _aes128Decrypter2 = _interopRequireDefault(_aes128Decrypter);
var _errors = require('../errors');
var _logger = require('../utils/logger');
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"); } }
var Decrypter = function () {
function Decrypter(hls) {
_classCallCheck(this, Decrypter);
this.hls = hls;
this.iv = null;
try {
var browserCrypto = window ? window.crypto : crypto;
this.subtle = browserCrypto.subtle || browserCrypto.webkitSubtle;
this.disableWebCrypto = !this.subtle;
} catch (e) {
this.disableWebCrypto = true;
}
}
_createClass(Decrypter, [{
key: 'destroy',
value: function destroy() {}
}, {
key: 'decrypt',
value: function decrypt(data, key, iv, callback) {
if (this.disableWebCrypto && this.hls.config.enableSoftwareAES) {
this.decryptBySoftware(data, key, iv, callback);
} else {
this.decryptByWebCrypto(data, key, iv, callback);
}
}
}, {
key: 'decryptByWebCrypto',
value: function decryptByWebCrypto(data, key, iv, callback) {
var _this = this;
_logger.logger.log('decrypting by WebCrypto API');
this.subtle.importKey('raw', key, { name: 'AES-CBC', length: 128 }, false, ['decrypt']).then(function (importedKey) {
_this.subtle.decrypt({ name: 'AES-CBC', iv: iv.buffer }, importedKey, data).then(callback).catch(function (err) {
_this.onWebCryptoError(err, data, key, iv, callback);
});
}).catch(function (err) {
_this.onWebCryptoError(err, data, key, iv, callback);
});
}
}, {
key: 'decryptBySoftware',
value: function decryptBySoftware(data, key8, iv8, callback) {
_logger.logger.log('decrypting by JavaScript Implementation');
var view = new DataView(key8.buffer);
var key = new Uint32Array([view.getUint32(0), view.getUint32(4), view.getUint32(8), view.getUint32(12)]);
if (iv8) {
view = new DataView(iv8.buffer);
this.iv = new Uint32Array([view.getUint32(0), view.getUint32(4), view.getUint32(8), view.getUint32(12)]);
}
var decrypter = new _aes128Decrypter2.default(key, this.iv);
var ivview = new DataView(data),
len = data.byteLength;
// save initvector for the next chunk
this.iv = new Uint32Array([ivview.getUint32(len - 16), ivview.getUint32(len - 12), ivview.getUint32(len - 8), ivview.getUint32(len - 4)]);
callback(decrypter.decrypt(data).buffer);
}
}, {
key: 'onWebCryptoError',
value: function onWebCryptoError(err, data, key, iv, callback) {
if (this.hls.config.enableSoftwareAES) {
_logger.logger.log('disabling to use WebCrypto API');
this.disableWebCrypto = true;
this.decryptBySoftware(data, key, iv, callback);
} else {
_logger.logger.error('decrypting error : ' + err.message);
this.hls.trigger(Event.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.FRAG_DECRYPT_ERROR, fatal: true, reason: err.message });
}
}
}]);
return Decrypter;
}();
exports.default = Decrypter;
},{"../errors":20,"../utils/logger":38,"./aes128-decrypter":10}],12:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
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; }; }(); /**
* AAC demuxer
*/
var _adts = require('./adts');
var _adts2 = _interopRequireDefault(_adts);
var _logger = require('../utils/logger');
var _id = require('../demux/id3');
var _id2 = _interopRequireDefault(_id);
var _events = require('../events');
var _events2 = _interopRequireDefault(_events);
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"); } }
var AACDemuxer = function () {
function AACDemuxer(observer, remuxerClass, config, typeSupported) {
_classCallCheck(this, AACDemuxer);
this.observer = observer;
this.remuxerClass = remuxerClass;
this.config = config;
this.remuxer = new this.remuxerClass(observer, config, typeSupported);
this._aacTrack = { container: 'audio/adts', type: 'audio', id: -1, sequenceNumber: 0, samples: [], len: 0 };
}
_createClass(AACDemuxer, [{
key: 'push',
// feed incoming data to the front of the parsing pipeline
value: function push(data, audioCodec, videoCodec, timeOffset, cc, level, sn, duration, accurate, first, final) {
var track = this._aacTrack,
id3 = new _id2.default(data),
pts = 90 * id3.timeStamp,
config,
frameLength,
frameDuration,
frameIndex,
offset,
headerLength,
stamp,
len,
aacSample,
startPTS,
endPTS;
// look for ADTS header (0xFFFx)
for (offset = id3.length, len = data.length; offset < len - 1; offset++) {
if (data[offset] === 0xff && (data[offset + 1] & 0xf0) === 0xf0) {
break;
}
}
if (first) {
this.fragStats = { keyFrames: 0, dropped: 0, segment: sn, level: level, notFirstKeyframe: 0 };
}
if (!track.audiosamplerate) {
config = _adts2.default.getAudioConfig(this.observer, data, offset, audioCodec);
track.config = config.config;
track.audiosamplerate = config.samplerate;
track.channelCount = config.channelCount;
track.codec = config.codec;
track.duration = duration;
_logger.logger.log('parsed codec:' + track.codec + ',rate:' + config.samplerate + ',nb channel:' + config.channelCount);
}
frameIndex = 0;
frameDuration = 1024 * 90000 / track.audiosamplerate;
while (offset + 5 < len) {
// The protection skip bit tells us if we have 2 bytes of CRC data at the end of the ADTS header
headerLength = !!(data[offset + 1] & 0x01) ? 7 : 9;
// retrieve frame size
frameLength = (data[offset + 3] & 0x03) << 11 | data[offset + 4] << 3 | (data[offset + 5] & 0xE0) >>> 5;
frameLength -= headerLength;
//stamp = pes.pts;
if (frameLength > 0 && offset + headerLength + frameLength <= len) {
stamp = pts + frameIndex * frameDuration;
//logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}/${(stamp/90).toFixed(0)}`);
aacSample = { unit: data.subarray(offset + headerLength, offset + headerLength + frameLength), pts: stamp, dts: stamp };
track.samples.push(aacSample);
track.len += frameLength;
offset += frameLength + headerLength;
frameIndex++;
// look for ADTS header (0xFFFx)
for (; offset < len - 1; offset++) {
if (data[offset] === 0xff && (data[offset + 1] & 0xf0) === 0xf0) {
break;
}
}
} else {
break;
}
}
if (track.samples.length && final) {
var timescale = this.remuxer.PES_TIMESCALE;
var initDTS = this.remuxer._initDTS === undefined ? track.samples[0].dts - timescale * timeOffset : this.remuxer._initDTS;
var nextAvcDts = timeOffset * timescale;
startPTS = this.remuxer._PTSNormalize(track.samples[0].pts - initDTS, nextAvcDts) / timescale;
endPTS = this.remuxer._PTSNormalize(track.samples[track.samples.length - 1].pts + frameDuration - initDTS, nextAvcDts) / timescale;
}
this.remuxer.remux(this._aacTrack, { samples: [] }, { samples: [{ pts: pts, dts: pts, unit: id3.payload }] }, { samples: [] }, timeOffset, undefined, undefined, undefined, undefined, this.fragStats);
if (final) {
this.observer.trigger(_events2.default.FRAG_PARSED, { startPTS: startPTS, endPTS: endPTS, PTSDTSshift: 0 });
}
}
}, {
key: 'destroy',
value: function destroy() {}
}], [{
key: 'probe',
value: function probe(data) {
// check if data contains ID3 timestamp and ADTS sync worc
var id3 = new _id2.default(data),
offset,
len;
if (id3.hasTimeStamp) {
// look for ADTS header (0xFFFx)
for (offset = id3.length, len = data.length; offset < len - 1; offset++) {
if (data[offset] === 0xff && (data[offset + 1] & 0xf0) === 0xf0) {
//logger.log('ADTS sync word found !');
return true;
}
}
}
return false;
}
}]);
return AACDemuxer;
}();
exports.default = AACDemuxer;
},{"../demux/id3":18,"../events":22,"../utils/logger":38,"./adts":13}],13:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
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; }; }(); /**
* ADTS parser helper
*/
var _logger = require('../utils/logger');
var _errors = require('../errors');
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var ADTS = function () {
function ADTS() {
_classCallCheck(this, ADTS);
}
_createClass(ADTS, null, [{
key: 'getAudioConfig',
value: function getAudioConfig(observer, data, offset, audioCodec) {
var adtsObjectType,
// :int
adtsSampleingIndex,
// :int
adtsExtensionSampleingIndex,
// :int
adtsChanelConfig,
// :int
config,
userAgent = navigator.userAgent.toLowerCase(),
adtsSampleingRates = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
// byte 2
adtsObjectType = ((data[offset + 2] & 0xC0) >>> 6) + 1;
adtsSampleingIndex = (data[offset + 2] & 0x3C) >>> 2;
if (adtsSampleingIndex > adtsSampleingRates.length - 1) {
observer.trigger(Event.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.FRAG_PARSING_ERROR, fatal: true, reason: 'invalid ADTS sampling index:' + adtsSampleingIndex });
return;
}
adtsChanelConfig = (data[offset + 2] & 0x01) << 2;
// byte 3
adtsChanelConfig |= (data[offset + 3] & 0xC0) >>> 6;
_logger.logger.log('manifest codec:' + audioCodec + ',ADTS data:type:' + adtsObjectType + ',sampleingIndex:' + adtsSampleingIndex + '[' + adtsSampleingRates[adtsSampleingIndex] + 'Hz],channelConfig:' + adtsChanelConfig);
// firefox: freq less than 24kHz = AAC SBR (HE-AAC)
if (userAgent.indexOf('firefox') !== -1) {
if (adtsSampleingIndex >= 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)
adtsExtensionSampleingIndex = adtsSampleingIndex - 3;
} else {
adtsObjectType = 2;
config = new Array(2);
adtsExtensionSampleingIndex = adtsSampleingIndex;
}
// Android : always use AAC
} else if (userAgent.indexOf('android') !== -1) {
adtsObjectType = 2;
config = new Array(2);
adtsExtensionSampleingIndex = adtsSampleingIndex;
} else {
/* for other browsers (chrome ...)
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 && adtsSampleingIndex >= 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)
adtsExtensionSampleingIndex = adtsSampleingIndex - 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 && adtsSampleingIndex >= 6 && adtsChanelConfig === 1 || !audioCodec && adtsChanelConfig === 1) {
adtsObjectType = 2;
config = new Array(2);
}
adtsExtensionSampleingIndex = adtsSampleingIndex;
}
}
/* 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] |= (adtsSampleingIndex & 0x0E) >> 1;
config[1] |= (adtsSampleingIndex & 0x01) << 7;
// channelConfiguration
config[1] |= adtsChanelConfig << 3;
if (adtsObjectType === 5) {
// adtsExtensionSampleingIndex
config[1] |= (adtsExtensionSampleingIndex & 0x0E) >> 1;
config[2] = (adtsExtensionSampleingIndex & 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[adtsSampleingIndex], channelCount: adtsChanelConfig, codec: 'mp4a.40.' + adtsObjectType };
}
}]);
return ADTS;
}();
exports.default = ADTS;
},{"../errors":20,"../utils/logger":38}],14:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
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; }; }(); /* inline demuxer.
* probe fragments and instantiate appropriate demuxer depending on content type (TSDemuxer, AACDemuxer, ...)
*/
var _events = require('../events');
var _events2 = _interopRequireDefault(_events);
var _errors = require('../errors');
var _aacdemuxer = require('../demux/aacdemuxer');
var _aacdemuxer2 = _interopRequireDefault(_aacdemuxer);
var _tsdemuxer = require('../demux/tsdemuxer');
var _tsdemuxer2 = _interopRequireDefault(_tsdemuxer);
var _mp4Remuxer = require('../remux/mp4-remuxer');
var _mp4Remuxer2 = _interopRequireDefault(_mp4Remuxer);
var _passthroughRemuxer = require('../remux/passthrough-remuxer');
var _passthroughRemuxer2 = _interopRequireDefault(_passthroughRemuxer);
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"); } }
var DemuxerInline = function () {
function DemuxerInline(hls, typeSupported) {
var config = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
_classCallCheck(this, DemuxerInline);
var _this = this;
this.hls = hls;
this.config = this.hls.config || config;
this.typeSupported = typeSupported;
this.timeOffset = 0;
this.onFragParsingData = function (ev, data) {
if (data.type === 'video' && !data.flush) {
// sync on video chunks
_this.timeOffset += data.endDTS - data.startDTS;
}
};
this.hls.on(_events2.default.FRAG_PARSING_DATA, this.onFragParsingData);
}
_createClass(DemuxerInline, [{
key: 'destroy',
value: function destroy() {
var demuxer = this.demuxer;
if (demuxer) {
demuxer.destroy();
}
this.hls.off(_events2.default.FRAG_PARSING_DATA, this.onFragParsingData);
}
}, {
key: 'push',
value: function push(data, audioCodec, videoCodec, timeOffset, cc, level, sn, duration, accurate, first, final, lastSN) {
var demuxer = this.demuxer;
if (!demuxer) {
var hls = this.hls;
// probe for content type
if (_tsdemuxer2.default.probe(data)) {
if (this.typeSupported.mp2t === true) {
demuxer = new _tsdemuxer2.default(hls, _passthroughRemuxer2.default, this.config, this.typeSupported);
} else {
demuxer = new _tsdemuxer2.default(hls, _mp4Remuxer2.default, this.config, this.typeSupported);
}
} else if (_aacdemuxer2.default.probe(data)) {
demuxer = new _aacdemuxer2.default(hls, _mp4Remuxer2.default, this.config, this.typeSupported);
} else {
var i = void 0,
len = data.length,
info = 'len:' + len + ' [';
for (i = 0, len = Math.min(len, 10); i < len; i++) {
if (i) {
info += ',';
}
info += data[i];
}
info += '..]';
if (data.length >= 3 * 188) {
info += ' [0]==' + data[0] + ' [188]==' + data[188] + ' [2*188]==' + data[2 * 188];
}
hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.FRAG_PARSING_ERROR, fatal: true,
reason: 'no demux matching with content found ' + info });
return;
}
this.demuxer = demuxer;
}
if (first) {
this.timeOffset = timeOffset;
}
demuxer.push(data, audioCodec, videoCodec, this.timeOffset, cc, level, sn, duration, accurate, first, final, lastSN);
}
}]);
return DemuxerInline;
}();
exports.default = DemuxerInline;
},{"../demux/aacdemuxer":12,"../demux/tsdemuxer":19,"../errors":20,"../events":22,"../remux/mp4-remuxer":31,"../remux/passthrough-remuxer":32}],15:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _demuxerInline = require('../demux/demuxer-inline');
var _demuxerInline2 = _interopRequireDefault(_demuxerInline);
var _events = require('../events');
var _events2 = _interopRequireDefault(_events);
var _events3 = require('events');
var _events4 = _interopRequireDefault(_events3);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var DemuxerWorker = function DemuxerWorker(self) {
// observer setup
var observer = new _events4.default();
observer.trigger = function trigger(event) {
for (var _len = arguments.length, data = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
data[_key - 1] = arguments[_key];
}
observer.emit.apply(observer, [event, event].concat(data));
};
observer.off = function off(event) {
for (var _len2 = arguments.length, data = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
data[_key2 - 1] = arguments[_key2];
}
observer.removeListener.apply(observer, [event].concat(data));
};
self.addEventListener('message', function (ev) {
var data = ev.data;
//console.log('demuxer cmd:' + data.cmd);
switch (data.cmd) {
case 'init':
self.demuxer = new _demuxerInline2.default(observer, data.typeSupported, JSON.parse(data.config));
break;
case 'demux':
self.demuxer.push(new Uint8Array(data.data), data.audioCodec, data.videoCodec, data.timeOffset, data.cc, data.level, data.sn, data.duration, data.accurate, data.first, data.final, data.lastSN);
break;
case 'empty':
self.postMessage({ event: _events2.default.DEMUXER_QUEUE_EMPTY });
break;
default:
break;
}
});
// listen to events triggered by Demuxer
observer.on(_events2.default.FRAG_PARSING_INIT_SEGMENT, function (ev, data) {
self.postMessage({ event: ev, tracks: data.tracks, unique: data.unique });
});
observer.on(_events2.default.FRAG_PARSING_DATA, function (ev, data) {
var objData = { event: ev, type: data.type, startPTS: data.startPTS, endPTS: data.endPTS, startDTS: data.startDTS, endDTS: data.endDTS, data1: data.data1.buffer, data2: data.data2.buffer, nb: data.nb, dropped: data.dropped, deltaPTS: data.deltaPTS };
// pass data1/data2 as transferable object (no copy)
self.postMessage(objData, [objData.data1, objData.data2]);
});
observer.on(_events2.default.FRAG_PARSED, function (event, data) {
self.postMessage({ event: event, data: data });
});
observer.on(_events2.default.FRAG_STATISTICS, function (event, data) {
self.postMessage({ event: event, data: data });
});
observer.on(_events2.default.ERROR, function (event, data) {
self.postMessage({ event: event, data: data });
});
observer.on(_events2.default.FRAG_PARSING_METADATA, function (event, data) {
var objData = { event: event, samples: data.samples };
self.postMessage(objData);
});
observer.on(_events2.default.FRAG_PARSING_USERDATA, function (event, data) {
var objData = { event: event, samples: data.samples };
self.postMessage(objData);
});
}; /* demuxer web worker.
* - listen to worker message, and trigger DemuxerInline upon reception of Fragments.
* - provides MP4 Boxes back to main thread using [transferable objects](https://developers.google.com/web/updates/2011/12/Transferable-Objects-Lightning-Fast) in order to minimize message passing overhead.
*/
exports.default = DemuxerWorker;
},{"../demux/demuxer-inline":14,"../events":22,"events":44}],16:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
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 _events = require('../events');
var _events2 = _interopRequireDefault(_events);
var _demuxerInline = require('../demux/demuxer-inline');
var _demuxerInline2 = _interopRequireDefault(_demuxerInline);
var _demuxerWorker = require('../demux/demuxer-worker');
var _demuxerWorker2 = _interopRequireDefault(_demuxerWorker);
var _logger = require('../utils/logger');
var _decrypter = require('../crypt/decrypter');
var _decrypter2 = _interopRequireDefault(_decrypter);
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"); } }
var Demuxer = function () {
function Demuxer(hls) {
_classCallCheck(this, Demuxer);
this.hls = hls;
this.trail = new Uint8Array(0);
var typeSupported = {
mp4: MediaSource.isTypeSupported('video/mp4'),
mp2t: hls.config.enableMP2TPassThrough && MediaSource.isTypeSupported('video/mp2t'),
mpeg: MediaSource.isTypeSupported('audio/mpeg'),
mp3: MediaSource.isTypeSupported('audio/mp4; codecs="mp3"')
};
if (hls.config.disableMp3) {
typeSupported.mpeg = typeSupported.mp3 = false;
}
if (hls.config.enableWorker && typeof Worker !== 'undefined') {
_logger.logger.log('demuxing in webworker');
try {
var work = require('webworkify');
this.w = work(_demuxerWorker2.default);
this.onwmsg = this.onWorkerMessage.bind(this);
this.w.addEventListener('message', this.onwmsg);
this.w.postMessage({ cmd: 'init', typeSupported: typeSupported, config: JSON.stringify(hls.config) });
} catch (err) {
_logger.logger.error('error while initializing DemuxerWorker, fallback on DemuxerInline');
this.demuxer = new _demuxerInline2.default(hls, typeSupported);
}
} else {
this.demuxer = new _demuxerInline2.default(hls, typeSupported);
}
this.demuxInitialized = true;
}
_createClass(Demuxer, [{
key: 'destroy',
value: function destroy() {
if (this.w) {
this.w.removeEventListener('message', this.onwmsg);
this.w.terminate();
this.w = null;
} else {
this.demuxer.destroy();
this.demuxer = null;
}
if (this.decrypter) {
this.decrypter.destroy();
this.decrypter = null;
}
}
}, {
key: 'pushDecrypted',
value: function pushDecrypted(data, audioCodec, videoCodec, timeOffset, cc, level, sn, duration, accurate, first, final, lastSN) {
if (this.w) {
// post fragment payload as transferable objects (no copy)
this.w.postMessage({ cmd: 'demux', data: data, audioCodec: audioCodec, videoCodec: videoCodec, timeOffset: timeOffset, cc: cc, level: level, sn: sn, duration: duration, accurate: accurate, first: first, final: final, lastSN: lastSN }, [data]);
} else {
this.demuxer.push(new Uint8Array(data), audioCodec, videoCodec, timeOffset, cc, level, sn, duration, accurate, first, final, lastSN);
}
}
}, {
key: 'push',
value: function push(data, audioCodec, videoCodec, timeOffset, cc, level, sn, duration, decryptdata, accurate, lastSN) {
if (data.first) {
this.trail = new Uint8Array(0);
this.trail.first = true;
}
var traillen = this.trail.length;
// 752 = 4*188. We need number of bytes to be multiplier of 16 to
// perform chained AES decryption
if (traillen || (data.byteLength + traillen) % 752) {
var final = data.final,
first = data.first || this.trail.first || false;
// add trailing bytes
var newlen = data.byteLength + traillen;
if (!final) {
// at final chunk we sent all pending data
newlen -= newlen % 752;
}
var olddata = new Uint8Array(data);
var newdata = new Uint8Array(newlen);
var newtrail = new Uint8Array(data.byteLength + traillen - newlen);
if (newlen) {
newdata.set(this.trail);
newdata.set(olddata.subarray(0, newlen - traillen), traillen);
}
if (newtrail.length) {
if (newlen) {
newtrail.set(olddata.subarray(-newtrail.length));
} else {
newtrail.set(this.trail);
newtrail.set(olddata, traillen);
newtrail.first = first;
}
}
olddata = null;
this.trail = newtrail;
if (!newdata.length) {
return;
}
data = newdata.buffer;
data.final = final;
data.first = first;
newdata = null;
}
if (data.byteLength > 0 && decryptdata != null && decryptdata.key != null && decryptdata.method === 'AES-128') {
if (this.decrypter == null) {
this.decrypter = new _decrypter2.default(this.hls);
}
var localthis = this;
this.decrypter.decrypt(data, decryptdata.key, data.first && decryptdata.iv, function (decryptedData) {
localthis.pushDecrypted(decryptedData, audioCodec, videoCodec, timeOffset, cc, level, sn, duration, accurate, !!data.first, !!data.final, lastSN);
});
} else {
this.pushDecrypted(data, audioCodec, videoCodec, timeOffset, cc, level, sn, duration, accurate, !!data.first, !!data.final, lastSN);
}
}
}, {
key: 'onWorkerMessage',
value: function onWorkerMessage(ev) {
var data = ev.data;
switch (data.event) {
case _events2.default.FRAG_PARSING_INIT_SEGMENT:
var obj = {};
obj.tracks = data.tracks;
obj.unique = data.unique;
this.hls.trigger(_events2.default.FRAG_PARSING_INIT_SEGMENT, obj);
break;
case _events2.default.FRAG_PARSING_DATA:
this.hls.trigger(_events2.default.FRAG_PARSING_DATA, {
data1: new Uint8Array(data.data1),
data2: new Uint8Array(data.data2),
startPTS: data.startPTS,
endPTS: data.endPTS,
startDTS: data.startDTS,
endDTS: data.endDTS,
type: data.type,
nb: data.nb,
dropped: data.dropped,
deltaPTS: data.deltaPTS
});
break;
case _events2.default.FRAG_PARSING_METADATA:
this.hls.trigger(_events2.default.FRAG_PARSING_METADATA, {
samples: data.samples
});
break;
case _events2.default.FRAG_PARSING_USERDATA:
this.hls.trigger(_events2.default.FRAG_PARSING_USERDATA, {
samples: data.samples
});
break;
default:
this.hls.trigger(data.event, data.data);
break;
}
}
}, {
key: 'waitQueue',
value: function waitQueue() {
if (this.w) {
this.w.postMessage({ cmd: 'empty' });
}
}
}]);
return Demuxer;
}();
exports.default = Demuxer;
},{"../crypt/decrypter":11,"../demux/demuxer-inline":14,"../demux/demuxer-worker":15,"../events":22,"../utils/logger":38,"webworkify":45}],17:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
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; }; }(); /**
* Parser for exponential Golomb codes, a variable-bitwidth number encoding scheme used by h264.
*/
var _logger = require('../utils/logger');
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var ExpGolomb = function () {
function ExpGolomb(data) {
_classCallCheck(this, ExpGolomb);
this.data = data;
// the number of bytes left to examine in this.data
this.bytesAvailable = this.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
}
_createClass(ExpGolomb, [{
key: 'wholeBytesAvailable',
value: function wholeBytesAvailable() {
return this.bytesAvailable + (this.bitsAvailable >> 3);
}
// ():void
}, {
key: 'loadWord',
value: function loadWord() {
var position = this.data.byteLength - this.bytesAvailable,
workingBytes = new Uint8Array(4),
availableBytes = Math.min(4, this.bytesAvailable);
if (availableBytes === 0) {
throw new Error('no bytes available');
}
workingBytes.set(this.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
}, {
key: 'skipBits',
value: 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
}, {
key: 'readBits',
value: function readBits(size) {
var bits = Math.min(this.bitsAvailable, size),
// :uint
valu = this.word >>> 32 - bits; // :uint
if (size > 32) {
_logger.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;
return bits > 0 && this.bitsAvailable ? valu << bits | this.readBits(bits) : valu;
}
// ():uint
}, {
key: 'skipLZ',
value: function skipLZ() {
var leadingZeroCount; // :uint
for (leadingZeroCount = 0; leadingZeroCount < this.bitsAvailable; ++leadingZeroCount) {
if (0 !== (this.word & 0x80000000 >>> leadingZeroCount)) {
// 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
}, {
key: 'skipUEG',
value: function skipUEG() {
this.skipBits(1 + this.skipLZ());
}
// ():void
}, {
key: 'skipEG',
value: function skipEG() {
this.skipBits(1 + this.skipLZ());
}
// ():uint
}, {
key: 'readUEG',
value: function readUEG() {
var clz = this.skipLZ(); // :uint
return this.readBits(clz + 1) - 1;
}
// ():int
}, {
key: 'readEG',
value: 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
}, {
key: 'readBoolean',
value: function readBoolean() {
return 1 === this.readBits(1);
}
// ():int
}, {
key: 'readUByte',
value: function readUByte() {
return this.readBits(8);
}
// ():int
}, {
key: 'readUShort',
value: function readUShort() {
return this.readBits(16);
}
// ():int
}, {
key: 'readUInt',
value: 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 {number} the number of entries in this scaling list
* @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1
*/
}, {
key: 'skipScalingList',
value: function skipScalingList(count) {
var lastScale = 8,
nextScale = 8,
j,
deltaScale;
for (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.
*/
}, {
key: 'readSPS',
value: function readSPS() {
var frameCropLeftOffset = 0,
frameCropRightOffset = 0,
frameCropTopOffset = 0,
frameCropBottomOffset = 0,
sarScale = 1,
profileIdc,
profileCompat,
levelIdc,
numRefFramesInPicOrderCntCycle,
picWidthInMbsMinus1,
picHeightInMapUnitsMinus1,
frameMbsOnlyFlag,
scalingListCount,
i;
this.readUByte();
profileIdc = this.readUByte(); // profile_idc
profileCompat = this.readBits(5); // constraint_set[0-4]_flag, u(5)
this.skipBits(3); // reserved_zero_3bits u(3),
levelIdc = this.readUByte(); //level_idc u(8)
this.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 = this.readUEG();
if (chromaFormatIdc === 3) {
this.skipBits(1); // separate_colour_plane_flag
}
this.skipUEG(); // bit_depth_luma_minus8
this.skipUEG(); // bit_depth_chroma_minus8
this.skipBits(1); // qpprime_y_zero_transform_bypass_flag
if (this.readBoolean()) {
// seq_scaling_matrix_present_flag
scalingListCount = chromaFormatIdc !== 3 ? 8 : 12;
for (i = 0; i < scalingListCount; i++) {
if (this.readBoolean()) {
// seq_scaling_list_present_flag[ i ]
if (i < 6) {
this.skipScalingList(16);
} else {
this.skipScalingList(64);
}
}
}
}
}
this.skipUEG(); // log2_max_frame_num_minus4
var picOrderCntType = this.readUEG();
if (picOrderCntType === 0) {
this.readUEG(); //log2_max_pic_order_cnt_lsb_minus4
} else if (picOrderCntType === 1) {
this.skipBits(1); // delta_pic_order_always_zero_flag
this.skipEG(); // offset_for_non_ref_pic
this.skipEG(); // offset_for_top_to_bottom_field
numRefFramesInPicOrderCntCycle = this.readUEG();
for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) {
this.skipEG(); // offset_for_ref_frame[ i ]
}
}
this.skipUEG(); // max_num_ref_frames
this.skipBits(1); // gaps_in_frame_num_value_allowed_flag
picWidthInMbsMinus1 = this.readUEG();
picHeightInMapUnitsMinus1 = this.readUEG();
frameMbsOnlyFlag = this.readBits(1);
if (frameMbsOnlyFlag === 0) {
this.skipBits(1); // mb_adaptive_frame_field_flag
}
this.skipBits(1); // direct_8x8_inference_flag
if (this.readBoolean()) {
// frame_cropping_flag
frameCropLeftOffset = this.readUEG();
frameCropRightOffset = this.readUEG();
frameCropTopOffset = this.readUEG();
frameCropBottomOffset = this.readUEG();
}
if (this.readBoolean()) {
// vui_parameters_present_flag
if (this.readBoolean()) {
// aspect_ratio_info_present_flag
var sarRatio = void 0;
var aspectRatioIdc = this.readUByte();
switch (aspectRatioIdc) {
case 1:
sarRatio = [1, 1];break;
case 2:
sarRatio = [12, 11];break;
case 3:
sarRatio = [10, 11];break;
case 4:
sarRatio = [16, 11];break;
case 5:
sarRatio = [40, 33];break;
case 6:
sarRatio = [24, 11];break;
case 7:
sarRatio = [20, 11];break;
case 8:
sarRatio = [32, 11];break;
case 9:
sarRatio = [80, 33];break;
case 10:
sarRatio = [18, 11];break;
case 11:
sarRatio = [15, 11];break;
case 12:
sarRatio = [64, 33];break;
case 13:
sarRatio = [160, 99];break;
case 14:
sarRatio = [4, 3];break;
case 15:
sarRatio = [3, 2];break;
case 16:
sarRatio = [2, 1];break;
case 255:
{
sarRatio = [this.readUByte() << 8 | this.readUByte(), this.readUByte() << 8 | this.readUByte()];
break;
}
}
if (sarRatio) {
sarScale = sarRatio[0] / sarRatio[1];
}
}
}
return {
width: Math.ceil(((picWidthInMbsMinus1 + 1) * 16 - frameCropLeftOffset * 2 - frameCropRightOffset * 2) * sarScale),
height: (2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16 - (frameMbsOnlyFlag ? 2 : 4) * (frameCropTopOffset + frameCropBottomOffset)
};
}
}, {
key: 'readSliceType',
value: function readSliceType() {
// skip NALu type
this.readUByte();
// discard first_mb_in_slice
this.readUEG();
// return slice_type
return this.readUEG();
}
}]);
return ExpGolomb;
}();
exports.default = ExpGolomb;
},{"../utils/logger":38}],18:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
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; }; }(); /**
* ID3 parser
*/
var _logger = require('../utils/logger');
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
//import Hex from '../utils/hex';
var ID3 = function () {
function ID3(data) {
_classCallCheck(this, ID3);
this._hasTimeStamp = false;
var offset = 0,
byte1,
byte2,
byte3,
byte4,
tagSize,
endPos,
header,
len;
do {
header = this.readUTF(data, offset, 3);
offset += 3;
// first check for ID3 header
if (header === 'ID3') {
// skip 24 bits
offset += 3;
// retrieve tag(s) length
byte1 = data[offset++] & 0x7f;
byte2 = data[offset++] & 0x7f;
byte3 = data[offset++] & 0x7f;
byte4 = data[offset++] & 0x7f;
tagSize = (byte1 << 21) + (byte2 << 14) + (byte3 << 7) + byte4;
endPos = offset + tagSize;
//logger.log(`ID3 tag found, size/end: ${tagSize}/${endPos}`);
// read ID3 tags
this._parseID3Frames(data, offset, endPos);
offset = endPos;
} else if (header === '3DI') {
// http://id3.org/id3v2.4.0-structure chapter 3.4. ID3v2 footer
offset += 7;
_logger.logger.log('3DI footer found, end: ' + offset);
} else {
offset -= 3;
len = offset;
if (len) {
//logger.log(`ID3 len: ${len}`);
if (!this.hasTimeStamp) {
_logger.logger.warn('ID3 tag found, but no timestamp');
}
this._length = len;
this._payload = data.subarray(0, len);
}
return;
}
} while (true);
}
_createClass(ID3, [{
key: 'readUTF',
value: function readUTF(data, start, len) {
var result = '',
offset = start,
end = start + len;
do {
result += String.fromCharCode(data[offset++]);
} while (offset < end);
return result;
}
}, {
key: '_parseID3Frames',
value: function _parseID3Frames(data, offset, endPos) {
var tagId, tagLen, tagStart, tagFlags, timestamp;
while (offset + 8 <= endPos) {
tagId = this.readUTF(data, offset, 4);
offset += 4;
tagLen = data[offset++] << 24 + data[offset++] << 16 + data[offset++] << 8 + data[offset++];
tagFlags = data[offset++] << 8 + data[offset++];
tagStart = offset;
//logger.log("ID3 tag id:" + tagId);
switch (tagId) {
case 'PRIV':
//logger.log('parse frame:' + Hex.hexDump(data.subarray(offset,endPos)));
// owner should be "com.apple.streaming.transportStreamTimestamp"
if (this.readUTF(data, offset, 44) === 'com.apple.streaming.transportStreamTimestamp') {
offset += 44;
// smelling even better ! we found the right descriptor
// skip null character (string end) + 3 first bytes
offset += 4;
// timestamp is 33 bit expressed as a big-endian eight-octet number, with the upper 31 bits set to zero.
var pts33Bit = data[offset++] & 0x1;
this._hasTimeStamp = true;
timestamp = ((data[offset++] << 23) + (data[offset++] << 15) + (data[offset++] << 7) + data[offset++]) / 45;
if (pts33Bit) {
timestamp += 47721858.84; // 2^32 / 90
}
timestamp = Math.round(timestamp);
_logger.logger.trace('ID3 timestamp found: ' + timestamp);
this._timeStamp = timestamp;
}
break;
default:
break;
}
}
}
}, {
key: 'hasTimeStamp',
get: function get() {
return this._hasTimeStamp;
}
}, {
key: 'timeStamp',
get: function get() {
return this._timeStamp;
}
}, {
key: 'length',
get: function get() {
return this._length;
}
}, {
key: 'payload',
get: function get() {
return this._payload;
}
}]);
return ID3;
}();
exports.default = ID3;
},{"../utils/logger":38}],19:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
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; }; }(); /**
* 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.
*/
// import Hex from '../utils/hex';
var _adts = require('./adts');
var _adts2 = _interopRequireDefault(_adts);
var _events = require('../events');
var _events2 = _interopRequireDefault(_events);
var _expGolomb = require('./exp-golomb');
var _expGolomb2 = _interopRequireDefault(_expGolomb);
var _logger = require('../utils/logger');
var _errors = require('../errors');
require('../utils/polyfill');
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"); } }
var TSDemuxer = function () {
function TSDemuxer(observer, remuxerClass, config, typeSupported) {
_classCallCheck(this, TSDemuxer);
this.observer = observer;
this.remuxerClass = remuxerClass;
this.config = config;
this.typeSupported = typeSupported;
this.lastCC = 0;
this._setEmptyTracks();
this._clearAllData();
this.remuxer = new this.remuxerClass(observer, config, typeSupported);
}
_createClass(TSDemuxer, [{
key: '_setEmptyTracks',
value: function _setEmptyTracks() {
var track = void 0;
if (track = this._avcTrack) {
if (track.sps) {
track.savedSps = track.sps;
}
if (track.pps) {
track.savedPps = track.pps;
}
}
this._avcTrack = Object.assign({}, this._avcTrack, { container: 'video/mp2t', type: 'video', samples: [], len: 0, nbNalu: 0, sps: undefined, pps: undefined });
this._aacTrack = Object.assign({}, this._aacTrack, { container: 'video/mp2t', type: 'audio', samples: [], len: 0, isAAC: true });
this._id3Track = Object.assign({}, this._id3Track, { type: 'id3', samples: [], len: 0 });
this._txtTrack = Object.assign({}, this._txtTrack, { type: 'text', samples: [], len: 0 });
this._avcTrack.sequenceNumber = this._avcTrack.sequenceNumber | 0;
this._aacTrack.sequenceNumber = this._aacTrack.sequenceNumber | 0;
this._id3Track.sequenceNumber = this._id3Track.sequenceNumber | 0;
this._txtTrack.sequenceNumber = this._txtTrack.sequenceNumber | 0;
}
}, {
key: '_clearIDs',
value: function _clearIDs() {
this._aacTrack.id = this._avcTrack.id = this._id3Track.id = this._txtTrack.id = -1;
}
}, {
key: 'switchLevel',
value: function switchLevel() {
// flush end of previous segment
if (this._avcTrack.samples.length) {
this.remux(null, false, true, false);
}
this.pmtParsed = false;
this._pmtId = -1;
this._setEmptyTracks();
this._clearAllData();
this._clearIDs();
// flush any partial content
this.aacOverFlow = null;
this.lastAacPTS = null;
this.remuxer.switchLevel();
}
}, {
key: '_clearAvcData',
value: function _clearAvcData() {
return this._avcData = { data: [], size: 0 };
}
}, {
key: '_clearAacData',
value: function _clearAacData() {
return this._aacData = { data: [], size: 0 };
}
}, {
key: '_clearID3Data',
value: function _clearID3Data() {
return this._id3Data = { data: [], size: 0 };
}
}, {
key: '_clearAllData',
value: function _clearAllData() {
this._clearAvcData();
this._clearAacData();
this._clearID3Data();
}
}, {
key: 'insertDiscontinuity',
value: function insertDiscontinuity() {
this.switchLevel();
this.remuxer.insertDiscontinuity();
}
// feed incoming data to the front of the parsing pipeline
}, {
key: 'push',
value: function push(data, audioCodec, videoCodec, timeOffset, cc, level, sn, duration, accurate, first, final, lastSN) {
var avcData = this._avcData,
aacData = this._aacData,
pes,
id3Data = this._id3Data,
start,
len = data.length,
stt,
pid,
atf,
info,
num,
offset,
codecsOnly = this.remuxer.passthrough,
unknownPIDs = false;
this.audioCodec = audioCodec;
this.videoCodec = videoCodec;
this.timeOffset = timeOffset;
this.accurate = accurate;
this._duration = duration;
this.contiguous = false;
this.firstSample = first;
if (cc !== this.lastCC) {
_logger.logger.log('discontinuity detected');
this.insertDiscontinuity();
this.lastCC = cc;
}
var trackSwitch = level !== this.lastLevel;
if (trackSwitch) {
_logger.logger.log('level switch detected');
this.switchLevel();
this.lastLevel = level;
}
if (!trackSwitch && sn === this.lastSN + 1 || !first) {
this.contiguous = true;
} else {
// flush any partial content
if (this._avcTrack.samples.length) {
this.remux(null, false, true, false);
}
this.aacOverFlow = null;
this._clearAllData();
this._setEmptyTracks();
}
if (first) {
this.lastContiguous = !trackSwitch && sn === this.lastSN + 1;
this.fragStats = { keyFrames: 0, dropped: 0, segment: sn, level: level, notFirstKeyframe: 0 };
this.remuxAVCCount = this.remuxAACCount = 0;
this.fragStartPts = this.fragStartDts = this.gopStartDTS = undefined;
this.fragStartAVCPos = this._avcTrack.samples.length;
this.fragStartAACPos = this._aacTrack.samples.length;
this.nextAvcDts = this.contiguous ? this.remuxer.nextAvcDts : this.timeOffset * this.remuxer.PES_TIMESCALE;
}
this.currentSN = sn;
var avcId = this._avcTrack.id,
aacId = this._aacTrack.id,
id3Id = this._id3Track.id;
// don't parse last TS packet if incomplete
len -= len % 188;
// loop through TS packets
for (start = 0, num = 0; start < len; start += 188) {
if (data[start] === 0x47) {
stt = !!(data[start + 1] & 0x40);
// pid is a 13-bit field starting at the last bit of TS[1]
pid = ((data[start + 1] & 0x1f) << 8) + data[start + 2];
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.
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 (pes = this._parsePES(avcData)) {
this._parseAVCPES(pes);
if (codecsOnly) {
// if we have video codec info AND
// if audio PID is undefined OR if we have audio codec info,
// we have all codec info !
if (this._avcTrack.codec && (aacId === -1 || this._aacTrack.codec)) {
this.remux(data);
return;
}
}
}
avcData = this._clearAvcData();
}
avcData.data.push(data.subarray(offset, start + 188));
avcData.size += start + 188 - offset;
break;
case aacId:
if (stt) {
if (pes = this._parsePES(aacData)) {
if (this._aacTrack.isAAC) {
this._parseAACPES(pes);
} else {
this._parseMPEGPES(pes);
}
if (codecsOnly) {
// here we now that we have audio codec info
// if video PID is undefined OR if we have video codec info,
// we have all codec infos !
if (this._aacTrack.codec && (avcId === -1 || this._avcTrack.codec)) {
this.remux(data);
return;
}
}
}
aacData = this._clearAacData();
}
aacData.data.push(data.subarray(offset, start + 188));
aacData.size += start + 188 - offset;
break;
case id3Id:
if (stt) {
if (pes = this._parsePES(id3Data)) {
this._parseID3PES(pes);
}
id3Data = this._clearID3Data();
}
id3Data.data.push(data.subarray(offset, start + 188));
id3Data.size += start + 188 - offset;
break;
case 0:
if (stt) {
offset += data[offset] + 1;
}
this._parsePAT(data, offset);
break;
case this._pmtId:
if (stt) {
offset += data[offset] + 1;
}
this._parsePMT(data, offset, this.typeSupported.mpeg === true || this.typeSupported.mp3 === true);
avcId = this._avcTrack.id;
aacId = this._aacTrack.id;
id3Id = this._id3Track.id;
if (unknownPIDs && !this.pmtParsed) {
_logger.logger.log('reparse from beginning');
unknownPIDs = false;
// we set it to -188, the += 188 in the for loop will reset start to 0
start = -188;
}
this.pmtParsed = true;
break;
case 17:
case 0x1fff:
break;
default:
unknownPIDs = true;
break;
}
} else {
if (num === 0) {
var i = void 0,
_len = data.length;
info = 'len:' + _len + ' [';
for (i = 0, _len = Math.min(_len, 10); i < _len; i++) {
if (i) {
info += ',';
}
info += data[start + i];
}
info += '..]';
}
num++;
}
}
if (num) {
this.observer.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.FRAG_PARSING_ERROR, fatal: false, reason: 'TS packet did not start with 0x47 sn:' + sn + ' samples: ' + num + ' ' + info });
}
// parse last PES packet
if (final) {
if (avcData.size && (pes = this._parsePES(avcData))) {
this._parseAVCPES(pes);
this._clearAvcData();
}
if (aacData.size && (pes = this._parsePES(aacData))) {
if (this._aacTrack.isAAC) {
this._parseAACPES(pes);
} else {
this._parseMPEGPES(pes);
}
this._clearAacData();
}
if (id3Data.size && (pes = this._parsePES(id3Data))) {
this._parseID3PES(pes);
this._clearID3Data();
}
this.lastSN = sn;
}
if (this.fragStartPts === undefined && this._avcTrack.samples.length > this.fragStartAVCPos) {
this.fragStartPts = this._avcTrack.samples[this.fragStartAVCPos].pts;
this.fragStartDts = this._avcTrack.samples[this.fragStartAVCPos].dts;
}
if (this.gopStartDTS === undefined && this._avcTrack.samples.length) {
this.gopStartDTS = this._avcTrack.samples[0].dts;
}
this.remux(null, final, final && sn === lastSN, true);
if (final) {
this.observer.trigger(_events2.default.FRAG_STATISTICS, this.fragStats);
}
}
}, {
key: '_recalcTrack',
value: function _recalcTrack(track) {
if (track.hasOwnProperty('nbNalu')) {
track.nbNalu = 0;
}
track.len = 0;
for (var i = 0; i < track.samples.length; i++) {
var sample = track.samples[i];
track.len += ((sample.units && sample.units.length) | 0) + ((sample.unit && sample.unit.length) | 0) + (sample.len | 0) + ((sample.bytes && sample.bytes.length) | 0);
if (track.hasOwnProperty('nbNalu')) {
track.nbNalu += sample.units.units.length;
}
}
}
}, {
key: '_filterSamples',
value: function _filterSamples(track, end, _save) {
var _new = [];
for (var i = 0; i < track.samples.length; i++) {
var sample = track.samples[i];
var sampleTime = sample.dts || sample.pts;
if (sampleTime <= end) {
_new.push(sample);
} else {
_save.push(sample);
}
}
track.samples = _new;
this._recalcTrack(track);
}
}, {
key: 'remux',
value: function remux(data, final, flush, lastSegment) {
var _saveAVCSamples = [],
_saveAACSamples = [],
_saveID3Samples = [],
_saveTextSamples = [],
maxk,
samples = this._avcTrack.samples,
startPTS,
endPTS,
gopEndDTS,
initDTS;
var timescale = this.remuxer.PES_TIMESCALE;
if (samples.length && final) {
this.fragStats.PTSDTSshift = ((this.fragStartPts === undefined ? samples[0].pts : this.fragStartPts) - (this.fragStartDts === undefined ? samples[0].dts : this.fragStartDts)) / timescale;
initDTS = this.remuxer._initDTS === undefined ? samples[0].dts - timescale * this.timeOffset : this.remuxer._initDTS;
var startDTS = Math.max(this.remuxer._PTSNormalize((this.gopStartDTS === undefined ? samples[0].dts : this.gopStartDTS) - initDTS, this.nextAvcDts), 0);
var sample = samples[samples.length - 1];
var videoStartPTS = Math.max(this.remuxer._PTSNormalize((this.fragStartPts === undefined ? samples[0].pts : this.fragStartPts) - initDTS, this.nextAvcDts), 0) / timescale;
var videoEndPTS = Math.max(this.remuxer._PTSNormalize(sample.pts - initDTS, this.nextAvcDts), 0) / timescale;
if (this.accurate && Math.abs(startDTS - this.nextAvcDts) > 90) {
videoStartPTS -= (startDTS - this.nextAvcDts) / timescale;
}
if (samples.length + this.remuxAVCCount > this.fragStartAVCPos + 1 && this.fragStartDts !== undefined) {
var fragStartDts = this.remuxer._PTSNormalize(this.fragStartDts, this.nextAvcDts);
var sampleDts = this.remuxer._PTSNormalize(sample.dts, this.nextAvcDts);
videoEndPTS += (sampleDts - fragStartDts) / (samples.length + this.remuxAVCCount - this.fragStartAVCPos - 1) / timescale;
}
startPTS = videoStartPTS;
endPTS = videoEndPTS;
if (this._aacTrack.audiosamplerate) {
var expectedSampleDuration = 1024 / this._aacTrack.audiosamplerate;
var remuxAACCount = this._aacTrack.samples.length;
var nextAacPTS = (this.lastContiguous !== undefined && this.lastContiguous || this.contiguous && this.remuxAACCount) && this.remuxer.nextAacPts ? this.remuxer.nextAacPts / timescale : this.accurate ? this.timeOffset : startPTS;
startPTS = Math.max(startPTS, nextAacPTS + (this.fragStartAACPos - this.remuxAACCount) * expectedSampleDuration);
if (remuxAACCount) {
endPTS = Math.min(endPTS, nextAacPTS + expectedSampleDuration * remuxAACCount);
}
var AVUnsync = void 0;
if ((AVUnsync = endPTS - startPTS + videoStartPTS - videoEndPTS) > 0.2) {
this.fragStats.AVUnsync = AVUnsync;
}
}
// console.log(`parsed total ${startPTS}/${endPTS} video ${videoStartPTS}/${videoEndPTS} shift ${this.fragStats.PTSDTSshift}`);
}
if (!flush) {
// save samples and break by GOP
for (maxk = samples.length - 1; maxk > 0; maxk--) {
if (samples[maxk].key) {
if (maxk && (samples[maxk - 1].dts - initDTS) / timescale < startPTS) {
maxk = 0;
}
break;
}
}
if (maxk > 0) {
_saveAVCSamples = samples.slice(maxk);
this._avcTrack.samples = samples.slice(0, maxk);
gopEndDTS = this._avcTrack.samples[maxk - 1].dts;
this._recalcTrack(this._avcTrack);
this._filterSamples(this._aacTrack, gopEndDTS, _saveAACSamples);
this._filterSamples(this._id3Track, gopEndDTS, _saveID3Samples);
this._filterSamples(this._txtTrack, gopEndDTS, _saveTextSamples);
}
}
if ((flush || final && !this.remuxAVCCount) && this._avcTrack.samples.length + this._aacTrack.samples.length || maxk > 0) {
this.remuxAVCCount += this._avcTrack.samples.length;
this.remuxAACCount += this._aacTrack.samples.length;
this.remuxer.remux(this._aacTrack, this._avcTrack, this._id3Track, this._txtTrack, flush && this.nextStartPts ? this.nextStartPts : this.timeOffset, flush && !lastSegment || (this.lastContiguous !== undefined ? this.lastContiguous : this.contiguous), this.accurate, data, flush, this.fragStats);
this.lastContiguous = undefined;
this.nextStartPts = this.remuxer.endPTS;
this._avcTrack.samples = _saveAVCSamples;
this._aacTrack.samples = _saveAACSamples;
this._id3Track.samples = _saveID3Samples;
this._txtTrack.samples = _saveTextSamples;
this._recalcTrack(this._avcTrack);
this._recalcTrack(this._aacTrack);
this._recalcTrack(this._id3Track);
this._recalcTrack(this._txtTrack);
}
//notify end of parsing
if (final) {
var lastGopPTS = Math.min(this.remuxer.nextAvcDts, this.remuxer.nextAacPts) / timescale;
this.observer.trigger(_events2.default.FRAG_PARSED, { startPTS: startPTS, endPTS: endPTS, PTSDTSshift: this.fragStats.PTSDTSshift, lastGopPTS: lastGopPTS });
}
}
}, {
key: 'destroy',
value: function destroy() {
this.switchLevel();
this._initPTS = this._initDTS = undefined;
this._duration = 0;
}
}, {
key: '_parsePAT',
value: function _parsePAT(data, offset) {
// skip the PSI header and parse the first PMT entry
this._pmtId = (data[offset + 10] & 0x1F) << 8 | data[offset + 11];
//logger.log('PMT PID:' + this._pmtId);
}
}, {
key: '_parsePMT',
value: function _parsePMT(data, offset, mpegSupported) {
var sectionLength, tableEnd, programInfoLength, pid;
sectionLength = (data[offset + 1] & 0x0f) << 8 | data[offset + 2];
tableEnd = offset + 3 + sectionLength - 4;
// to determine where the table is, we have to figure out how
// long the program info descriptors are
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) {
pid = (data[offset + 1] & 0x1F) << 8 | data[offset + 2];
switch (data[offset]) {
// ISO/IEC 13818-7 ADTS AAC (MPEG-2 lower bit-rate audio)
case 0x0f:
//logger.log('AAC PID:' + pid);
if (this._aacTrack.id === -1) {
this._aacTrack.id = pid;
}
break;
// Packetized metadata (ID3)
case 0x15:
//logger.log('ID3 PID:' + pid);
if (this._id3Track.id === -1) {
this._id3Track.id = pid;
}
break;
// ITU-T Rec. H.264 and ISO/IEC 14496-10 (lower bit-rate video)
case 0x1b:
//logger.log('AVC PID:' + pid);
if (this._avcTrack.id === -1) {
this._avcTrack.id = 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.logger.log('MPEG PID:' + pid);
if (!mpegSupported) {
_logger.logger.log('MPEG audio found, not supported in this browser for now');
} else {
if (this._aacTrack.id === -1) {
this._aacTrack.id = pid;
}
this._aacTrack.isAAC = false;
}
break;
case 0x24:
this.fragStats.HEVC = (this.fragStats.HEVC | 0) + 1;
_logger.logger.warn('HEVC stream type found, not supported for now');
break;
default:
this.fragStats.unknownStream = (this.fragStats.unknownStream | 0) + 1;
_logger.logger.log('unkown 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;
}
}
}, {
key: '_parsePES',
value: function _parsePES(stream) {
var i = 0,
frag,
pesFlags,
pesPrefix,
pesLen,
pesHdrLen,
pesData,
pesPts,
pesDts,
payloadStartOffset,
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];
pesPrefix = (frag[0] << 16) + (frag[1] << 8) + frag[2];
if (pesPrefix === 1) {
pesLen = (frag[4] << 8) + frag[5];
if (pesLen && pesLen > stream.size - 6) {
return null;
}
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;
// check if greater than 2^32 -1
if (pesPts > 4294967295) {
// decrement 2^33
pesPts -= 8589934592;
}
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;
// check if greater than 2^32 -1
if (pesDts > 4294967295) {
// decrement 2^33
pesDts -= 8589934592;
}
if (pesPts - pesDts > 60 * 90000) {
_logger.logger.warn(Math.round((pesPts - pesDts) / 90000) + 's delta between PTS and DTS, align them');
pesPts = pesDts;
}
} else {
pesDts = pesPts;
}
}
pesHdrLen = frag[8];
payloadStartOffset = pesHdrLen + 9;
stream.size -= payloadStartOffset;
//reassemble PES packet
pesData = new Uint8Array(stream.size);
while (data.length) {
frag = data.shift();
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 };
} else {
return null;
}
}
}, {
key: '_parseAVCPES',
value: function _parseAVCPES(pes) {
var _this = this;
var track = this._avcTrack,
samples = track.samples,
units = this._parseAVCNALu(pes.data),
units2 = [],
debug = false,
key = false,
length = 0,
expGolombDecoder,
avcSample,
push,
hlsConfig = this.config,
i;
// no NALu found
if (units.length === 0 && samples.length > 0) {
// append pes.data to previous NAL unit
var lastavcSample = samples[samples.length - 1];
var lastUnit = lastavcSample.units.units[lastavcSample.units.units.length - 1];
var tmp = new Uint8Array(lastUnit.data.byteLength + pes.data.byteLength);
tmp.set(lastUnit.data, 0);
tmp.set(pes.data, lastUnit.data.byteLength);
lastUnit.data = tmp;
lastavcSample.units.length += pes.data.byteLength;
track.len += pes.data.byteLength;
}
//free pes.data to save up some memory
pes.data = null;
var debugString = '';
units.forEach(function (unit) {
switch (unit.type) {
//NDR
case 1:
push = true;
if (debug) {
debugString += 'NDR ';
}
// retrieve slice type by parsing beginning of NAL unit (follow H264 spec, slice_header definition) to detect keyframe embedded in NDR
var data = unit.data;
if (data.length > 1) {
var sliceType = new _expGolomb2.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) {
key = true;
}
}
break;
//IDR
case 5:
push = true;
if (debug) {
debugString += 'IDR ';
}
key = true;
break;
//SEI
case 6:
push = true;
if (debug) {
debugString += 'SEI ';
}
expGolombDecoder = new _expGolomb2.default(_this.discardEPB(unit.data));
// skip frameType
expGolombDecoder.readUByte();
var payloadType = 0;
var payloadSize = 0;
var endOfCaptions = false;
var b = 0;
while (!endOfCaptions && expGolombDecoder.wholeBytesAvailable() > 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);
// if SEI recovery_point has been found mark as keyframe
if (!hlsConfig.disableSEIkeyframes) {
key = key || payloadType === 6;
}
if (key && !track.sps && track.savedSps) {
track.sps = track.savedSps;
if (!track.pps && track.savedPps) {
track.pps = track.savedPps;
}
}
// 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.wholeBytesAvailable() !== 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 (i = 0; i < totalCCs; i++) {
// 3 bytes per CC
byteArray.push(expGolombDecoder.readUByte());
byteArray.push(expGolombDecoder.readUByte());
byteArray.push(expGolombDecoder.readUByte());
}
_this._insertSampleInOrder(_this._txtTrack.samples, { type: 3, pts: pes.pts, bytes: byteArray });
}
}
}
}
} else if (payloadSize < expGolombDecoder.wholeBytesAvailable()) {
for (i = 0; i < payloadSize; i++) {
expGolombDecoder.readUByte();
}
}
}
break;
//SPS
case 7:
push = true;
if (debug) {
debugString += 'SPS ';
}
if (!track.sps || track.sps === track.savedSps) {
track.savedSps = undefined;
expGolombDecoder = new _expGolomb2.default(unit.data);
var config = expGolombDecoder.readSPS();
track.width = config.width;
track.height = config.height;
track.sps = [unit.data];
track.duration = _this._duration;
var codecarray = unit.data.subarray(1, 4);
var codecstring = 'avc1.';
for (i = 0; i < 3; i++) {
var h = codecarray[i].toString(16);
if (h.length < 2) {
h = '0' + h;
}
codecstring += h;
}
track.codec = codecstring;
}
break;
//PPS
case 8:
push = true;
if (debug) {
debugString += 'PPS ';
}
if (!track.pps || track.pps === track.savedPps) {
track.savedPps = undefined;
track.pps = [unit.data];
}
break;
case 9:
push = false;
if (debug) {
debugString += 'AUD ';
}
break;
// Filler Data
case 12:
push = false;
break;
default:
push = false;
debugString += 'unknown NAL ' + unit.type + ' ';
break;
}
if (push) {
units2.push(unit);
length += unit.data.byteLength;
}
});
if (debug || debugString.length) {
_logger.logger.log(debugString);
}
//build sample from PES
// Annex B to MP4 conversion to be done
if (units2.length) {
// only push AVC sample if keyframe already found in this fragment OR
// keyframe found in last fragment (track.sps) AND
// samples already appended (we already found a keyframe in this fragment) OR fragment is contiguous
if (key === true || track.sps && (samples.length || this.contiguous)) {
avcSample = { units: { units: units2, length: length }, pts: pes.pts, dts: pes.dts, key: key };
if (key) {
this.fragStats.keyFrames++;
}
// logger.log(`avcSample ${units2.length} ${length} ${pes.dts} ${key}`);
samples.push(avcSample);
track.len += length;
track.nbNalu += units2.length;
} else {
this.fragStats.dropped++;
}
if (this.firstSample && !key) {
this.fragStats.notFirstKeyframe++;
}
this.firstSample = false;
}
}
}, {
key: '_insertSampleInOrder',
value: 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);
}
}
}, {
key: '_parseAVCNALu',
value: function _parseAVCNALu(array) {
var i = 0,
len = array.byteLength,
value,
overflow,
state = 0;
var units = [],
unit,
unitType,
lastUnitStart,
lastUnitType;
//logger.log('PES:' + Hex.hexDump(array));
while (i < len) {
value = array[i++];
// finding 3 or 4-byte start codes (00 00 01 OR 00 00 00 01)
switch (state) {
case 0:
if (value === 0) {
state = 1;
}
break;
case 1:
if (value === 0) {
state = 2;
} else {
state = 0;
}
break;
case 2:
case 3:
if (value === 0) {
state = 3;
} else if (value === 1 && i < len) {
unitType = array[i] & 0x1f;
//logger.log('find NALU @ offset:' + i + ',type:' + unitType);
if (lastUnitStart) {
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 {
// 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) {
var track = this._avcTrack,
samples = track.samples;
//logger.log('first NALU found with overflow:' + overflow);
if (samples.length) {
var lastavcSample = samples[samples.length - 1],
lastUnits = lastavcSample.units.units,
lastUnit = lastUnits[lastUnits.length - 1],
tmp = new Uint8Array(lastUnit.data.byteLength + overflow);
tmp.set(lastUnit.data, 0);
tmp.set(array.subarray(0, overflow), lastUnit.data.byteLength);
lastUnit.data = tmp;
lastavcSample.units.length += overflow;
track.len += overflow;
}
}
}
lastUnitStart = i;
lastUnitType = unitType;
state = 0;
} else {
state = 0;
}
break;
default:
break;
}
}
if (lastUnitStart) {
unit = { data: array.subarray(lastUnitStart, len), type: lastUnitType };
units.push(unit);
//logger.log('pushing NALU, type/size:' + unit.type + '/' + unit.data.byteLength);
}
return units;
}
/**
* remove Emulation Prevention bytes from a RBSP
*/
}, {
key: 'discardEPB',
value: function discardEPB(data) {
var length = data.byteLength,
EPBPositions = [],
i = 1,
newLength,
newData;
// 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
newLength = length - EPBPositions.length;
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;
}
}, {
key: '_parseAACPES',
value: function _parseAACPES(pes) {
var track = this._aacTrack,
data = pes.data,
pts = pes.pts,
startOffset = 0,
duration = this._duration,
audioCodec = this.audioCodec,
aacOverFlow = this.aacOverFlow,
lastAacPTS = this.lastAacPTS,
config,
frameLength,
frameDuration,
frameIndex,
offset,
headerLength,
stamp,
len,
aacSample;
if (aacOverFlow) {
var tmp = new Uint8Array(aacOverFlow.byteLength + data.byteLength);
tmp.set(aacOverFlow, 0);
tmp.set(data, aacOverFlow.byteLength);
//logger.log(`AAC: append overflowing ${aacOverFlow.byteLength} bytes to beginning of new PES`);
data = tmp;
}
// look for ADTS header (0xFFFx)
for (offset = startOffset, len = data.length; offset < len - 1; offset++) {
if (data[offset] === 0xff && (data[offset + 1] & 0xf0) === 0xf0) {
break;
}
}
// if ADTS header does not start straight from the beginning of the PES payload, raise an error
if (offset) {
var reason, 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;
}
this.observer.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.FRAG_PARSING_ERROR, fatal: fatal, reason: reason });
if (fatal) {
return;
}
}
config = _adts2.default.getAudioConfig(this.observer, data, offset, audioCodec);
if (track.audiosamplerate !== config.samplerate || track.codec !== config.codec) {
track.config = config.config;
track.audiosamplerate = config.samplerate;
track.channelCount = config.channelCount;
track.codec = config.codec;
track.duration = duration;
_logger.logger.log('parsed codec:' + track.codec + ',rate:' + config.samplerate + ',nb channel:' + config.channelCount);
}
frameIndex = 0;
frameDuration = 1024 * 90000 / track.audiosamplerate;
// if last AAC frame is overflowing, we should ensure timestamps are contiguous:
// first sample PTS should be equal to last sample PTS + frameDuration
if (aacOverFlow && lastAacPTS) {
var newPTS = lastAacPTS + frameDuration;
if (Math.abs(newPTS - pts) > 1) {
_logger.logger.log('AAC: align PTS for overlapping frames by ' + Math.round((newPTS - pts) / 90));
pts = newPTS;
}
}
while (offset + 5 < len) {
// The protection skip bit tells us if we have 2 bytes of CRC data at the end of the ADTS header
headerLength = !!(data[offset + 1] & 0x01) ? 7 : 9;
// retrieve frame size
frameLength = (data[offset + 3] & 0x03) << 11 | data[offset + 4] << 3 | (data[offset + 5] & 0xE0) >>> 5;
frameLength -= headerLength;
//stamp = pes.pts;
if (frameLength > 0 && offset + headerLength + frameLength <= len) {
stamp = pts + frameIndex * frameDuration;
//logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}/${(stamp/90).toFixed(0)}`);
aacSample = { unit: data.subarray(offset + headerLength, offset + headerLength + frameLength), pts: stamp, dts: stamp };
track.samples.push(aacSample);
track.len += frameLength;
offset += frameLength + headerLength;
frameIndex++;
// look for ADTS header (0xFFFx)
for (; offset < len - 1; offset++) {
if (data[offset] === 0xff && (data[offset + 1] & 0xf0) === 0xf0) {
break;
}
}
} else {
break;
}
}
if (offset < len) {
aacOverFlow = data.subarray(offset, len);
//logger.log(`AAC: overflow detected:${len-offset}`);
} else {
aacOverFlow = null;
}
this.aacOverFlow = aacOverFlow;
this.lastAacPTS = stamp;
}
}, {
key: '_parseMPEGPES',
value: function _parseMPEGPES(pes) {
var data = pes.data;
var pts = pes.pts;
var length = data.length;
var frameIndex = 0;
var offset = 0;
var parsed;
while (offset < length && (parsed = this._parseMpeg(data, offset, length, frameIndex++, pts)) > 0) {
offset += parsed;
}
}
}, {
key: '_onMpegFrame',
value: function _onMpegFrame(data, bitRate, sampleRate, channelCount, frameIndex, pts) {
var frameDuration = 1152 / sampleRate * 1000;
var stamp = pts + frameIndex * frameDuration;
var track = this._aacTrack;
track.config = [];
track.channelCount = channelCount;
track.audiosamplerate = sampleRate;
track.duration = this._duration;
track.samples.push({ unit: data, pts: stamp, dts: stamp });
track.len += data.length;
}
}, {
key: '_onMpegNoise',
value: function _onMpegNoise(data) {
_logger.logger.warn('mpeg audio has noise: ' + data.length + ' bytes');
}
}, {
key: '_parseMpeg',
value: function _parseMpeg(data, start, end, frameIndex, pts) {
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];
if (start + 2 > end) {
return -1; // we need at least 2 bytes to detect sync pattern
}
if (data[start] === 0xFF || (data[start + 1] & 0xE0) === 0xE0) {
// Using http://www.datavoyage.com/mpgscript/mpeghdr.htm as a reference
if (start + 24 > end) {
return -1;
}
var headerB = data[start + 1] >> 3 & 3;
var headerC = data[start + 1] >> 1 & 3;
var headerE = data[start + 2] >> 4 & 15;
var headerF = data[start + 2] >> 2 & 3;
var headerG = !!(data[start + 2] & 2);
if (headerB !== 1 && headerE !== 0 && headerE !== 15 && headerF !== 3) {
var columnInBitrates = headerB === 3 ? 3 - headerC : headerC === 3 ? 3 : 4;
var bitRate = BitratesMap[columnInBitrates * 14 + headerE - 1] * 1000;
var columnInSampleRates = headerB === 3 ? 0 : headerB === 2 ? 1 : 2;
var sampleRate = SamplingRateMap[columnInSampleRates * 3 + headerF];
var padding = headerG ? 1 : 0;
var channelCount = data[start + 3] >> 6 === 3 ? 1 : 2; // If bits of channel mode are `11` then it is a single channel (Mono)
var frameLength = headerC === 3 ? (headerB === 3 ? 12 : 6) * bitRate / sampleRate + padding << 2 : (headerB === 3 ? 144 : 72) * bitRate / sampleRate + padding | 0;
if (start + frameLength > end) {
return -1;
}
if (this._onMpegFrame) {
this._onMpegFrame(data.subarray(start, start + frameLength), bitRate, sampleRate, channelCount, frameIndex, pts);
}
return frameLength;
}
}
// noise or ID3, trying to skip
var offset = start + 2;
while (offset < end) {
if (data[offset - 1] === 0xFF && (data[offset] & 0xE0) === 0xE0) {
// sync pattern is found
if (this._onMpegNoise) {
this._onMpegNoise(data.subarray(start, offset - 1));
}
return offset - start - 1;
}
offset++;
}
return -1;
}
}, {
key: '_parseID3PES',
value: function _parseID3PES(pes) {
this._id3Track.samples.push(pes);
}
}], [{
key: 'probe',
value: function probe(data) {
// a TS fragment should contain at least 3 TS packets, a PAT, a PMT, and one PID, each starting with 0x47
return data.length >= 3 * 188 && data[0] === 0x47 && data[188] === 0x47 && data[2 * 188] === 0x47;
}
}]);
return TSDemuxer;
}();
exports.default = TSDemuxer;
},{"../errors":20,"../events":22,"../utils/logger":38,"../utils/polyfill":39,"./adts":13,"./exp-golomb":17}],20:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var ErrorTypes = exports.ErrorTypes = {
// Identifier for a network error (loading error / timeout ...)
NETWORK_ERROR: 'networkError',
// Identifier for a media Error (video/parsing/mediasource error)
MEDIA_ERROR: 'mediaError',
// Identifier for all other errors
OTHER_ERROR: 'otherError'
};
var ErrorDetails = exports.ErrorDetails = {
// Identifier for a manifest load error - data: { url : faulty URL, response : XHR response}
MANIFEST_LOAD_ERROR: 'manifestLoadError',
// Identifier for a manifest load timeout - data: { url : faulty URL, response : XHR response}
MANIFEST_LOAD_TIMEOUT: 'manifestLoadTimeOut',
// Identifier for a manifest parsing error - data: { url : faulty URL, reason : error reason}
MANIFEST_PARSING_ERROR: 'manifestParsingError',
// Identifier for a manifest with only incompatible codecs error - data: { url : faulty URL, reason : error reason}
MANIFEST_INCOMPATIBLE_CODECS_ERROR: 'manifestIncompatibleCodecsError',
// Identifier for playlist load error - data: { url : faulty URL, response : XHR response}
LEVEL_LOAD_ERROR: 'levelLoadError',
// Identifier for playlist load timeout - data: { url : faulty URL, response : XHR response}
LEVEL_LOAD_TIMEOUT: 'levelLoadTimeOut',
// Identifier for a level switch error - data: { level : faulty level Id, event : error description}
LEVEL_SWITCH_ERROR: 'levelSwitchError',
// Identifier for fragment load error - data: { frag : fragment object, response : XHR response}
FRAG_LOAD_ERROR: 'fragLoadError',
// Identifier for fragment loop loading error - data: { frag : fragment object}
FRAG_LOOP_LOADING_ERROR: 'fragLoopLoadingError',
// Identifier for fragment load timeout error - data: { frag : fragment object}
FRAG_LOAD_TIMEOUT: 'fragLoadTimeOut',
// Identifier for a fragment decryption error event - data: parsing error description
FRAG_DECRYPT_ERROR: 'fragDecryptError',
// Identifier for a fragment parsing error event - data: parsing error description
FRAG_PARSING_ERROR: 'fragParsingError',
// Identifier for decrypt key load error - data: { frag : fragment object, response : XHR response}
KEY_LOAD_ERROR: 'keyLoadError',
// Identifier for decrypt key load timeout error - data: { frag : fragment object}
KEY_LOAD_TIMEOUT: 'keyLoadTimeOut',
// Triggered when an exception occurs while adding a sourceBuffer to MediaSource - data : { err : exception , mimeType : mimeType }
BUFFER_ADD_CODEC_ERROR: 'bufferAddCodecError',
// Identifier for a buffer append error - data: append error description
BUFFER_APPEND_ERROR: 'bufferAppendError',
// Identifier for a buffer appending error event - data: appending error description
BUFFER_APPENDING_ERROR: 'bufferAppendingError',
// Identifier for a buffer stalled error event
BUFFER_STALLED_ERROR: 'bufferStalledError',
// Identifier for a buffer full event
BUFFER_FULL_ERROR: 'bufferFullError',
// Identifier for a buffer seek over hole event
BUFFER_SEEK_OVER_HOLE: 'bufferSeekOverHole',
// Identifier for a buffer nudge on stall (playback is stuck although currentTime is in a buffered area)
BUFFER_NUDGE_ON_STALL: 'bufferNudgeOnStall',
// Identifier for an internal exception happening inside hls.js while handling an event
INTERNAL_EXCEPTION: 'internalException'
};
},{}],21:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _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; }; }(); /*
*
* All objects in the event handling chain should inherit from this class
*
*/
var _logger = require('./utils/logger');
var _errors = require('./errors');
var _events = require('./events');
var _events2 = _interopRequireDefault(_events);
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"); } }
var EventHandler = function () {
function EventHandler(hls) {
_classCallCheck(this, EventHandler);
this.hls = hls;
this.onEvent = this.onEvent.bind(this);
for (var _len = arguments.length, events = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
events[_key - 1] = arguments[_key];
}
this.handledEvents = events;
this.useGenericHandler = true;
this.registerListeners();
}
_createClass(EventHandler, [{
key: 'destroy',
value: function destroy() {
this.unregisterListeners();
}
}, {
key: 'isEventHandler',
value: function isEventHandler() {
return _typeof(this.handledEvents) === 'object' && this.handledEvents.length && typeof this.onEvent === 'function';
}
}, {
key: 'registerListeners',
value: function registerListeners() {
if (this.isEventHandler()) {
this.handledEvents.forEach(function (event) {
if (event === 'hlsEventGeneric') {
throw new Error('Forbidden event name: ' + event);
}
this.hls.on(event, this.onEvent);
}.bind(this));
}
}
}, {
key: 'unregisterListeners',
value: function unregisterListeners() {
if (this.isEventHandler()) {
this.handledEvents.forEach(function (event) {
this.hls.off(event, this.onEvent);
}.bind(this));
}
}
/**
* arguments: event (string), data (any)
*/
}, {
key: 'onEvent',
value: function onEvent(event, data) {
this.onEventGeneric(event, data);
}
}, {
key: 'onEventGeneric',
value: function onEventGeneric(event, data) {
var eventToFunction = function eventToFunction(event, data) {
var funcName = 'on' + event.replace('hls', '');
if (typeof this[funcName] !== 'function') {
throw new Error('Event ' + event + ' has no generic handler in this ' + this.constructor.name + ' class (tried ' + funcName + ')');
}
return this[funcName].bind(this, data);
};
try {
eventToFunction.call(this, event, data).call();
} catch (err) {
_logger.logger.error('internal error happened while processing ' + event + ':' + err.message);
this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.OTHER_ERROR, details: _errors.ErrorDetails.INTERNAL_EXCEPTION, fatal: false, event: event, err: err });
}
}
}]);
return EventHandler;
}();
exports.default = EventHandler;
},{"./errors":20,"./events":22,"./utils/logger":38}],22:[function(require,module,exports){
'use strict';
module.exports = {
// fired by api when new player instance created - data: { instance }
PLAYER_CREATED: 'hlsPlayerCreated',
// fired by api when player instance gets destroyed - data: { instance }
PLAYER_DESTROYED: 'hlsPlayerDestroyed',
// fired before MediaSource is attaching to media element - data: { media }
MEDIA_ATTACHING: 'hlsMediaAttaching',
// fired when MediaSource has been succesfully attached to media element - data: { }
MEDIA_ATTACHED: 'hlsMediaAttached',
// fired before detaching MediaSource from media element - data: { }
MEDIA_DETACHING: 'hlsMediaDetaching',
// fired when MediaSource has been detached from media element - data: { }
MEDIA_DETACHED: 'hlsMediaDetached',
// fired when we buffer is going to be resetted
BUFFER_RESET: 'hlsBufferReset',
// fired when we know about the codecs that we need buffers for to push into - data: {tracks : { container, codec, levelCodec, initSegment, metadata }}
BUFFER_CODECS: 'hlsBufferCodecs',
// fired when we append a segment to the buffer - data: { segment: segment object }
BUFFER_APPENDING: 'hlsBufferAppending',
// fired when the stream is finished and we want to notify the media buffer that there will be no more data
BUFFER_EOS: 'hlsBufferEos',
// fired when the media buffer should be flushed - data {startOffset, endOffset}
BUFFER_FLUSHING: 'hlsBufferFlushing',
// fired when the media has been flushed
BUFFER_FLUSHED: 'hlsBufferFlushed',
// fired to signal that a manifest loading starts - data: { url : manifestURL}
MANIFEST_LOADING: 'hlsManifestLoading',
// fired after manifest has been loaded - data: { levels : [available quality levels] , url : manifestURL, stats : { trequest, tfirst, tload, mtime}}
MANIFEST_LOADED: 'hlsManifestLoaded',
// fired after manifest has been parsed - data: { levels : [available quality levels] , firstLevel : index of first quality level appearing in Manifest}
MANIFEST_PARSED: 'hlsManifestParsed',
// fired when a level playlist loading starts - data: { url : level URL level : id of level being loaded}
LEVEL_LOADING: 'hlsLevelLoading',
// fired when a level playlist loading finishes - data: { details : levelDetails object, level : id of loaded level, stats : { trequest, tfirst, tload, mtime} }
LEVEL_LOADED: 'hlsLevelLoaded',
// fired when a level's details have been updated based on previous details, after it has been loaded. - data: { details : levelDetails object, level : id of updated level }
LEVEL_UPDATED: 'hlsLevelUpdated',
// fired when a level's PTS information has been updated after parsing a fragment - data: { details : levelDetails object, level : id of updated level, drift: PTS drift observed when parsing last fragment }
LEVEL_PTS_UPDATED: 'hlsLevelPtsUpdated',
// fired when a level switch is requested - data: { level : id of new level }
LEVEL_SWITCH: 'hlsLevelSwitch',
// fired when a fragment loading starts - data: { frag : fragment object}
FRAG_LOADING: 'hlsFragLoading',
// fired when a fragment loading is progressing - data: { frag : fragment object, { trequest, tfirst, loaded}}
FRAG_LOAD_PROGRESS: 'hlsFragLoadProgress',
// Identifier for fragment load aborting for emergency switch down - data: {frag : fragment object}
FRAG_LOAD_EMERGENCY_ABORTED: 'hlsFragLoadEmergencyAborted',
// fired when a fragment chunk loading is completed - data: { frag : fragment object, payload : fragment payload}
FRAG_CHUNK_LOADED: 'hlsFragChunkLoaded',
// fired when a fragment loading is completed - data: { frag : fragment object, payload : fragment payload, stats : { trequest, tfirst, tload, length}}
FRAG_LOADED: 'hlsFragLoaded',
// fired when Init Segment has been extracted from fragment - data: { moov : moov MP4 box, codecs : codecs found while parsing fragment}
FRAG_PARSING_INIT_SEGMENT: 'hlsFragParsingInitSegment',
// fired when parsing sei text is completed - data: { samples : [ sei samples pes ] }
FRAG_PARSING_USERDATA: 'hlsFragParsingUserdata',
// fired when parsing id3 is completed - data: { samples : [ id3 samples pes ] }
FRAG_PARSING_METADATA: 'hlsFragParsingMetadata',
// fired when data have been extracted from fragment - data: { data1 : moof MP4 box or TS fragments, data2 : mdat MP4 box or null}
FRAG_PARSING_DATA: 'hlsFragParsingData',
// fired when fragment parsing is completed - data: undefined
FRAG_PARSED: 'hlsFragParsed',
// fired when there are skipped frames in the beginning of frag
FRAG_STATISTICS: 'hlsFragStatistics',
// fired when fragment remuxed MP4 boxes have all been appended into SourceBuffer - data: { frag : fragment object, stats : { trequest, tfirst, tload, tparsed, tbuffered, length} }
FRAG_BUFFERED: 'hlsFragBuffered',
// fired when fragment matching with current media position is changing - data : { frag : fragment object }
FRAG_CHANGED: 'hlsFragChanged',
// fired when fragment chunks passed to media buffer
FRAG_APPENDING: 'hlsFragAppending',
// fired when fragment appended to media buffer
FRAG_APPENDED: 'hlsFragAppended',
// Identifier for a FPS drop event - data: {curentDropped, currentDecoded, totalDroppedFrames}
FPS_DROP: 'hlsFpsDrop',
//triggered when FPS drop triggers auto level capping - data: {level, droppedlevel}
FPS_DROP_LEVEL_CAPPING: 'hlsFpsDropLevelCapping',
// Identifier for an error event - data: { type : error type, details : error details, fatal : if true, hls.js cannot/will not try to recover, if false, hls.js will try to recover,other error specific data}
ERROR: 'hlsError',
// fired when hls.js instance starts destroying. Different from MEDIA_DETACHED as one could want to detach and reattach a media to the instance of hls.js to handle mid-rolls for example
DESTROYING: 'hlsDestroying',
// fired when a decrypt key loading starts - data: { frag : fragment object}
KEY_LOADING: 'hlsKeyLoading',
// fired when a decrypt key loading is completed - data: { frag : fragment object, payload : key payload, stats : { trequest, tfirst, tload, length}}
KEY_LOADED: 'hlsKeyLoaded',
// fired upon stream controller state transitions - data: {previousState, nextState}
STREAM_STATE_TRANSITION: 'hlsStreamStateTransition',
DEMUXER_QUEUE_EMPTY: 'hlsDemuxerQueueEmpty',
// fired when playback is stalled on low/high buffer
BUF_STATISTICS: 'hlsBufStatistics'
};
},{}],23:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* AAC helper
*/
var AAC = function () {
function AAC() {
_classCallCheck(this, AAC);
}
_createClass(AAC, null, [{
key: "getSilentFrame",
value: function getSilentFrame(channelCount) {
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]);
}
return null;
}
}]);
return AAC;
}();
exports.default = AAC;
},{}],24:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* Buffer Helper class, providing methods dealing buffer length retrieval
*/
var BufferHelper = function () {
function BufferHelper() {
_classCallCheck(this, BufferHelper);
}
_createClass(BufferHelper, null, [{
key: "isBuffered",
value: function isBuffered(media, position) {
if (media) {
var buffered = media.buffered;
for (var i = 0; i < buffered.length; i++) {
if (position >= buffered.start(i) && position <= buffered.end(i)) {
return true;
}
}
}
return false;
}
}, {
key: "bufferInfo",
value: function bufferInfo(media, pos, maxHoleDuration) {
if (media) {
var vbuffered = media.buffered,
buffered = [],
i;
for (i = 0; i < vbuffered.length; i++) {
buffered.push({ start: vbuffered.start(i), end: vbuffered.end(i) });
}
return this.bufferedInfo(buffered, pos, maxHoleDuration);
} else {
return { len: 0, start: 0, end: 0, nextStart: undefined };
}
}
}, {
key: "bufferedInfo",
value: function bufferedInfo(buffered, pos, maxHoleDuration) {
var buffered2 = [],
// bufferStart and bufferEnd are buffer boundaries around current video position
bufferLen,
bufferStart,
bufferEnd,
bufferStartNext,
i;
// 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;
}
});
// 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 (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]);
}
}
for (i = 0, bufferLen = 0, bufferStart = bufferEnd = pos; i < buffered2.length; i++) {
var start = buffered2[i].start,
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, end: bufferEnd, nextStart: bufferStartNext };
}
}]);
return BufferHelper;
}();
exports.default = BufferHelper;
},{}],25:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
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; }; }(); /**
* Level Helper class, providing methods dealing with playlist sliding and drift
*/
var _logger = require('../utils/logger');
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var LevelHelper = function () {
function LevelHelper() {
_classCallCheck(this, LevelHelper);
}
_createClass(LevelHelper, null, [{
key: 'isLive',
value: function isLive(level, levels) {
return !!(level !== undefined && levels && levels[level] && levels[level].details && levels[level].details.live);
}
}, {
key: 'canMerge',
value: function canMerge(oldDetails, newDetails) {
var _LevelHelper$probeDet = LevelHelper.probeDetails(oldDetails, newDetails),
start = _LevelHelper$probeDet.start,
end = _LevelHelper$probeDet.end;
return end >= start;
}
}, {
key: 'probeDetails',
value: function probeDetails(oldDetails, newDetails) {
function getTimes(details) {
var startTS = 0,
endTS = 0,
i = 0;
for (; i < details.fragments.length; i++) {
if (details.fragments[i].programDateTime) {
break;
}
}
if (i !== details.fragments.length) {
startTS = endTS = details.fragments[i].programDateTime.getTime();
for (var j = 0; j < details.fragments.length - 1; j++) {
if (j < i) {
startTS -= details.fragments[j].duration * 1000;
} else {
endTS += details.fragments[j].duration * 1000;
}
}
return { start: startTS, end: endTS };
}
}
var start = Math.max(oldDetails.startSN, newDetails.startSN) - newDetails.startSN;
var end = Math.min(oldDetails.endSN, newDetails.endSN) - newDetails.startSN;
var delta = newDetails.startSN - oldDetails.startSN;
if (end >= start) {
return { start: start, end: end, delta: delta };
}
var oldTimes = getTimes(oldDetails),
newTimes = getTimes(newDetails);
if (oldTimes && newTimes && oldTimes.start <= newTimes.start && oldTimes.end >= newTimes.start) {
start = delta = 0;
end = Math.min(newDetails.fragments.length, oldDetails.fragments.length) - 1;
var ts = oldTimes.start;
// 0.1 sec grace
while (newTimes.start - ts > 100) {
ts += oldDetails.fragments[delta++].duration * 1000;
end--;
}
return { start: start, end: end, delta: delta };
}
return { start: 1, end: 0, delta: 0 };
}
}, {
key: 'mergeDetails',
value: function mergeDetails(oldDetails, newDetails) {
var oldfragments = oldDetails.fragments,
newfragments = newDetails.fragments,
ccOffset = 0,
PTSFrag;
var _LevelHelper$probeDet2 = LevelHelper.probeDetails(oldDetails, newDetails),
start = _LevelHelper$probeDet2.start,
end = _LevelHelper$probeDet2.end,
delta = _LevelHelper$probeDet2.delta;
// check if old/new playlists have fragments in common
if (end < start) {
newDetails.PTSKnown = false;
return;
}
// loop through overlapping SN and update startPTS , cc, and duration if any found
for (var i = start; i <= end; i++) {
var oldFrag = oldfragments[delta + i],
newFrag = newfragments[i];
ccOffset = oldFrag.cc - newFrag.cc;
if (!isNaN(oldFrag.startPTS)) {
newFrag.start = newFrag.startPTS = oldFrag.startPTS;
newFrag.endPTS = oldFrag.endPTS;
newFrag.duration = oldFrag.duration;
newFrag.PTSDTSshift = oldFrag.PTSDTSshift;
newFrag.lastGop = oldFrag.lastGop;
PTSFrag = newFrag;
}
if (oldFrag.firstGop) {
newFrag.firstGop = oldFrag.firstGop;
}
}
if (ccOffset) {
_logger.logger.log('discontinuity sliding from playlist, take drift into account');
for (i = 0; i < newfragments.length; i++) {
newfragments[i].cc += ccOffset;
}
}
// if at least one fragment contains PTS info, recompute PTS information for all fragments
if (PTSFrag) {
LevelHelper.updateFragPTS(newDetails, PTSFrag.sn, PTSFrag.startPTS, PTSFrag.endPTS, PTSFrag.PTSDTSshift || 0, PTSFrag.lastGop);
} 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
if (delta >= 0 && delta < oldfragments.length) {
// adjust start by sliding offset
var sliding = oldfragments[delta].start;
for (i = 0; i < newfragments.length; i++) {
newfragments[i].start += sliding;
}
}
}
// if we are here, it means we have fragments overlapping between
// old and new level. reliable PTS info is thus relying on old level
newDetails.PTSKnown = oldDetails.PTSKnown;
return;
}
}, {
key: 'updateFragPTS',
value: function updateFragPTS(details, sn, startPTS, endPTS, PTSDTSshift, lastGop) {
var fragIdx, fragments, frag, i;
// exit if sn out of range
if (sn < details.startSN || sn > details.endSN) {
return 0;
}
fragIdx = sn - details.startSN;
fragments = details.fragments;
frag = fragments[fragIdx];
if (!isNaN(frag.startPTS)) {
startPTS = Math.min(startPTS, frag.startPTS);
endPTS = Math.max(endPTS, frag.endPTS);
}
var drift = startPTS - frag.start;
frag.start = frag.startPTS = startPTS;
frag.endPTS = endPTS;
frag.duration = endPTS - startPTS;
frag.PTSDTSshift = PTSDTSshift || 0;
if (lastGop) {
frag.lastGop = lastGop;
}
// adjust fragment PTS/duration from seqnum-1 to frag 0
for (i = fragIdx; i > 0; i--) {
LevelHelper.updatePTS(fragments, i, i - 1);
}
// adjust fragment PTS/duration from seqnum to last frag
for (i = fragIdx; i < fragments.length - 1; i++) {
LevelHelper.updatePTS(fragments, i, i + 1);
}
details.PTSKnown = true;
//logger.log(` frag start/end:${startPTS.toFixed(3)}/${endPTS.toFixed(3)}`);
return drift;
}
}, {
key: 'updatePTS',
value: function updatePTS(fragments, fromIdx, toIdx) {
var fragFrom = fragments[fromIdx],
fragTo = fragments[toIdx],
fragToPTS = fragTo.startPTS;
// if we know startPTS[toIdx]
if (!isNaN(fragToPTS)) {
// update fragment duration.
// it helps to fix drifts between playlist reported duration and fragment real duration
if (toIdx > fromIdx) {
fragFrom.duration = fragToPTS - fragFrom.start;
if (fragFrom.duration < 0) {
_logger.logger.warn('negative duration computed for frag ' + fragFrom.sn + ',level ' + fragFrom.level + ', there should be some duration drift between playlist and fragment!');
}
} else {
fragTo.duration = fragFrom.start - fragToPTS;
if (fragTo.duration < 0) {
_logger.logger.warn('negative duration computed for frag ' + fragTo.sn + ',level ' + fragTo.level + ', there should be some duration drift between playlist and fragment!');
}
}
} else {
// we dont know startPTS[toIdx]
if (toIdx > fromIdx) {
fragTo.start = fragFrom.start + fragFrom.duration;
} else {
fragTo.start = fragFrom.start - fragTo.duration;
}
}
if (toIdx > fromIdx) {
if (!fragTo.PTSDTSshift) {
fragTo.PTSDTSshift = fragFrom.PTSDTSshift || 0;
}
if (fragFrom.lastGop) {
fragTo.firstGop = fragFrom.lastGop;
}
}
}
}]);
return LevelHelper;
}();
exports.default = LevelHelper;
},{"../utils/logger":38}],26:[function(require,module,exports){
/**
* HLS interface
*/
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
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 _events = require('./events');
var _events2 = _interopRequireDefault(_events);
var _errors = require('./errors');
var _playlistLoader = require('./loader/playlist-loader');
var _playlistLoader2 = _interopRequireDefault(_playlistLoader);
var _fragmentLoader = require('./loader/fragment-loader');
var _fragmentLoader2 = _interopRequireDefault(_fragmentLoader);
var _abrController = require('./controller/abr-controller');
var _abrController2 = _interopRequireDefault(_abrController);
var _bufferController = require('./controller/buffer-controller');
var _bufferController2 = _interopRequireDefault(_bufferController);
var _capLevelController = require('./controller/cap-level-controller');
var _capLevelController2 = _interopRequireDefault(_capLevelController);
var _streamController = require('./controller/stream-controller');
var _streamController2 = _interopRequireDefault(_streamController);
var _levelController = require('./controller/level-controller');
var _levelController2 = _interopRequireDefault(_levelController);
var _timelineController = require('./controller/timeline-controller');
var _timelineController2 = _interopRequireDefault(_timelineController);
var _fpsController = require('./controller/fps-controller');
var _fpsController2 = _interopRequireDefault(_fpsController);
var _logger = require('./utils/logger');
var _xhrLoader = require('./utils/xhr-loader');
var _xhrLoader2 = _interopRequireDefault(_xhrLoader);
var _events3 = require('events');
var _events4 = _interopRequireDefault(_events3);
var _keyLoader = require('./loader/key-loader');
var _keyLoader2 = _interopRequireDefault(_keyLoader);
var _cues = require('./utils/cues');
var _cues2 = _interopRequireDefault(_cues);
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"); } }
var Hls = function () {
_createClass(Hls, null, [{
key: 'isSupported',
value: function isSupported() {
// Opera Mini for Android with enabled optimizations breaks m3u8 files
function isOperaMini() {
var checkOpera = /\bOPR\b\/(\d+)/i;
var checkChrome = / Chrome\/(\d+)(\.\d+)+.* Safari\/\d+(\.\d+)+/;
var opera,
ua = window.navigator && window.navigator.userAgent;
var res = checkChrome.exec(ua);
if (res) {
opera = checkOpera.exec(ua);
return ua.match(/Android/) && (opera ? opera[1] : undefined) < 25;
}
return false;
}
if (isOperaMini()) {
return false;
}
return window.MediaSource && window.MediaSource.isTypeSupported('video/mp4; codecs="avc1.42E01E,mp4a.40.2"');
}
}, {
key: 'isIe',
value: function isIe() {
var res = void 0,
ua = typeof window !== 'undefined' && window.navigator && navigator.userAgent;
if (res = /[( ]MSIE ([6789]|10).\d[);]/.exec(ua)) {
return { browser: 'ie', version: res[1] };
}
if (res = /[( ]Trident\/\d+(\.\d)+.*rv:(\d\d)(\.\d)+[);]/.exec(ua)) {
return { browser: 'ie', version: res[2] };
}
}
}, {
key: 'version',
get: function get() {
// replaced with browserify-versionify transform
return '0.6.1-129';
}
}, {
key: 'Events',
get: function get() {
return _events2.default;
}
}, {
key: 'ErrorTypes',
get: function get() {
return _errors.ErrorTypes;
}
}, {
key: 'ErrorDetails',
get: function get() {
return _errors.ErrorDetails;
}
}, {
key: 'DefaultConfig',
get: function get() {
if (!Hls.defaultConfig) {
Hls.defaultConfig = {
autoStartLoad: true,
debug: false,
capLevelOnFPSDrop: false,
capLevelToPlayerSize: false,
maxBufferLength: 40,
maxBufferSize: 60 * 1000 * 1000,
maxBufferHole: 0.5,
maxSeekHole: 2,
lowBufferWatchdogPeriod: 0,
highBufferWatchdogPeriod: 3,
nudgeOffset: 0.1,
nudgeMaxRetry: 5,
maxFragLookUpTolerance: 0.2,
liveSyncDurationCount: 3,
liveMaxLatencyDurationCount: Infinity,
liveSyncDuration: undefined,
liveMaxLatencyDuration: undefined,
maxMaxBufferLength: 40,
enableWorker: !Hls.isIe(),
enableSoftwareAES: true,
manifestLoadingTimeOut: 20000,
manifestLoadingMaxRetry: 4,
manifestLoadingRetryDelay: 1000,
levelLoadingTimeOut: 20000,
levelLoadingMaxRetry: 4,
levelLoadingRetryDelay: 1000,
fragLoadingTimeOut: 20000,
fragLoadingMaxRetry: 6,
fragLoadingRetryDelay: 1000,
fragLoadingLoopThreshold: 1000,
clearLevelDetailsOnSwitching: false,
startFragPrefetch: false,
fpsDroppedMonitoringPeriod: 5000,
fpsDroppedMonitoringThreshold: 0.2,
appendErrorMaxRetry: 3,
loader: _xhrLoader2.default,
fLoader: undefined,
pLoader: undefined,
abrController: _abrController2.default,
bufferController: _bufferController2.default,
capLevelController: _capLevelController2.default,
fpsController: _fpsController2.default,
streamController: _streamController2.default,
timelineController: _timelineController2.default,
cueHandler: _cues2.default,
enableCEA708Captions: true,
enableMP2TPassThrough: false,
stretchShortVideoTrack: false
};
}
return Hls.defaultConfig;
},
set: function set(defaultConfig) {
Hls.defaultConfig = defaultConfig;
}
}]);
function Hls() {
var config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
_classCallCheck(this, Hls);
var defaultConfig = Hls.DefaultConfig;
if ((config.liveSyncDurationCount || config.liveMaxLatencyDurationCount) && (config.liveSyncDuration || config.liveMaxLatencyDuration)) {
throw new Error('Illegal hls.js config: don\'t mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration');
}
for (var prop in defaultConfig) {
if (prop in config) {
continue;
}
config[prop] = defaultConfig[prop];
}
if (config.liveMaxLatencyDurationCount !== undefined && config.liveMaxLatencyDurationCount <= config.liveSyncDurationCount) {
throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be gt "liveSyncDurationCount"');
}
if (config.liveMaxLatencyDuration !== undefined && (config.liveMaxLatencyDuration <= config.liveSyncDuration || config.liveSyncDuration === undefined)) {
throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be gt "liveSyncDuration"');
}
(0, _logger.enableLogs)(config.debug);
this.config = config;
// observer setup
var observer = this.observer = new _events4.default();
observer.trigger = function trigger(event) {
for (var _len = arguments.length, data = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
data[_key - 1] = arguments[_key];
}
observer.emit.apply(observer, [event, event].concat(data));
};
observer.off = function off(event) {
for (var _len2 = arguments.length, data = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
data[_key2 - 1] = arguments[_key2];
}
observer.removeListener.apply(observer, [event].concat(data));
};
this.on = observer.on.bind(observer);
this.off = observer.off.bind(observer);
this.trigger = observer.trigger.bind(observer);
this.playlistLoader = new _playlistLoader2.default(this);
this.fragmentLoader = new _fragmentLoader2.default(this);
this.levelController = new _levelController2.default(this);
this.abrController = new config.abrController(this);
this.bufferController = new config.bufferController(this);
this.capLevelController = new config.capLevelController(this);
this.fpsController = new config.fpsController(this);
this.streamController = new config.streamController(this);
this.timelineController = new config.timelineController(this);
this.keyLoader = new _keyLoader2.default(this);
Hls.api.players.push(this);
Hls.api.emit(_events2.default.PLAYER_CREATED, this);
}
_createClass(Hls, [{
key: 'destroy',
value: function destroy() {
_logger.logger.log('destroy');
this.trigger(_events2.default.DESTROYING);
this.detachMedia();
this.playlistLoader.destroy();
this.fragmentLoader.destroy();
this.levelController.destroy();
this.abrController.destroy();
this.bufferController.destroy();
this.capLevelController.destroy();
this.fpsController.destroy();
this.streamController.destroy();
this.timelineController.destroy();
this.keyLoader.destroy();
this.url = null;
this.observer.removeAllListeners();
var globalId = Hls.api.players.indexOf(this);
if (globalId < 0) {
return;
}
Hls.api.players.splice(globalId, 1);
Hls.api.emit(_events2.default.PLAYER_DESTROYED, this);
}
}, {
key: 'attachMedia',
value: function attachMedia(media) {
_logger.logger.log('attachMedia');
this.media = media;
this.trigger(_events2.default.MEDIA_ATTACHING, { media: media });
}
}, {
key: 'detachMedia',
value: function detachMedia() {
_logger.logger.log('detachMedia');
this.trigger(_events2.default.MEDIA_DETACHING);
this.media = null;
}
}, {
key: 'loadSource',
value: function loadSource(url) {
_logger.logger.log('loadSource:' + url);
this.url = url;
// when attaching to a source URL, trigger a playlist load
this.trigger(_events2.default.MANIFEST_LOADING, { url: url });
}
}, {
key: 'startLoad',
value: function startLoad() {
var startPosition = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
_logger.logger.log('startLoad(' + startPosition + ')');
this.levelController.startLoad();
this.streamController.startLoad(startPosition);
}
}, {
key: 'stopLoad',
value: function stopLoad() {
_logger.logger.log('stopLoad');
this.levelController.stopLoad();
this.streamController.stopLoad();
}
}, {
key: 'clearLevelDetails',
value: function clearLevelDetails() {
_logger.logger.log('clearing level details');
this.levelController.clearLevelDetails();
}
}, {
key: 'swapAudioCodec',
value: function swapAudioCodec() {
_logger.logger.log('swapAudioCodec');
this.streamController.swapAudioCodec();
}
}, {
key: 'recoverMediaError',
value: function recoverMediaError() {
_logger.logger.log('recoverMediaError');
var media = this.media;
this.detachMedia();
this.attachMedia(media);
}
/** Return all quality levels **/
}, {
key: 'levels',
get: function get() {
return this.levelController.levels;
}
/** Return current playback quality level **/
}, {
key: 'currentLevel',
get: function get() {
return this.streamController.currentLevel;
}
/* set quality level immediately (-1 for automatic level selection) */
,
set: function set(newLevel) {
_logger.logger.log('set currentLevel:' + newLevel);
this.loadLevel = newLevel;
this.streamController.immediateLevelSwitch();
}
/** Return next playback quality level (quality level of next fragment) **/
}, {
key: 'nextLevel',
get: function get() {
return this.streamController.nextLevel;
}
/* set quality level for next fragment (-1 for automatic level selection) */
,
set: function set(newLevel) {
_logger.logger.log('set nextLevel:' + newLevel);
this.levelController.manualLevel = newLevel;
this.streamController.nextLevelSwitch();
}
/** Return the quality level of current/last loaded fragment **/
}, {
key: 'loadLevel',
get: function get() {
return this.levelController.level;
}
/* set quality level for current/next loaded fragment (-1 for automatic level selection) */
,
set: function set(newLevel) {
_logger.logger.log('set loadLevel:' + newLevel);
this.levelController.manualLevel = newLevel;
}
/** Return the quality level of next loaded fragment **/
}, {
key: 'nextLoadLevel',
get: function get() {
return this.levelController.nextLoadLevel;
}
/** set quality level of next loaded fragment **/
,
set: function set(level) {
this.levelController.nextLoadLevel = level;
}
/** Return first level (index of first level referenced in manifest)
**/
}, {
key: 'firstLevel',
get: function get() {
return this.levelController.firstLevel;
}
/** set first level (index of first level referenced in manifest)
**/
,
set: function set(newLevel) {
_logger.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)
**/
}, {
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)
**/
,
set: function set(newLevel) {
_logger.logger.log('set startLevel:' + newLevel);
this.levelController.startLevel = newLevel;
}
/** Return the capping/max level value that could be used by automatic level selection algorithm **/
}, {
key: 'autoLevelCapping',
get: function get() {
return this.abrController.autoLevelCapping;
}
/** set the capping/max level value that could be used by automatic level selection algorithm **/
,
set: function set(newLevel) {
_logger.logger.log('set autoLevelCapping:' + newLevel);
this.abrController.autoLevelCapping = newLevel;
}
/* check if we are in automatic level selection mode */
}, {
key: 'autoLevelEnabled',
get: function get() {
return this.levelController.manualLevel === -1;
}
/* return manual level */
}, {
key: 'manualLevel',
get: function get() {
return this.levelController.manualLevel;
}
}]);
return Hls;
}();
Hls.api = new _events4.default();
Hls.api.players = [];
exports.default = Hls;
},{"./controller/abr-controller":2,"./controller/buffer-controller":3,"./controller/cap-level-controller":4,"./controller/fps-controller":5,"./controller/level-controller":6,"./controller/stream-controller":7,"./controller/timeline-controller":8,"./errors":20,"./events":22,"./loader/fragment-loader":27,"./loader/key-loader":28,"./loader/playlist-loader":29,"./utils/cues":37,"./utils/logger":38,"./utils/xhr-loader":41,"events":44}],27:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
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 _events = require('../events');
var _events2 = _interopRequireDefault(_events);
var _eventHandler = require('../event-handler');
var _eventHandler2 = _interopRequireDefault(_eventHandler);
var _errors = require('../errors');
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; } /*
* Fragment Loader
*/
var FragmentLoader = function (_EventHandler) {
_inherits(FragmentLoader, _EventHandler);
function FragmentLoader(hls) {
_classCallCheck(this, FragmentLoader);
return _possibleConstructorReturn(this, (FragmentLoader.__proto__ || Object.getPrototypeOf(FragmentLoader)).call(this, hls, _events2.default.FRAG_LOADING));
}
_createClass(FragmentLoader, [{
key: 'destroy',
value: function destroy() {
if (this.loader) {
this.loader.destroy();
this.loader = null;
}
this.firstChunk = true;
_eventHandler2.default.prototype.destroy.call(this);
}
}, {
key: 'onFragLoading',
value: function onFragLoading(data) {
var frag = data.frag;
this.frag = frag;
this.frag.loaded = 0;
this.firstChunk = true;
var config = this.hls.config;
frag.loader = this.loader = typeof config.fLoader !== 'undefined' ? new config.fLoader(config) : new config.loader(config);
this.loader.load(frag.url, 'arraybuffer', this.loadsuccess.bind(this), this.loaderror.bind(this), this.loadtimeout.bind(this), config.fragLoadingTimeOut, 1, 0, this.loadprogress.bind(this), frag, this.loadchunk.bind(this));
}
}, {
key: 'loadchunk',
value: function loadchunk(event, stats) {
var payload = event.currentTarget.response;
payload.first = this.firstChunk;
this.firstChunk = false;
this.hls.trigger(_events2.default.FRAG_CHUNK_LOADED, { payload: payload, frag: this.frag, stats: stats });
}
}, {
key: 'loadsuccess',
value: function loadsuccess(event, stats) {
var payload = event.currentTarget.response;
payload.final = true;
stats.length = payload.byteLength;
this.hls.trigger(_events2.default.FRAG_LOADED, { frag: this.frag, stats: stats });
// we cannot add new property to xhr response object in IE
this.loadchunk({ currentTarget: { response: payload } }, stats);
this.firstChunk = true;
// detach fragment loader on load success
this.frag.loader = undefined;
}
}, {
key: 'loaderror',
value: function loaderror(event) {
if (this.loader) {
this.loader.abort();
}
this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.NETWORK_ERROR, details: _errors.ErrorDetails.FRAG_LOAD_ERROR, fatal: false, frag: this.frag, response: event });
}
}, {
key: 'loadtimeout',
value: function loadtimeout() {
if (this.loader) {
this.loader.abort();
}
this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.NETWORK_ERROR, details: _errors.ErrorDetails.FRAG_LOAD_TIMEOUT, fatal: false, frag: this.frag });
}
}, {
key: 'loadprogress',
value: function loadprogress(stats) {
this.frag.loaded = stats.loaded;
this.hls.trigger(_events2.default.FRAG_LOAD_PROGRESS, { frag: this.frag, stats: stats });
}
}]);
return FragmentLoader;
}(_eventHandler2.default);
exports.default = FragmentLoader;
},{"../errors":20,"../event-handler":21,"../events":22}],28:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
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 _events = require('../events');
var _events2 = _interopRequireDefault(_events);
var _eventHandler = require('../event-handler');
var _eventHandler2 = _interopRequireDefault(_eventHandler);
var _errors = require('../errors');
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; } /*
* Decrypt key Loader
*/
var KeyLoader = function (_EventHandler) {
_inherits(KeyLoader, _EventHandler);
function KeyLoader(hls) {
_classCallCheck(this, KeyLoader);
var _this = _possibleConstructorReturn(this, (KeyLoader.__proto__ || Object.getPrototypeOf(KeyLoader)).call(this, hls, _events2.default.KEY_LOADING));
_this.decryptkey = null;
_this.decrypturl = null;
return _this;
}
_createClass(KeyLoader, [{
key: 'destroy',
value: function destroy() {
if (this.loader) {
this.loader.destroy();
this.loader = null;
}
_eventHandler2.default.prototype.destroy.call(this);
}
}, {
key: 'onKeyLoading',
value: function onKeyLoading(data) {
var frag = this.frag = data.frag,
decryptdata = frag.decryptdata,
uri = decryptdata.uri;
// if uri is different from previous one or if decrypt key not retrieved yet
if (uri !== this.decrypturl || this.decryptkey === null) {
var config = this.hls.config;
frag.loader = this.loader = new config.loader(config);
this.decrypturl = uri;
this.decryptkey = null;
frag.loader.load(uri, 'arraybuffer', this.loadsuccess.bind(this), this.loaderror.bind(this), this.loadtimeout.bind(this), config.fragLoadingTimeOut, config.fragLoadingMaxRetry, config.fragLoadingRetryDelay, this.loadprogress.bind(this), frag);
} else if (this.decryptkey) {
// we already loaded this key, return it
decryptdata.key = this.decryptkey;
this.hls.trigger(_events2.default.KEY_LOADED, { frag: frag });
}
}
}, {
key: 'loadsuccess',
value: function loadsuccess(event) {
var frag = this.frag;
this.decryptkey = frag.decryptdata.key = new Uint8Array(event.currentTarget.response);
// detach fragment loader on load success
frag.loader = undefined;
this.hls.trigger(_events2.default.KEY_LOADED, { frag: frag });
}
}, {
key: 'loaderror',
value: function loaderror(event) {
if (this.loader) {
this.loader.abort();
}
this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.NETWORK_ERROR, details: _errors.ErrorDetails.KEY_LOAD_ERROR, fatal: false, frag: this.frag, response: event.currentTarget });
}
}, {
key: 'loadtimeout',
value: function loadtimeout() {
if (this.loader) {
this.loader.abort();
}
this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.NETWORK_ERROR, details: _errors.ErrorDetails.KEY_LOAD_TIMEOUT, fatal: false, frag: this.frag });
}
}, {
key: 'loadprogress',
value: function loadprogress() {}
}]);
return KeyLoader;
}(_eventHandler2.default);
exports.default = KeyLoader;
},{"../errors":20,"../event-handler":21,"../events":22}],29:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
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 _events = require('../events');
var _events2 = _interopRequireDefault(_events);
var _eventHandler = require('../event-handler');
var _eventHandler2 = _interopRequireDefault(_eventHandler);
var _errors = require('../errors');
var _url = require('../utils/url');
var _url2 = _interopRequireDefault(_url);
var _attrList = require('../utils/attr-list');
var _attrList2 = _interopRequireDefault(_attrList);
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; } /**
* Playlist Loader
*/
//import {logger} from '../utils/logger';
var PlaylistLoader = function (_EventHandler) {
_inherits(PlaylistLoader, _EventHandler);
function PlaylistLoader(hls) {
_classCallCheck(this, PlaylistLoader);
return _possibleConstructorReturn(this, (PlaylistLoader.__proto__ || Object.getPrototypeOf(PlaylistLoader)).call(this, hls, _events2.default.MANIFEST_LOADING, _events2.default.LEVEL_LOADING));
}
_createClass(PlaylistLoader, [{
key: 'destroy',
value: function destroy() {
if (this.loader) {
this.loader.destroy();
this.loader = null;
}
this.url = this.id = null;
_eventHandler2.default.prototype.destroy.call(this);
}
}, {
key: 'onManifestLoading',
value: function onManifestLoading(data) {
this.load(data.url, null);
}
}, {
key: 'onLevelLoading',
value: function onLevelLoading(data) {
this.load(data.url, data.level, data.id);
}
}, {
key: 'reloadCurrentRequests',
value: function reloadCurrentRequests() {
// we only reload manifest requests, level requests will be retried anyway
if (this.loading && this.loader && this.id === null) {
this.loader.abort();
this.loading = false;
this.load(this.url, this.id, this.id2);
}
}
}, {
key: 'load',
value: function load(url, id1, id2) {
var config = this.hls.config,
retry,
timeout,
retryDelay;
if (this.loading && this.loader) {
if (this.url === url && this.id === id1 && this.id2 === id2) {
// same request than last pending one, don't do anything
return;
} else {
// one playlist load request is pending, but with different params, abort it before loading new playlist
this.loader.abort();
}
}
this.url = url;
this.id = id1;
this.id2 = id2;
if (this.id === null) {
retry = config.manifestLoadingMaxRetry;
timeout = config.manifestLoadingTimeOut;
retryDelay = config.manifestLoadingRetryDelay;
} else {
retry = config.levelLoadingMaxRetry;
timeout = config.levelLoadingTimeOut;
retryDelay = config.levelLoadingRetryDelay;
}
this.loader = typeof config.pLoader !== 'undefined' ? new config.pLoader(config) : new config.loader(config);
this.loading = true;
this.loader.load(url, '', this.loadsuccess.bind(this), this.loaderror.bind(this), this.loadtimeout.bind(this), timeout, retry, retryDelay);
}
}, {
key: 'resolve',
value: function resolve(url, baseUrl) {
return _url2.default.buildAbsoluteURL(baseUrl, url);
}
}, {
key: 'parseMasterPlaylist',
value: function parseMasterPlaylist(string, baseurl) {
var levels = [],
result = void 0;
// https://regex101.com is your friend
var re = /#EXT-X-STREAM-INF:([^\n\r]*)[\r\n]+([^\r\n]+)/g;
while ((result = re.exec(string)) != null) {
var level = {};
var attrs = level.attrs = new _attrList2.default(result[1]);
level.url = this.resolve(result[2], baseurl);
var resolution = attrs.decimalResolution('RESOLUTION');
if (resolution) {
level.width = resolution.width;
level.height = resolution.height;
}
level.bitrate = attrs.decimalInteger('AVERAGE-BANDWIDTH') || attrs.decimalInteger('BANDWIDTH');
level.name = attrs.NAME;
var closedCaptions = attrs.enumeratedString('CLOSED-CAPTIONS');
if (closedCaptions) {
level.closedCaptions = closedCaptions;
}
var codecs = attrs.CODECS;
if (codecs) {
codecs = codecs.split(',');
for (var i = 0; i < codecs.length; i++) {
var codec = codecs[i];
if (codec.indexOf('avc1') !== -1) {
level.videoCodec = this.avc1toavcoti(codec);
} else {
level.audioCodec = codec;
}
}
}
levels.push(level);
}
return levels;
}
/**
* Utility method for parseLevelPlaylist to create an initialization vector for a given segment
* @returns {Uint8Array}
*/
}, {
key: 'createInitializationVector',
value: 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 {*} - an object to be applied as a fragment's decryptdata
*/
}, {
key: 'fragmentDecryptdataFromLevelkey',
value: function fragmentDecryptdataFromLevelkey(levelkey, segmentNumber) {
var decryptdata = levelkey;
if (levelkey && levelkey.method && levelkey.uri && !levelkey.iv) {
decryptdata = this.cloneObj(levelkey);
decryptdata.iv = this.createInitializationVector(segmentNumber);
}
return decryptdata;
}
}, {
key: 'avc1toavcoti',
value: function avc1toavcoti(codec) {
var result,
avcdata = codec.split('.');
if (avcdata.length > 2) {
result = avcdata.shift() + '.';
result += parseInt(avcdata.shift()).toString(16);
result += ('000' + parseInt(avcdata.shift()).toString(16)).substr(-4);
} else {
result = codec;
}
return result;
}
}, {
key: 'cloneObj',
value: function cloneObj(obj) {
return JSON.parse(JSON.stringify(obj));
}
}, {
key: 'parseLevelPlaylist',
value: function parseLevelPlaylist(string, baseurl, id) {
var currentSN = 0,
fragdecryptdata,
totalduration = 0,
level = { url: baseurl, fragments: [], live: true, startSN: 0 },
levelkey = { method: null, key: null, iv: null, uri: null },
cc = 0,
programDateTime = null,
frag = null,
result,
regexp,
byteRangeEndOffset,
byteRangeStartOffset,
tagList = [];
regexp = /(?:#EXT-X-(MEDIA-SEQUENCE):(\d+))|(?:#EXT-X-(TARGETDURATION):(\d+))|(?:#EXT-X-(KEY):(.*)[\r\n]+([^#|\r\n]+)?)|(?:#EXT(INF):([\d\.]+)[^\r\n]*([\r\n]+[^#|\r\n]+)?)|(?:#EXT-X-(BYTERANGE):([\d]+[@[\d]*)]*[\r\n]+([^#|\r\n]+)?|(?:#EXT-X-(ENDLIST))|(?:#EXT-X-(DIS)CONTINUITY))|(?:#EXT-X-(PROGRAM-DATE-TIME):(.*))|(?:#EXT-X-(VERSION):(.*))|(?:#(.*):(.*))|(?:#(.*))/g;
while ((result = regexp.exec(string)) !== null) {
result.shift();
result = result.filter(function (n) {
return n !== undefined;
});
switch (result[0]) {
case 'MEDIA-SEQUENCE':
currentSN = level.startSN = parseInt(result[1]);
break;
case 'TARGETDURATION':
level.targetduration = parseFloat(result[1]);
break;
case 'VERSION':
break;
case 'EXTM3U':
break;
case 'ENDLIST':
level.live = false;
break;
case 'DIS':
cc++;
tagList.push(result.map(function (e) {
return (' ' + e).slice(1);
}));
break;
case 'BYTERANGE':
var params = result[1].split('@');
if (params.length === 1) {
byteRangeStartOffset = byteRangeEndOffset;
} else {
byteRangeStartOffset = parseInt(params[1]);
}
byteRangeEndOffset = parseInt(params[0]) + byteRangeStartOffset;
if (frag && !frag.url) {
frag.byteRangeStartOffset = byteRangeStartOffset;
frag.byteRangeEndOffset = byteRangeEndOffset;
frag.url = this.resolve(result[2], baseurl);
tagList.push(result.map(function (e) {
return (' ' + e).slice(1);
}));
}
break;
case 'INF':
var duration = parseFloat(result[1]);
if (!isNaN(duration)) {
var sn = currentSN++;
fragdecryptdata = this.fragmentDecryptdataFromLevelkey(levelkey, sn);
var url = result[2] ? this.resolve(result[2], baseurl) : null;
tagList.push(result.map(function (e) {
return (' ' + e).slice(1);
}));
frag = { url: url, duration: duration, start: totalduration, sn: sn, level: id, cc: cc, byteRangeStartOffset: byteRangeStartOffset, byteRangeEndOffset: byteRangeEndOffset, decryptdata: fragdecryptdata, programDateTime: programDateTime, tagList: tagList, PTSDTSshift: 0 };
level.fragments.push(frag);
totalduration += duration;
byteRangeStartOffset = null;
programDateTime = null;
tagList = [];
}
break;
case 'KEY':
// https://tools.ietf.org/html/draft-pantos-http-live-streaming-08#section-3.4.4
var decryptparams = result[1];
var keyAttrs = new _attrList2.default(decryptparams);
var decryptmethod = keyAttrs.enumeratedString('METHOD'),
decrypturi = keyAttrs.URI,
decryptiv = keyAttrs.hexadecimalInteger('IV');
if (decryptmethod) {
levelkey = { method: null, key: null, iv: null, uri: null };
if (decrypturi && decryptmethod === 'AES-128') {
levelkey.method = decryptmethod;
// URI to get the key
levelkey.uri = this.resolve(decrypturi, baseurl);
levelkey.key = null;
// Initialization Vector (IV)
levelkey.iv = decryptiv;
}
}
//issue #425, applying url and decrypt data in instances where EXT-KEY immediately follow EXT-INF
if (frag && !frag.url && result.length >= 3) {
frag.url = this.resolve(result[2], baseurl);
//we have not moved onto another segment, we are still parsing one
fragdecryptdata = this.fragmentDecryptdataFromLevelkey(levelkey, currentSN - 1);
frag.decryptdata = fragdecryptdata;
tagList.push(result.map(function (e) {
return (' ' + e).slice(1);
}));
}
break;
case 'PROGRAM-DATE-TIME':
programDateTime = new Date(Date.parse(result[1]));
tagList.push(result.map(function (e) {
return (' ' + e).slice(1);
}));
break;
default:
tagList.push(result.map(function (e) {
return (' ' + e).slice(1);
}));
break;
}
}
//logger.log('found ' + level.fragments.length + ' fragments');
if (frag && !frag.url) {
level.fragments.pop();
totalduration -= frag.duration;
}
level.totalduration = totalduration;
level.averagetargetduration = totalduration / level.fragments.length;
level.endSN = currentSN - 1;
return level;
}
}, {
key: 'loadsuccess',
value: function loadsuccess(event, stats) {
var target = event.currentTarget,
string = target.responseText,
url = target.responseURL,
id = this.id,
id2 = this.id2,
hls = this.hls,
levels;
this.loading = false;
// 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 = this.url;
}
stats.tload = performance.now();
stats.mtime = new Date(target.getResponseHeader('Last-Modified'));
if (string.indexOf('#EXTM3U') === 0) {
if (string.indexOf('#EXTINF:') > 0) {
// 1 level playlist
// if first request, fire manifest loaded event, level will be reloaded afterwards
// (this is to have a uniform logic for 1 level/multilevel playlists)
if (this.id === null) {
hls.trigger(_events2.default.MANIFEST_LOADED, { levels: [{ url: url }], url: url, stats: stats });
} else {
var levelDetails = this.parseLevelPlaylist(string, url, id);
stats.tparsed = performance.now();
hls.trigger(_events2.default.LEVEL_LOADED, { details: levelDetails, level: id, id: id2, stats: stats });
}
} else {
levels = this.parseMasterPlaylist(string, url);
// multi level playlist, parse level info
if (levels.length) {
hls.trigger(_events2.default.MANIFEST_LOADED, { levels: levels, url: url, stats: stats });
} else {
hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.NETWORK_ERROR, details: _errors.ErrorDetails.MANIFEST_PARSING_ERROR, fatal: true, url: url, reason: 'no level found in manifest' });
}
}
} else {
hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.NETWORK_ERROR, details: _errors.ErrorDetails.MANIFEST_PARSING_ERROR, fatal: true, url: url, reason: 'no EXTM3U delimiter' });
}
}
}, {
key: 'loaderror',
value: function loaderror(event) {
var details, fatal;
if (this.id === null) {
details = _errors.ErrorDetails.MANIFEST_LOAD_ERROR;
fatal = true;
} else {
details = _errors.ErrorDetails.LEVEL_LOAD_ERROR;
fatal = false;
}
if (this.loader) {
this.loader.abort();
}
this.loading = false;
this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.NETWORK_ERROR, details: details, fatal: fatal, url: this.url, loader: this.loader, response: event.currentTarget, level: this.id, id: this.id2 });
}
}, {
key: 'loadtimeout',
value: function loadtimeout() {
var details, fatal;
if (this.id === null) {
details = _errors.ErrorDetails.MANIFEST_LOAD_TIMEOUT;
fatal = true;
} else {
details = _errors.ErrorDetails.LEVEL_LOAD_TIMEOUT;
fatal = false;
}
if (this.loader) {
this.loader.abort();
}
this.loading = false;
this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.NETWORK_ERROR, details: details, fatal: fatal, url: this.url, loader: this.loader, level: this.id, id: this.id2 });
}
}]);
return PlaylistLoader;
}(_eventHandler2.default);
exports.default = PlaylistLoader;
},{"../errors":20,"../event-handler":21,"../events":22,"../utils/attr-list":33,"../utils/url":40}],30:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* Generate MP4 Box
*/
var UINT32_MAX = Math.pow(2, 32) - 1;
//import Hex from '../utils/hex';
var MP4 = function () {
function MP4() {
_classCallCheck(this, MP4);
}
_createClass(MP4, null, [{
key: 'init',
value: function init() {
MP4.types = {
avc1: [], // codingname
avcC: [],
btrt: [],
dinf: [],
dref: [],
esds: [],
ftyp: [],
hdlr: [],
mdat: [],
mdhd: [],
mdia: [],
mfhd: [],
minf: [],
moof: [],
moov: [],
mp4a: [],
'.mp3': [],
mvex: [],
mvhd: [],
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]);
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));
}
}, {
key: 'box',
value: function box(type) {
var payload = Array.prototype.slice.call(arguments, 1),
size = 8,
i = payload.length,
len = i,
result;
// calculate the total size we need to allocate
while (i--) {
size += payload[i].byteLength;
}
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;
}
}, {
key: 'hdlr',
value: function hdlr(type) {
return MP4.box(MP4.types.hdlr, MP4.HDLR_TYPES[type]);
}
}, {
key: 'mdat',
value: function mdat(data) {
return MP4.box(MP4.types.mdat, data);
}
}, {
key: 'mdhd',
value: function mdhd(timescale, duration) {
duration *= timescale;
return MP4.box(MP4.types.mdhd, new Uint8Array([0x00, // version 0
0x00, 0x00, 0x00, // flags
0x00, 0x00, 0x00, 0x02, // creation_time
0x00, 0x00, 0x00, 0x03, // modification_time
timescale >> 24 & 0xFF, timescale >> 16 & 0xFF, timescale >> 8 & 0xFF, timescale & 0xFF, // timescale
duration >> 24, duration >> 16 & 0xFF, duration >> 8 & 0xFF, duration & 0xFF, // duration
0x55, 0xc4, // 'und' language (undetermined)
0x00, 0x00]));
}
}, {
key: 'mdia',
value: function mdia(track) {
return MP4.box(MP4.types.mdia, MP4.mdhd(track.timescale, track.duration), MP4.hdlr(track.type), MP4.minf(track));
}
}, {
key: 'mfhd',
value: 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]));
}
}, {
key: 'minf',
value: 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));
}
}
}, {
key: 'moof',
value: 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
*/
}, {
key: 'moov',
value: function moov(tracks) {
var i = tracks.length,
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)));
}
}, {
key: 'mvex',
value: function mvex(tracks) {
var i = tracks.length,
boxes = [];
while (i--) {
boxes[i] = MP4.trex(tracks[i]);
}
return MP4.box.apply(null, [MP4.types.mvex].concat(boxes));
}
}, {
key: 'mvhd',
value: function mvhd(timescale, duration) {
duration *= timescale;
var bytes = new Uint8Array([0x00, // version 0
0x00, 0x00, 0x00, // flags
0x00, 0x00, 0x00, 0x01, // creation_time
0x00, 0x00, 0x00, 0x02, // modification_time
timescale >> 24 & 0xFF, timescale >> 16 & 0xFF, timescale >> 8 & 0xFF, timescale & 0xFF, // timescale
duration >> 24 & 0xFF, duration >> 16 & 0xFF, duration >> 8 & 0xFF, duration & 0xFF, // duration
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);
}
}, {
key: 'sdtp',
value: function sdtp(track) {
var samples = track.samples || [],
bytes = new Uint8Array(4 + samples.length),
flags,
i;
// 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);
}
}, {
key: 'stbl',
value: 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));
}
}, {
key: 'avc1',
value: function avc1(track) {
var sps = [],
pps = [],
i,
data,
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.concat(Array.prototype.slice.call(data)); // SPS
}
// 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"
width = track.width,
height = track.height;
//console.log('avcc:' + Hex.hexDump(avcc));
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
);
}
}, {
key: 'esds',
value: 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
}
}, {
key: 'mp4a',
value: function mp4a(track) {
var audiosamplerate = track.audiosamplerate;
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
audiosamplerate >> 8 & 0xFF, audiosamplerate & 0xff, //
0x00, 0x00]), MP4.box(MP4.types.esds, MP4.esds(track)));
}
}, {
key: 'mp3',
value: function mp3(track) {
var audiosamplerate = track.audiosamplerate;
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
audiosamplerate >> 8 & 0xFF, audiosamplerate & 0xff, //
0x00, 0x00]));
}
}, {
key: 'stsd',
value: 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));
}
}
}, {
key: 'tkhd',
value: function tkhd(track) {
var id = track.id,
duration = track.duration * track.timescale,
width = track.width,
height = track.height;
return MP4.box(MP4.types.tkhd, new Uint8Array([0x00, // version 0
0x00, 0x00, 0x07, // flags
0x00, 0x00, 0x00, 0x00, // creation_time
0x00, 0x00, 0x00, 0x00, // modification_time
id >> 24 & 0xFF, id >> 16 & 0xFF, id >> 8 & 0xFF, id & 0xFF, // track_ID
0x00, 0x00, 0x00, 0x00, // reserved
duration >> 24, duration >> 16 & 0xFF, duration >> 8 & 0xFF, duration & 0xFF, // duration
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
]));
}
}, {
key: 'traf',
value: function traf(track, baseMediaDecodeTime) {
var sampleDependencyTable = MP4.sdtp(track),
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])), MP4.box(MP4.types.tfdt, new Uint8Array([0x01, // version 1
0x00, 0x00, 0x00, // flags
upperWordBaseMediaDecodeTime >>> 24 & 0xFF, upperWordBaseMediaDecodeTime >>> 16 & 0xFF, upperWordBaseMediaDecodeTime >>> 8 & 0xFF, upperWordBaseMediaDecodeTime & 0xFF, lowerWordBaseMediaDecodeTime >>> 24 & 0xFF, 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
*/
}, {
key: 'trak',
value: function trak(track) {
track.duration = track.duration || 0xffffffff;
return MP4.box(MP4.types.trak, MP4.tkhd(track), MP4.mdia(track));
}
}, {
key: 'trex',
value: 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
]));
}
}, {
key: 'trun',
value: function trun(track, offset) {
var samples = track.samples || [],
len = samples.length,
arraylen = 12 + 16 * len,
array = new Uint8Array(arraylen),
i,
sample,
duration,
size,
flags,
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);
}
}, {
key: 'initSegment',
value: function initSegment(tracks) {
if (!MP4.types) {
MP4.init();
}
var movie = MP4.moov(tracks),
result;
result = new Uint8Array(MP4.FTYP.byteLength + movie.byteLength);
result.set(MP4.FTYP);
result.set(movie, MP4.FTYP.byteLength);
return result;
}
}]);
return MP4;
}();
exports.default = MP4;
},{}],31:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
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; }; }(); /**
* fMP4 remuxer
*/
var _aac = require('../helper/aac');
var _aac2 = _interopRequireDefault(_aac);
var _events = require('../events');
var _events2 = _interopRequireDefault(_events);
var _logger = require('../utils/logger');
var _mp4Generator = require('../remux/mp4-generator');
var _mp4Generator2 = _interopRequireDefault(_mp4Generator);
var _errors = require('../errors');
require('../utils/polyfill');
var _browser = require('../utils/browser');
var _browser2 = _interopRequireDefault(_browser);
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"); } }
var MP4Remuxer = function () {
function MP4Remuxer(observer, config, typeSupported) {
_classCallCheck(this, MP4Remuxer);
this.observer = observer;
this.config = config;
this.typeSupported = typeSupported;
this.ISGenerated = false;
this.PES2MP4SCALEFACTOR = 4;
this.PES_TIMESCALE = 90000;
this.MP4_TIMESCALE = this.PES_TIMESCALE / this.PES2MP4SCALEFACTOR;
}
_createClass(MP4Remuxer, [{
key: 'destroy',
value: function destroy() {}
}, {
key: 'insertDiscontinuity',
value: function insertDiscontinuity() {
this._initPTS = this._initDTS = undefined;
}
}, {
key: 'switchLevel',
value: function switchLevel() {
this.ISGenerated = false;
this.nextAacPts = this.nextAvcDts = undefined;
}
}, {
key: 'remux',
value: function remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurate, data, flush, stats) {
// dummy
data = null;
// generate Init Segment if needed
if (!this.ISGenerated) {
this.generateIS(audioTrack, videoTrack, timeOffset);
}
if (this.ISGenerated) {
// Purposefully remuxing audio before video, so that remuxVideo can use nextAacPts, which is
// calculated in remuxAudio.
//logger.log('nb AAC samples:' + audioTrack.samples.length);
if (audioTrack.samples.length) {
var audioData = this.remuxAudio(audioTrack, timeOffset, contiguous, accurate, stats);
//logger.log('nb AVC samples:' + videoTrack.samples.length);
if (videoTrack.samples.length) {
var audioTrackLength = void 0,
audioStartPTS = void 0;
if (audioData) {
audioStartPTS = audioData.startPTS;
audioTrackLength = audioData.endPTS - audioStartPTS;
}
this.remuxVideo(videoTrack, timeOffset, contiguous, audioTrackLength, audioStartPTS, flush, stats);
} else if (!contiguous) {
this.nextAvcDts = undefined;
}
} else {
var videoData = void 0;
//logger.log('nb AVC samples:' + videoTrack.samples.length);
if (videoTrack.samples.length) {
videoData = this.remuxVideo(videoTrack, timeOffset, contiguous, undefined, undefined, flush, stats);
}
if (videoData && audioTrack.codec) {
this.remuxEmptyAudio(audioTrack, timeOffset, contiguous, videoData, stats);
}
}
}
//logger.log('nb ID3 samples:' + audioTrack.samples.length);
if (id3Track.samples.length) {
this.remuxID3(id3Track, timeOffset);
}
//logger.log('nb ID3 samples:' + audioTrack.samples.length);
if (textTrack.samples.length) {
this.remuxText(textTrack, timeOffset);
}
}
}, {
key: 'generateIS',
value: function generateIS(audioTrack, videoTrack, timeOffset) {
var observer = this.observer,
audioSamples = audioTrack.samples,
videoSamples = videoTrack.samples,
pesTimeScale = this.PES_TIMESCALE,
tracks = {},
data = { tracks: tracks, unique: false },
computePTSDTS = this._initPTS === undefined,
initPTS,
initDTS;
if (computePTSDTS) {
initPTS = initDTS = Infinity;
}
if (audioTrack.config && audioSamples.length) {
audioTrack.timescale = audioTrack.audiosamplerate;
// MP4 duration (track duration in seconds multiplied by timescale) is coded on 32 bits
// we know that each AAC sample contains 1024 frames....
// in order to avoid overflowing the 32 bit counter for large duration, we use smaller timescale (timescale/gcd)
// we just need to ensure that AAC sample duration will still be an integer (will be 1024/gcd)
if (audioTrack.timescale * audioTrack.duration > Math.pow(2, 32)) {
var greatestCommonDivisor = function greatestCommonDivisor(a, b) {
if (!b) {
return a;
}
return greatestCommonDivisor(b, a % b);
};
audioTrack.timescale = audioTrack.audiosamplerate / greatestCommonDivisor(audioTrack.audiosamplerate, audioTrack.isAAC ? 1024 : 1152);
}
_logger.logger.log('audio mp4 timescale :' + audioTrack.timescale);
var container = 'audio/mp4';
if (!audioTrack.isAAC) {
if (this.typeSupported.mpeg) {
// Chrome and Safari
container = 'audio/mpeg';
audioTrack.codec = '';
} else if (this.typeSupported.mp3 === true) {
// Firefox
audioTrack.codec = 'mp3';
}
}
tracks.audio = {
container: container,
codec: audioTrack.codec,
initSegment: !audioTrack.isAAC && this.typeSupported.mpeg ? new Uint8Array() : _mp4Generator2.default.initSegment([audioTrack]),
metadata: {
channelCount: audioTrack.channelCount
}
};
if (computePTSDTS) {
// remember first PTS of this demuxing context. for audio, PTS = DTS
initPTS = initDTS = audioSamples[0].pts - pesTimeScale * timeOffset;
}
}
if (videoTrack.sps && videoTrack.pps && videoSamples.length) {
videoTrack.timescale = this.MP4_TIMESCALE;
tracks.video = {
container: 'video/mp4',
codec: videoTrack.codec,
initSegment: _mp4Generator2.default.initSegment([videoTrack]),
metadata: {
width: videoTrack.width,
height: videoTrack.height
}
};
if (computePTSDTS) {
initPTS = Math.min(initPTS, videoSamples[0].pts - pesTimeScale * timeOffset);
initDTS = Math.min(initDTS, videoSamples[0].dts - pesTimeScale * timeOffset);
}
}
if (Object.keys(tracks).length) {
observer.trigger(_events2.default.FRAG_PARSING_INIT_SEGMENT, data);
this.ISGenerated = true;
if (computePTSDTS) {
this._initPTS = initPTS;
this._initDTS = initDTS;
}
} else {
observer.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.FRAG_PARSING_ERROR, fatal: false, reason: 'no audio/video samples found' });
}
}
}, {
key: 'remuxVideo',
value: function remuxVideo(track, timeOffset, contiguous, audioTrackLength, audioStartPTS, flush, stats) {
var offset = 8,
pesTimeScale = this.PES_TIMESCALE,
pes2mp4ScaleFactor = this.PES2MP4SCALEFACTOR,
mp4SampleDuration,
mdat,
moof,
firstPTS,
firstDTS,
nextDTS,
lastPTS,
lastDTS,
inputSamples = track.samples,
outputSamples = [];
// handle broken streams with PTS < DTS, tolerance up 200ms (18000 in 90kHz timescale)
var PTSDTSshift = inputSamples.reduce(function (prev, curr) {
return Math.max(Math.min(prev, curr.pts - curr.dts), -18000);
}, 0);
if (PTSDTSshift < 0) {
_logger.logger.warn('PTS < DTS detected in video samples, shifting DTS by ' + Math.round(PTSDTSshift / 90) + ' ms to overcome this issue');
for (var i = 0; i < inputSamples.length; i++) {
inputSamples[i].dts += PTSDTSshift;
}
}
contiguous |= inputSamples.length && this.nextAvcDts && Math.abs(timeOffset - this.nextAvcDts / pesTimeScale) < 0.1;
// 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
// if parsed fragment is contiguous with last one, let's use last DTS value as reference
// if not contiguous, let's use target timeOffset
var nextAvcDts = contiguous ? this.nextAvcDts : timeOffset * pesTimeScale;
// compute first DTS and last DTS, normalize them against reference value
var sample = inputSamples[0];
firstDTS = Math.max(this._PTSNormalize(sample.dts - this._initDTS, nextAvcDts), 0);
firstPTS = Math.max(this._PTSNormalize(sample.pts - this._initDTS, nextAvcDts), 0);
// check timestamp continuity (to remove inter-fragment gap/hole)
var delta = Math.round((firstDTS - nextAvcDts) / 90);
if (contiguous && delta) {
_logger.logger.log('AVC:' + Math.abs(delta) + ' ms ' + (delta > 0 ? 'hole' : 'overlapping') + ' between fragments detected');
// remove hole/gap : set DTS to next expected DTS
firstDTS = nextAvcDts;
inputSamples[0].dts = firstDTS + this._initDTS;
// offset PTS as well, ensure that PTS is smaller or equal than new DTS
firstPTS = Math.max(firstPTS - delta * 90, nextAvcDts);
inputSamples[0].pts = firstPTS + this._initDTS;
_logger.logger.log('Video/PTS/DTS adjusted: ' + firstPTS + '/' + firstDTS + ',delta:' + delta);
stats.videoGap = stats.videoGap || [];
stats.videoGap.push(delta);
}
nextDTS = firstDTS;
// compute lastPTS/lastDTS
sample = inputSamples[inputSamples.length - 1];
lastDTS = Math.max(this._PTSNormalize(sample.dts - this._initDTS, nextAvcDts), 0);
lastPTS = Math.max(this._PTSNormalize(sample.pts - this._initDTS, nextAvcDts), 0);
lastPTS = Math.max(lastPTS, lastDTS);
// 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.
if (_browser2.default.isSafari()) {
mp4SampleDuration = Math.round((lastDTS - firstDTS) / (pes2mp4ScaleFactor * (inputSamples.length - 1)));
}
// normalize all PTS/DTS now ...
for (var _i = 0; _i < inputSamples.length; _i++) {
var _sample = inputSamples[_i];
if (_browser2.default.isSafari()) {
// sample DTS is computed using a constant decoding offset (mp4SampleDuration) between samples
_sample.dts = firstDTS + _i * pes2mp4ScaleFactor * mp4SampleDuration;
} else {
// ensure sample monotonic DTS
_sample.dts = Math.max(this._PTSNormalize(_sample.dts - this._initDTS, nextAvcDts), firstDTS);
// ensure dts is a multiple of scale factor to avoid rounding issues
_sample.dts = Math.round(_sample.dts / pes2mp4ScaleFactor) * pes2mp4ScaleFactor;
}
// we normalize PTS against nextAvcDts, we also substract initDTS (some streams don't start @ PTS O)
// and we ensure that computed value is greater or equal than sample DTS
_sample.pts = Math.max(this._PTSNormalize(_sample.pts - this._initDTS, nextAvcDts), _sample.dts);
// ensure pts is a multiple of scale factor to avoid rounding issues
_sample.pts = Math.round(_sample.pts / pes2mp4ScaleFactor) * pes2mp4ScaleFactor;
}
/* concatenate the video data and construct the mdat in place
(need 8 more bytes to fill length and mpdat type) */
mdat = new Uint8Array(track.len + 4 * track.nbNalu + 8);
var view = new DataView(mdat.buffer);
view.setUint32(0, mdat.byteLength);
mdat.set(_mp4Generator2.default.types.mdat, 4);
stats.videoDurAvg = stats.videoDurStd = 0;
stats.cttsError = 0;
for (var _i2 = 0; _i2 < inputSamples.length; _i2++) {
var avcSample = inputSamples[_i2],
mp4SampleLength = 0,
compositionTimeOffset = void 0;
// convert NALU bitstream to MP4 format (prepend NALU with size field)
while (avcSample.units.units.length) {
var unit = avcSample.units.units.shift();
view.setUint32(offset, unit.data.byteLength);
offset += 4;
mdat.set(unit.data, offset);
offset += unit.data.byteLength;
mp4SampleLength += 4 + unit.data.byteLength;
}
if (!_browser2.default.isSafari()) {
// expected sample duration is the Decoding Timestamp diff of consecutive samples
if (_i2 < inputSamples.length - 1) {
mp4SampleDuration = inputSamples[_i2 + 1].dts - avcSample.dts;
} else {
var config = this.config,
lastFrameDuration = avcSample.dts - inputSamples[_i2 > 0 ? _i2 - 1 : _i2].dts;
if (config.stretchShortVideoTrack) {
// 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 the minimum of maxBufferHole and
// maxSeekHole. 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 maxBufferHole = config.maxBufferHole,
maxSeekHole = config.maxSeekHole,
gapTolerance = Math.floor(Math.min(maxBufferHole, maxSeekHole) * pesTimeScale),
deltaToFrameEnd = (audioTrackLength ? firstPTS + audioTrackLength * pesTimeScale : this.nextAacPts) - avcSample.pts;
if (deltaToFrameEnd > gapTolerance) {
// We subtract lastFrameDuration from deltaToFrameEnd to try to prevent any video
// frame overlap. maxBufferHole/maxSeekHole should be >> lastFrameDuration anyway.
mp4SampleDuration = deltaToFrameEnd - lastFrameDuration;
if (mp4SampleDuration < 0) {
mp4SampleDuration = lastFrameDuration;
}
_logger.logger.log('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;
}
}
mp4SampleDuration /= pes2mp4ScaleFactor;
compositionTimeOffset = Math.round((avcSample.pts - avcSample.dts) / pes2mp4ScaleFactor);
} else {
compositionTimeOffset = Math.max(0, mp4SampleDuration * Math.round((avcSample.pts - avcSample.dts) / (pes2mp4ScaleFactor * mp4SampleDuration)));
}
//console.log('PTS/DTS/initDTS/normPTS/normDTS/relative PTS : ${avcSample.pts}/${avcSample.dts}/${this._initDTS}/${ptsnorm}/${dtsnorm}/${(avcSample.pts/4294967296).toFixed(3)}');
outputSamples.push({
size: mp4SampleLength,
// constant duration
duration: mp4SampleDuration,
cts: compositionTimeOffset,
flags: {
isLeading: 0,
isDependedOn: 0,
hasRedundancy: 0,
degradPrio: 0,
dependsOn: avcSample.key ? 2 : 1,
isNonSync: avcSample.key ? 0 : 1
}
});
stats.videoDurAvg += mp4SampleDuration / inputSamples.length;
stats.videoDurStd += mp4SampleDuration * mp4SampleDuration / inputSamples.length;
stats.cttsError += compositionTimeOffset - Math.floor(compositionTimeOffset / mp4SampleDuration) * mp4SampleDuration;
}
stats.videoDurStd = Math.sqrt(stats.videoDurStd - stats.videoDurAvg * stats.videoDurAvg);
// next AVC sample DTS should be equal to last sample DTS + last sample duration (in PES timescale)
this.nextAvcDts = lastDTS + mp4SampleDuration * pes2mp4ScaleFactor;
track.len = 0;
track.nbNalu = 0;
if (outputSamples.length && navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {
var flags = outputSamples[0].flags;
// chrome workaround, mark first sample as being a Random Access Point to avoid sourcebuffer append issue
// https://code.google.com/p/chromium/issues/detail?id=229412
flags.dependsOn = 2;
flags.isNonSync = 0;
}
track.samples = outputSamples;
moof = _mp4Generator2.default.moof(track.sequenceNumber++, firstDTS / pes2mp4ScaleFactor, track);
track.samples = [];
var data = {
data1: moof,
data2: mdat,
startPTS: firstPTS / pesTimeScale,
endPTS: (lastPTS + pes2mp4ScaleFactor * mp4SampleDuration) / pesTimeScale,
startDTS: firstDTS / pesTimeScale,
endDTS: this.nextAvcDts / pesTimeScale,
type: 'video',
flush: flush,
nb: outputSamples.length,
dropped: stats.dropped
};
// delta PTS between audio and video
data.deltaPTS = Math.abs(data.startPTS - audioStartPTS);
this.observer.trigger(_events2.default.FRAG_PARSING_DATA, data);
return data;
}
}, {
key: 'remuxAudio',
value: function remuxAudio(track, timeOffset, contiguous, accurate, stats) {
var pesTimeScale = this.PES_TIMESCALE,
mp4timeScale = track.timescale,
pes2mp4ScaleFactor = pesTimeScale / mp4timeScale,
mp4SampleDuration = track.isAAC ? 1024 : 1152,
expectedSampleDuration = track.timescale * mp4SampleDuration / track.audiosamplerate,
rawMPEG = !track.isAAC && this.typeSupported.mpeg;
var view,
offset = rawMPEG ? 0 : 8,
aacSample,
mp4Sample,
unit,
mdat,
moof,
firstPTS,
firstDTS,
lastDTS,
pts,
dts,
ptsnorm,
dtsnorm,
samples = [],
samples0 = track.samples,
fillFrame,
newStamp;
// 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 and next expected PTS
// 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
contiguous |= samples0.length && this.nextAacPts && Math.abs(timeOffset - this.nextAacPts / pesTimeScale) < 0.1;
var nextAacPts = contiguous && this.nextAacPts !== undefined ? this.nextAacPts : timeOffset * pesTimeScale;
// 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.
var pesFrameDuration = expectedSampleDuration * pes2mp4ScaleFactor;
var nextPtsNorm = nextAacPts;
for (var i = 0; i < samples0.length; i++) {
samples0[i].ptsNorm = this._PTSNormalize(samples0[i].pts - this._initDTS, nextAacPts);
}
samples0.sort(function (a, b) {
return a.ptsNorm - b.ptsNorm;
});
// only inject/drop audio frames in case time offset is accurate
if (accurate && track.isAAC) {
for (var _i3 = 0; _i3 < samples0.length;) {
// First, let's see how far off this frame is from where we expect it to be
var sample = samples0[_i3],
ptsNorm = sample.ptsNorm,
delta = ptsNorm - nextPtsNorm;
if (Math.abs(delta) > pesFrameDuration / 2) {
stats.audioGap = stats.audioGap || [];
stats.audioGap.push(delta / 90);
}
// If we're overlapping by more than a duration, drop this sample
if (delta < -pesFrameDuration) {
_logger.logger.log('Dropping frame due to ' + Math.abs(delta / 90) + ' ms overlap.');
samples0.splice(_i3, 1);
track.len -= sample.unit.length;
// Don't touch nextPtsNorm or i
}
// Otherwise, if we're more than a frame away from where we should be, insert missing frames
else if (delta > pesFrameDuration) {
var missing = Math.round(delta / pesFrameDuration);
_logger.logger.log('Injecting ' + missing + ' frame' + (missing > 1 ? 's' : '') + ' of missing audio due to ' + Math.round(delta / 90) + ' ms gap.');
for (var j = 0; j < missing; j++) {
newStamp = nextPtsNorm + this._initDTS;
newStamp = Math.max(newStamp, this._initDTS);
fillFrame = _aac2.default.getSilentFrame(track.channelCount);
if (!fillFrame) {
_logger.logger.log('Unable to get silent frame for given audio codec; duplicating last frame instead.');
fillFrame = sample.unit.slice(0);
}
samples0.splice(_i3, 0, { unit: fillFrame, pts: newStamp, dts: newStamp });
track.len += fillFrame.length;
nextPtsNorm += pesFrameDuration;
_i3 += 1;
}
// Adjust sample to next expected pts
sample.pts = sample.dts = nextPtsNorm + this._initDTS;
nextPtsNorm += pesFrameDuration;
_i3 += 1;
}
// Otherwise, we're within half a frame duration, so just adjust pts
else {
nextPtsNorm += pesFrameDuration;
if (_i3 === 0) {
sample.pts = sample.dts = this._initDTS + nextAacPts;
} else {
sample.pts = sample.dts = samples0[_i3 - 1].pts + pesFrameDuration;
}
_i3 += 1;
}
}
}
while (samples0.length) {
aacSample = samples0.shift();
unit = aacSample.unit;
pts = aacSample.pts - this._initDTS;
dts = aacSample.dts - this._initDTS;
//logger.log(`Audio/PTS:${Math.round(pts/90)}`);
// if not first sample
if (lastDTS !== undefined) {
ptsnorm = this._PTSNormalize(pts, lastDTS);
dtsnorm = this._PTSNormalize(dts, lastDTS);
mp4Sample.duration = Math.round((dtsnorm - lastDTS) / pes2mp4ScaleFactor);
} else {
ptsnorm = this._PTSNormalize(pts, nextAacPts);
dtsnorm = this._PTSNormalize(dts, nextAacPts);
var _delta = Math.round(1000 * (ptsnorm - nextAacPts) / pesTimeScale),
numMissingFrames = 0;
// log delta
if (contiguous && _delta && track.isAAC) {
if (_delta > 0) {
numMissingFrames = Math.round((ptsnorm - nextAacPts) / pesFrameDuration);
_logger.logger.log(_delta + ' ms hole between AAC samples detected,filling it');
if (numMissingFrames > 0) {
fillFrame = _aac2.default.getSilentFrame(track.channelCount);
if (!fillFrame) {
fillFrame = unit.slice(0);
}
track.len += numMissingFrames * fillFrame.length;
}
// if we have frame overlap, overlapping for more than half a frame duraion
} else if (_delta < -12) {
// drop overlapping audio frames... browser will deal with it
_logger.logger.log(-_delta + ' ms overlapping between AAC samples detected, drop frame');
track.len -= unit.byteLength;
continue;
}
// set PTS/DTS to expected PTS/DTS
ptsnorm = dtsnorm = nextAacPts;
}
// remember first PTS of our aacSamples, ensure value is positive
firstPTS = Math.max(0, ptsnorm);
firstDTS = Math.max(0, dtsnorm);
if (track.len <= 0) {
return;
}
/* concatenate the audio data and construct the mdat in place
(need 8 more bytes to fill length and mdat type) */
if (rawMPEG) {
mdat = new Uint8Array(track.len);
} else {
mdat = new Uint8Array(track.len + 8);
view = new DataView(mdat.buffer);
view.setUint32(0, mdat.byteLength);
mdat.set(_mp4Generator2.default.types.mdat, 4);
}
for (var _i4 = 0; _i4 < numMissingFrames; _i4++) {
newStamp = ptsnorm - (numMissingFrames - _i4) * pesFrameDuration;
fillFrame = _aac2.default.getSilentFrame(track.channelCount);
if (!fillFrame) {
_logger.logger.log('Unable to get silent frame for given audio codec; duplicating this frame instead.');
fillFrame = unit.slice(0);
}
mdat.set(fillFrame, offset);
offset += fillFrame.byteLength;
mp4Sample = {
size: fillFrame.byteLength,
cts: 0,
duration: mp4SampleDuration,
flags: {
isLeading: 0,
isDependedOn: 0,
hasRedundancy: 0,
degradPrio: 0,
dependsOn: 1
}
};
samples.push(mp4Sample);
}
}
mdat.set(unit, offset);
offset += unit.byteLength;
//console.log('PTS/DTS/initDTS/normPTS/normDTS/relative PTS : ${aacSample.pts}/${aacSample.dts}/${this._initDTS}/${ptsnorm}/${dtsnorm}/${(aacSample.pts/4294967296).toFixed(3)}');
mp4Sample = {
size: unit.byteLength,
cts: 0,
duration: 0,
flags: {
isLeading: 0,
isDependedOn: 0,
hasRedundancy: 0,
degradPrio: 0,
dependsOn: 1
}
};
samples.push(mp4Sample);
lastDTS = dtsnorm;
}
var lastSampleDuration = 0;
var nbSamples = samples.length;
//set last sample duration as being identical to previous sample
if (nbSamples >= 2) {
lastSampleDuration = samples[nbSamples - 2].duration;
mp4Sample.duration = lastSampleDuration;
}
if (nbSamples) {
stats.audioDurAvg = stats.audioDurStd = 0;
for (var _i5 = 0; _i5 < nbSamples; _i5++) {
stats.audioDurAvg += samples[_i5].duration;
stats.audioDurStd += samples[_i5].duration * samples[_i5].duration;
}
stats.audioDurStd = Math.sqrt(Math.abs(stats.audioDurStd - stats.audioDurAvg * stats.audioDurAvg / nbSamples) / nbSamples);
stats.audioDurAvg /= nbSamples;
// next aac sample PTS should be equal to last sample PTS + duration
this.nextAacPts = ptsnorm + pes2mp4ScaleFactor * lastSampleDuration;
//logger.log('Audio/PTS/PTSend:' + aacSample.pts.toFixed(0) + '/' + this.nextAacDts.toFixed(0));
track.len = 0;
track.samples = samples;
if (rawMPEG) {
moof = new Uint8Array();
} else {
moof = _mp4Generator2.default.moof(track.sequenceNumber++, firstDTS / pes2mp4ScaleFactor, track);
}
track.samples = [];
var audioData = {
data1: moof,
data2: mdat,
startPTS: firstPTS / pesTimeScale,
endPTS: this.nextAacPts / pesTimeScale,
startDTS: firstDTS / pesTimeScale,
endDTS: (dtsnorm + pes2mp4ScaleFactor * lastSampleDuration) / pesTimeScale,
type: 'audio',
nb: nbSamples
};
this.observer.trigger(_events2.default.FRAG_PARSING_DATA, audioData);
return audioData;
}
return null;
}
}, {
key: 'remuxEmptyAudio',
value: function remuxEmptyAudio(track, timeOffset, contiguous, videoData, stats) {
var pesTimeScale = this.PES_TIMESCALE,
mp4timeScale = track.timescale ? track.timescale : track.audiosamplerate,
pes2mp4ScaleFactor = pesTimeScale / mp4timeScale,
startDTS = (contiguous ? this.nextAacPts : videoData.startDTS * pesTimeScale) + this._initDTS,
endDTS = videoData.endDTS * pesTimeScale + this._initDTS,
// one sample's duration value
sampleDuration = 1024,
frameDuration = pes2mp4ScaleFactor * sampleDuration,
// samples count of this segment's duration
nbSamples = Math.ceil((endDTS - startDTS) / frameDuration),
// silent frame
silentFrame = _aac2.default.getSilentFrame(track.channelCount);
// Can't remux if we can't generate a silent frame...
if (!silentFrame) {
stats.noSilentFrame = (stats.noSilentFrame | 0) + 1;
_logger.logger.trace('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.slice(0), pts: stamp, dts: stamp });
track.len += silentFrame.length;
}
track.samples = samples;
this.remuxAudio(track, timeOffset, contiguous, undefined, stats);
}
}, {
key: 'remuxID3',
value: function remuxID3(track, timeOffset) {
var length = track.samples.length,
sample;
// consume samples
if (length) {
for (var index = 0; index < length; index++) {
sample = track.samples[index];
// setting id3 pts, dts to relative time
// using this._initPTS and this._initDTS to calculate relative time
sample.pts = (sample.pts - this._initPTS) / this.PES_TIMESCALE;
sample.dts = (sample.dts - this._initDTS) / this.PES_TIMESCALE;
}
this.observer.trigger(_events2.default.FRAG_PARSING_METADATA, {
samples: track.samples
});
}
track.samples = [];
timeOffset = timeOffset;
}
}, {
key: 'remuxText',
value: function remuxText(track, timeOffset) {
track.samples.sort(function (a, b) {
return a.pts - b.pts;
});
var length = track.samples.length,
sample;
// consume samples
if (length) {
for (var index = 0; index < length; index++) {
sample = track.samples[index];
// setting text pts, dts to relative time
// using this._initPTS and this._initDTS to calculate relative time
sample.pts = (sample.pts - this._initPTS) / this.PES_TIMESCALE;
}
this.observer.trigger(_events2.default.FRAG_PARSING_USERDATA, {
samples: track.samples
});
}
track.samples = [];
timeOffset = timeOffset;
}
}, {
key: '_PTSNormalize',
value: function _PTSNormalize(value, reference) {
var offset;
if (reference === undefined) {
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;
}
}, {
key: 'passthrough',
get: function get() {
return false;
}
}]);
return MP4Remuxer;
}();
exports.default = MP4Remuxer;
},{"../errors":20,"../events":22,"../helper/aac":23,"../remux/mp4-generator":30,"../utils/browser":35,"../utils/logger":38,"../utils/polyfill":39}],32:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
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; }; }(); /**
* passthrough remuxer
*/
var _events = require('../events');
var _events2 = _interopRequireDefault(_events);
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"); } }
var PassThroughRemuxer = function () {
function PassThroughRemuxer(observer) {
_classCallCheck(this, PassThroughRemuxer);
this.observer = observer;
this.ISGenerated = false;
}
_createClass(PassThroughRemuxer, [{
key: 'destroy',
value: function destroy() {}
}, {
key: 'insertDiscontinuity',
value: function insertDiscontinuity() {}
}, {
key: 'switchLevel',
value: function switchLevel() {
this.ISGenerated = false;
}
}, {
key: 'remux',
value: function remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, rawData) {
var observer = this.observer;
// generate Init Segment if needed
if (!this.ISGenerated) {
var tracks = {},
data = { tracks: tracks, unique: true },
track = videoTrack,
codec = track.codec;
if (codec) {
data.tracks.video = {
container: track.container,
codec: codec,
metadata: {
width: track.width,
height: track.height
}
};
}
track = audioTrack;
codec = track.codec;
if (codec) {
data.tracks.audio = {
container: track.container,
codec: codec,
metadata: {
channelCount: track.channelCount
}
};
}
this.ISGenerated = true;
observer.trigger(_events2.default.FRAG_PARSING_INIT_SEGMENT, data);
}
observer.trigger(_events2.default.FRAG_PARSING_DATA, {
data1: rawData,
startPTS: timeOffset,
startDTS: timeOffset,
type: 'audiovideo',
nb: 1,
dropped: 0,
deltaPTS: 0
});
}
}, {
key: 'passthrough',
get: function get() {
return true;
}
}]);
return PassThroughRemuxer;
}();
exports.default = PassThroughRemuxer;
},{"../events":22}],33:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
// adapted from https://github.com/kanongil/node-m3u8parse/blob/master/attrlist.js
var AttrList = function () {
function AttrList(attrs) {
_classCallCheck(this, AttrList);
if (typeof attrs === 'string') {
attrs = AttrList.parseAttrList(attrs);
}
for (var attr in attrs) {
if (attrs.hasOwnProperty(attr)) {
this[attr] = attrs[attr];
}
}
}
_createClass(AttrList, [{
key: 'decimalInteger',
value: function decimalInteger(attrName) {
var intValue = parseInt(this[attrName], 10);
if (intValue > Number.MAX_SAFE_INTEGER) {
return Infinity;
}
return intValue;
}
}, {
key: 'hexadecimalInteger',
value: 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;
}
}
}, {
key: 'hexadecimalIntegerAsNumber',
value: function hexadecimalIntegerAsNumber(attrName) {
var intValue = parseInt(this[attrName], 16);
if (intValue > Number.MAX_SAFE_INTEGER) {
return Infinity;
}
return intValue;
}
}, {
key: 'decimalFloatingPoint',
value: function decimalFloatingPoint(attrName) {
return parseFloat(this[attrName]);
}
}, {
key: 'enumeratedString',
value: function enumeratedString(attrName) {
return this[attrName];
}
}, {
key: 'decimalResolution',
value: function decimalResolution(attrName) {
var res = /^(\d+)x(\d+)$/.exec(this[attrName]);
if (res === null) {
return undefined;
}
return {
width: parseInt(res[1], 10),
height: parseInt(res[2], 10)
};
}
}], [{
key: 'parseAttrList',
value: function parseAttrList(input) {
var re = /\s*(.+?)\s*=((?:\".*?\")|.*?)(?:,|$)/g;
var match,
attrs = {};
while ((match = re.exec(input)) !== null) {
var value = match[2],
quote = '"';
if (value.indexOf(quote) === 0 && value.lastIndexOf(quote) === value.length - 1) {
value = value.slice(1, -1);
}
attrs[match[1]] = value;
}
return attrs;
}
}]);
return AttrList;
}();
exports.default = AttrList;
},{}],34:[function(require,module,exports){
"use strict";
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} list The array to search.
* @param {Function} comparisonFunction
* 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 {*} The object if it is found or null otherwise.
*/
search: function search(list, comparisonFunction) {
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 = comparisonFunction(currentElement);
if (comparisonResult > 0) {
minIndex = currentIndex + 1;
} else if (comparisonResult < 0) {
maxIndex = currentIndex - 1;
} else {
return currentElement;
}
}
return null;
}
};
module.exports = BinarySearch;
},{}],35:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var browser = {
isSafari: function isSafari() {
var vendor = navigator.vendor,
userAgent = navigator.userAgent;
return vendor && vendor.indexOf('Apple') > -1 && userAgent && !userAgent.match('CriOS');
}
};
exports.default = browser;
},{}],36:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
*
* This code was ported from the dash.js project at:
* https://github.com/Dash-Industry-Forum/dash.js/blob/development/externals/cea608-parser.js
* https://github.com/Dash-Industry-Forum/dash.js/commit/8269b26a761e0853bb21d78780ed945144ecdd4d#diff-71bc295a2d6b6b7093a1d3290d53a4b2
*
* The original copyright appears below:
*
* The copyright in this software is being made available under the BSD License,
* included below. This software may be subject to other third party and contributor
* rights, including patent rights, and no such rights are granted under this license.
*
* Copyright (c) 2015-2016, DASH Industry Forum.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
* 2. Neither the name of Dash Industry Forum nor the names of its
* contributors may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/**
* Exceptions from regular ASCII. CodePoints are mapped to UTF-16 codes
*/
var specialCea608CharsCodes = {
0x2a: 0xe1, // lowercase a, acute accent
0x5c: 0xe9, // lowercase e, acute accent
0x5e: 0xed, // lowercase i, acute accent
0x5f: 0xf3, // lowercase o, acute accent
0x60: 0xfa, // lowercase u, acute accent
0x7b: 0xe7, // lowercase c with cedilla
0x7c: 0xf7, // division symbol
0x7d: 0xd1, // uppercase N tilde
0x7e: 0xf1, // lowercase n tilde
0x7f: 0x2588, // Full block
// THIS BLOCK INCLUDES THE 16 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
// THAT COME FROM HI BYTE=0x11 AND LOW BETWEEN 0x30 AND 0x3F
// THIS MEANS THAT \x50 MUST BE ADDED TO THE VALUES
0x80: 0xae, // Registered symbol (R)
0x81: 0xb0, // degree sign
0x82: 0xbd, // 1/2 symbol
0x83: 0xbf, // Inverted (open) question mark
0x84: 0x2122, // Trademark symbol (TM)
0x85: 0xa2, // Cents symbol
0x86: 0xa3, // Pounds sterling
0x87: 0x266a, // Music 8'th note
0x88: 0xe0, // lowercase a, grave accent
0x89: 0x20, // transparent space (regular)
0x8a: 0xe8, // lowercase e, grave accent
0x8b: 0xe2, // lowercase a, circumflex accent
0x8c: 0xea, // lowercase e, circumflex accent
0x8d: 0xee, // lowercase i, circumflex accent
0x8e: 0xf4, // lowercase o, circumflex accent
0x8f: 0xfb, // lowercase u, circumflex accent
// THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
// THAT COME FROM HI BYTE=0x12 AND LOW BETWEEN 0x20 AND 0x3F
0x90: 0xc1, // capital letter A with acute
0x91: 0xc9, // capital letter E with acute
0x92: 0xd3, // capital letter O with acute
0x93: 0xda, // capital letter U with acute
0x94: 0xdc, // capital letter U with diaresis
0x95: 0xfc, // lowercase letter U with diaeresis
0x96: 0x2018, // opening single quote
0x97: 0xa1, // inverted exclamation mark
0x98: 0x2a, // asterisk
0x99: 0x2019, // closing single quote
0x9a: 0x2501, // box drawings heavy horizontal
0x9b: 0xa9, // copyright sign
0x9c: 0x2120, // Service mark
0x9d: 0x2022, // (round) bullet
0x9e: 0x201c, // Left double quotation mark
0x9f: 0x201d, // Right double quotation mark
0xa0: 0xc0, // uppercase A, grave accent
0xa1: 0xc2, // uppercase A, circumflex
0xa2: 0xc7, // uppercase C with cedilla
0xa3: 0xc8, // uppercase E, grave accent
0xa4: 0xca, // uppercase E, circumflex
0xa5: 0xcb, // capital letter E with diaresis
0xa6: 0xeb, // lowercase letter e with diaresis
0xa7: 0xce, // uppercase I, circumflex
0xa8: 0xcf, // uppercase I, with diaresis
0xa9: 0xef, // lowercase i, with diaresis
0xaa: 0xd4, // uppercase O, circumflex
0xab: 0xd9, // uppercase U, grave accent
0xac: 0xf9, // lowercase u, grave accent
0xad: 0xdb, // uppercase U, circumflex
0xae: 0xab, // left-pointing double angle quotation mark
0xaf: 0xbb, // right-pointing double angle quotation mark
// THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
// THAT COME FROM HI BYTE=0x13 AND LOW BETWEEN 0x20 AND 0x3F
0xb0: 0xc3, // Uppercase A, tilde
0xb1: 0xe3, // Lowercase a, tilde
0xb2: 0xcd, // Uppercase I, acute accent
0xb3: 0xcc, // Uppercase I, grave accent
0xb4: 0xec, // Lowercase i, grave accent
0xb5: 0xd2, // Uppercase O, grave accent
0xb6: 0xf2, // Lowercase o, grave accent
0xb7: 0xd5, // Uppercase O, tilde
0xb8: 0xf5, // Lowercase o, tilde
0xb9: 0x7b, // Open curly brace
0xba: 0x7d, // Closing curly brace
0xbb: 0x5c, // Backslash
0xbc: 0x5e, // Caret
0xbd: 0x5f, // Underscore
0xbe: 0x7c, // Pipe (vertical line)
0xbf: 0x223c, // Tilde operator
0xc0: 0xc4, // Uppercase A, umlaut
0xc1: 0xe4, // Lowercase A, umlaut
0xc2: 0xd6, // Uppercase O, umlaut
0xc3: 0xf6, // Lowercase o, umlaut
0xc4: 0xdf, // Esszett (sharp S)
0xc5: 0xa5, // Yen symbol
0xc6: 0xa4, // Generic currency sign
0xc7: 0x2503, // Box drawings heavy vertical
0xc8: 0xc5, // Uppercase A, ring
0xc9: 0xe5, // Lowercase A, ring
0xca: 0xd8, // Uppercase O, stroke
0xcb: 0xf8, // Lowercase o, strok
0xcc: 0x250f, // Box drawings heavy down and right
0xcd: 0x2513, // Box drawings heavy down and left
0xce: 0x2517, // Box drawings heavy up and right
0xcf: 0x251b // Box drawings heavy up and left
};
/**
* Utils
*/
var getCharForByte = function getCharForByte(byte) {
var charCode = byte;
if (specialCea608CharsCodes.hasOwnProperty(byte)) {
charCode = specialCea608CharsCodes[byte];
}
return String.fromCharCode(charCode);
};
var NR_ROWS = 15,
NR_COLS = 32;
// Tables to look up row from PAC data
var rowsLowCh1 = { 0x11: 1, 0x12: 3, 0x15: 5, 0x16: 7, 0x17: 9, 0x10: 11, 0x13: 12, 0x14: 14 };
var rowsHighCh1 = { 0x11: 2, 0x12: 4, 0x15: 6, 0x16: 8, 0x17: 10, 0x13: 13, 0x14: 15 };
var rowsLowCh2 = { 0x19: 1, 0x1A: 3, 0x1D: 5, 0x1E: 7, 0x1F: 9, 0x18: 11, 0x1B: 12, 0x1C: 14 };
var rowsHighCh2 = { 0x19: 2, 0x1A: 4, 0x1D: 6, 0x1E: 8, 0x1F: 10, 0x1B: 13, 0x1C: 15 };
var backgroundColors = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta', 'black', 'transparent'];
/**
* Simple logger class to be able to write with time-stamps and filter on level.
*/
var logger = {
verboseFilter: { 'DATA': 3, 'DEBUG': 3, 'INFO': 2, 'WARNING': 2, 'TEXT': 1, 'ERROR': 0 },
time: null,
verboseLevel: 0, // Only write errors
setTime: function setTime(newTime) {
this.time = newTime;
},
log: function log(severity, msg) {
var minLevel = this.verboseFilter[severity];
if (this.verboseLevel >= minLevel) {
console.log(this.time + ' [' + severity + '] ' + msg);
}
}
};
var numArrayToHexArray = function numArrayToHexArray(numArray) {
var hexArray = [];
for (var j = 0; j < numArray.length; j++) {
hexArray.push(numArray[j].toString(16));
}
return hexArray;
};
var PenState = function () {
function PenState(foreground, underline, italics, background, flash) {
_classCallCheck(this, PenState);
this.foreground = foreground || 'white';
this.underline = underline || false;
this.italics = italics || false;
this.background = background || 'black';
this.flash = flash || false;
}
_createClass(PenState, [{
key: 'reset',
value: function reset() {
this.foreground = 'white';
this.underline = false;
this.italics = false;
this.background = 'black';
this.flash = false;
}
}, {
key: 'setStyles',
value: function setStyles(styles) {
var attribs = ['foreground', 'underline', 'italics', 'background', 'flash'];
for (var i = 0; i < attribs.length; i++) {
var style = attribs[i];
if (styles.hasOwnProperty(style)) {
this[style] = styles[style];
}
}
}
}, {
key: 'isDefault',
value: function isDefault() {
return this.foreground === 'white' && !this.underline && !this.italics && this.background === 'black' && !this.flash;
}
}, {
key: 'equals',
value: function equals(other) {
return this.foreground === other.foreground && this.underline === other.underline && this.italics === other.italics && this.background === other.background && this.flash === other.flash;
}
}, {
key: 'copy',
value: function copy(newPenState) {
this.foreground = newPenState.foreground;
this.underline = newPenState.underline;
this.italics = newPenState.italics;
this.background = newPenState.background;
this.flash = newPenState.flash;
}
}, {
key: 'toString',
value: function toString() {
return 'color=' + this.foreground + ', underline=' + this.underline + ', italics=' + this.italics + ', background=' + this.background + ', flash=' + this.flash;
}
}]);
return PenState;
}();
/**
* Unicode character with styling and background.
* @constructor
*/
var StyledUnicodeChar = function () {
function StyledUnicodeChar(uchar, foreground, underline, italics, background, flash) {
_classCallCheck(this, StyledUnicodeChar);
this.uchar = uchar || ' '; // unicode character
this.penState = new PenState(foreground, underline, italics, background, flash);
}
_createClass(StyledUnicodeChar, [{
key: 'reset',
value: function reset() {
this.uchar = ' ';
this.penState.reset();
}
}, {
key: 'setChar',
value: function setChar(uchar, newPenState) {
this.uchar = uchar;
this.penState.copy(newPenState);
}
}, {
key: 'setPenState',
value: function setPenState(newPenState) {
this.penState.copy(newPenState);
}
}, {
key: 'equals',
value: function equals(other) {
return this.uchar === other.uchar && this.penState.equals(other.penState);
}
}, {
key: 'copy',
value: function copy(newChar) {
this.uchar = newChar.uchar;
this.penState.copy(newChar.penState);
}
}, {
key: 'isEmpty',
value: function isEmpty() {
return this.uchar === ' ' && this.penState.isDefault();
}
}]);
return StyledUnicodeChar;
}();
/**
* CEA-608 row consisting of NR_COLS instances of StyledUnicodeChar.
* @constructor
*/
var Row = function () {
function Row() {
_classCallCheck(this, Row);
this.chars = [];
for (var i = 0; i < NR_COLS; i++) {
this.chars.push(new StyledUnicodeChar());
}
this.pos = 0;
this.currPenState = new PenState();
}
_createClass(Row, [{
key: 'equals',
value: function equals(other) {
var equal = true;
for (var i = 0; i < NR_COLS; i++) {
if (!this.chars[i].equals(other.chars[i])) {
equal = false;
break;
}
}
return equal;
}
}, {
key: 'copy',
value: function copy(other) {
for (var i = 0; i < NR_COLS; i++) {
this.chars[i].copy(other.chars[i]);
}
}
}, {
key: 'isEmpty',
value: function isEmpty() {
var empty = true;
for (var i = 0; i < NR_COLS; i++) {
if (!this.chars[i].isEmpty()) {
empty = false;
break;
}
}
return empty;
}
/**
* Set the cursor to a valid column.
*/
}, {
key: 'setCursor',
value: function setCursor(absPos) {
if (this.pos !== absPos) {
this.pos = absPos;
}
if (this.pos < 0) {
logger.log('ERROR', 'Negative cursor position ' + this.pos);
this.pos = 0;
} else if (this.pos > NR_COLS) {
logger.log('ERROR', 'Too large cursor position ' + this.pos);
this.pos = NR_COLS;
}
}
/**
* Move the cursor relative to current position.
*/
}, {
key: 'moveCursor',
value: function moveCursor(relPos) {
var newPos = this.pos + relPos;
if (relPos > 1) {
for (var i = this.pos + 1; i < newPos + 1; i++) {
this.chars[i].setPenState(this.currPenState);
}
}
this.setCursor(newPos);
}
/**
* Backspace, move one step back and clear character.
*/
}, {
key: 'backSpace',
value: function backSpace() {
this.moveCursor(-1);
this.chars[this.pos].setChar(' ', this.currPenState);
}
}, {
key: 'insertChar',
value: function insertChar(byte) {
if (byte >= 0x90) {
//Extended char
this.backSpace();
}
var char = getCharForByte(byte);
if (this.pos >= NR_COLS) {
logger.log('ERROR', 'Cannot insert ' + byte.toString(16) + ' (' + char + ') at position ' + this.pos + '. Skipping it!');
return;
}
this.chars[this.pos].setChar(char, this.currPenState);
this.moveCursor(1);
}
}, {
key: 'clearFromPos',
value: function clearFromPos(startPos) {
var i;
for (i = startPos; i < NR_COLS; i++) {
this.chars[i].reset();
}
}
}, {
key: 'clear',
value: function clear() {
this.clearFromPos(0);
this.pos = 0;
this.currPenState.reset();
}
}, {
key: 'clearToEndOfRow',
value: function clearToEndOfRow() {
this.clearFromPos(this.pos);
}
}, {
key: 'getTextString',
value: function getTextString() {
var chars = [];
var empty = true;
for (var i = 0; i < NR_COLS; i++) {
var char = this.chars[i].uchar;
if (char !== ' ') {
empty = false;
}
chars.push(char);
}
if (empty) {
return '';
} else {
return chars.join('');
}
}
}, {
key: 'setPenStyles',
value: function setPenStyles(styles) {
this.currPenState.setStyles(styles);
var currChar = this.chars[this.pos];
currChar.setPenState(this.currPenState);
}
}]);
return Row;
}();
/**
* Keep a CEA-608 screen of 32x15 styled characters
* @constructor
*/
var CaptionScreen = function () {
function CaptionScreen() {
_classCallCheck(this, CaptionScreen);
this.rows = [];
for (var i = 0; i < NR_ROWS; i++) {
this.rows.push(new Row()); // Note that we use zero-based numbering (0-14)
}
this.currRow = NR_ROWS - 1;
this.nrRollUpRows = null;
this.reset();
}
_createClass(CaptionScreen, [{
key: 'reset',
value: function reset() {
for (var i = 0; i < NR_ROWS; i++) {
this.rows[i].clear();
}
this.currRow = NR_ROWS - 1;
}
}, {
key: 'equals',
value: function equals(other) {
var equal = true;
for (var i = 0; i < NR_ROWS; i++) {
if (!this.rows[i].equals(other.rows[i])) {
equal = false;
break;
}
}
return equal;
}
}, {
key: 'copy',
value: function copy(other) {
for (var i = 0; i < NR_ROWS; i++) {
this.rows[i].copy(other.rows[i]);
}
}
}, {
key: 'isEmpty',
value: function isEmpty() {
var empty = true;
for (var i = 0; i < NR_ROWS; i++) {
if (!this.rows[i].isEmpty()) {
empty = false;
break;
}
}
return empty;
}
}, {
key: 'backSpace',
value: function backSpace() {
var row = this.rows[this.currRow];
row.backSpace();
}
}, {
key: 'clearToEndOfRow',
value: function clearToEndOfRow() {
var row = this.rows[this.currRow];
row.clearToEndOfRow();
}
/**
* Insert a character (without styling) in the current row.
*/
}, {
key: 'insertChar',
value: function insertChar(char) {
var row = this.rows[this.currRow];
row.insertChar(char);
}
}, {
key: 'setPen',
value: function setPen(styles) {
var row = this.rows[this.currRow];
row.setPenStyles(styles);
}
}, {
key: 'moveCursor',
value: function moveCursor(relPos) {
var row = this.rows[this.currRow];
row.moveCursor(relPos);
}
}, {
key: 'setCursor',
value: function setCursor(absPos) {
logger.log('INFO', 'setCursor: ' + absPos);
var row = this.rows[this.currRow];
row.setCursor(absPos);
}
}, {
key: 'setPAC',
value: function setPAC(pacData) {
logger.log('INFO', 'pacData = ' + JSON.stringify(pacData));
var newRow = pacData.row - 1;
if (this.nrRollUpRows && newRow < this.nrRollUpRows - 1) {
newRow = this.nrRollUpRows - 1;
}
this.currRow = newRow;
var row = this.rows[this.currRow];
if (pacData.indent !== null) {
var indent = pacData.indent;
var prevPos = Math.max(indent - 1, 0);
row.setCursor(pacData.indent);
pacData.color = row.chars[prevPos].penState.foreground;
}
var styles = { foreground: pacData.color, underline: pacData.underline, italics: pacData.italics, background: 'black', flash: false };
this.setPen(styles);
}
/**
* Set background/extra foreground, but first do back_space, and then insert space (backwards compatibility).
*/
}, {
key: 'setBkgData',
value: function setBkgData(bkgData) {
logger.log('INFO', 'bkgData = ' + JSON.stringify(bkgData));
this.backSpace();
this.setPen(bkgData);
this.insertChar(0x20); //Space
}
}, {
key: 'setRollUpRows',
value: function setRollUpRows(nrRows) {
this.nrRollUpRows = nrRows;
}
}, {
key: 'rollUp',
value: function rollUp() {
if (this.nrRollUpRows === null) {
logger.log('DEBUG', 'roll_up but nrRollUpRows not set yet');
return; //Not properly setup
}
logger.log('TEXT', this.getDisplayText());
var topRowIndex = this.currRow + 1 - this.nrRollUpRows;
var topRow = this.rows.splice(topRowIndex, 1)[0];
topRow.clear();
this.rows.splice(this.currRow, 0, topRow);
logger.log('INFO', 'Rolling up');
//logger.log('TEXT', this.get_display_text())
}
/**
* Get all non-empty rows with as unicode text.
*/
}, {
key: 'getDisplayText',
value: function getDisplayText(asOneRow) {
asOneRow = asOneRow || false;
var displayText = [];
var text = '';
var rowNr = -1;
for (var i = 0; i < NR_ROWS; i++) {
var rowText = this.rows[i].getTextString();
if (rowText) {
rowNr = i + 1;
if (asOneRow) {
displayText.push('Row ' + rowNr + ': \'' + rowText + '\'');
} else {
displayText.push(rowText.trim());
}
}
}
if (displayText.length > 0) {
if (asOneRow) {
text = '[' + displayText.join(' | ') + ']';
} else {
text = displayText.join('\n');
}
}
return text;
}
}, {
key: 'getTextAndFormat',
value: function getTextAndFormat() {
return this.rows;
}
}]);
return CaptionScreen;
}();
//var modes = ['MODE_ROLL-UP', 'MODE_POP-ON', 'MODE_PAINT-ON', 'MODE_TEXT'];
var Cea608Channel = function () {
function Cea608Channel(channelNumber, outputFilter) {
_classCallCheck(this, Cea608Channel);
this.chNr = channelNumber;
this.outputFilter = outputFilter;
this.mode = null;
this.verbose = 0;
this.displayedMemory = new CaptionScreen();
this.nonDisplayedMemory = new CaptionScreen();
this.lastOutputScreen = new CaptionScreen();
this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1];
this.writeScreen = this.displayedMemory;
this.mode = null;
this.cueStartTime = null; // Keeps track of where a cue started.
}
_createClass(Cea608Channel, [{
key: 'reset',
value: function reset() {
this.mode = null;
this.displayedMemory.reset();
this.nonDisplayedMemory.reset();
this.lastOutputScreen.reset();
this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1];
this.writeScreen = this.displayedMemory;
this.mode = null;
this.cueStartTime = null;
this.lastCueEndTime = null;
}
}, {
key: 'getHandler',
value: function getHandler() {
return this.outputFilter;
}
}, {
key: 'setHandler',
value: function setHandler(newHandler) {
this.outputFilter = newHandler;
}
}, {
key: 'setPAC',
value: function setPAC(pacData) {
this.writeScreen.setPAC(pacData);
}
}, {
key: 'setBkgData',
value: function setBkgData(bkgData) {
this.writeScreen.setBkgData(bkgData);
}
}, {
key: 'setMode',
value: function setMode(newMode) {
if (newMode === this.mode) {
return;
}
this.mode = newMode;
logger.log('INFO', 'MODE=' + newMode);
if (this.mode === 'MODE_POP-ON') {
this.writeScreen = this.nonDisplayedMemory;
} else {
this.writeScreen = this.displayedMemory;
this.writeScreen.reset();
}
if (this.mode !== 'MODE_ROLL-UP') {
this.displayedMemory.nrRollUpRows = null;
this.nonDisplayedMemory.nrRollUpRows = null;
}
this.mode = newMode;
}
}, {
key: 'insertChars',
value: function insertChars(chars) {
for (var i = 0; i < chars.length; i++) {
this.writeScreen.insertChar(chars[i]);
}
var screen = this.writeScreen === this.displayedMemory ? 'DISP' : 'NON_DISP';
logger.log('INFO', screen + ': ' + this.writeScreen.getDisplayText(true));
if (this.mode === 'MODE_PAINT-ON' || this.mode === 'MODE_ROLL-UP') {
logger.log('TEXT', 'DISPLAYED: ' + this.displayedMemory.getDisplayText(true));
this.outputDataUpdate();
}
}
}, {
key: 'ccRCL',
value: function ccRCL() {
// Resume Caption Loading (switch mode to Pop On)
logger.log('INFO', 'RCL - Resume Caption Loading');
this.setMode('MODE_POP-ON');
}
}, {
key: 'ccBS',
value: function ccBS() {
// BackSpace
logger.log('INFO', 'BS - BackSpace');
if (this.mode === 'MODE_TEXT') {
return;
}
this.writeScreen.backSpace();
if (this.writeScreen === this.displayedMemory) {
this.outputDataUpdate();
}
}
}, {
key: 'ccAOF',
value: function ccAOF() {
// Reserved (formerly Alarm Off)
return;
}
}, {
key: 'ccAON',
value: function ccAON() {
// Reserved (formerly Alarm On)
return;
}
}, {
key: 'ccDER',
value: function ccDER() {
// Delete to End of Row
logger.log('INFO', 'DER- Delete to End of Row');
this.writeScreen.clearToEndOfRow();
this.outputDataUpdate();
}
}, {
key: 'ccRU',
value: function ccRU(nrRows) {
//Roll-Up Captions-2,3,or 4 Rows
logger.log('INFO', 'RU(' + nrRows + ') - Roll Up');
this.writeScreen = this.displayedMemory;
this.setMode('MODE_ROLL-UP');
this.writeScreen.setRollUpRows(nrRows);
}
}, {
key: 'ccFON',
value: function ccFON() {
//Flash On
logger.log('INFO', 'FON - Flash On');
this.writeScreen.setPen({ flash: true });
}
}, {
key: 'ccRDC',
value: function ccRDC() {
// Resume Direct Captioning (switch mode to PaintOn)
logger.log('INFO', 'RDC - Resume Direct Captioning');
this.setMode('MODE_PAINT-ON');
}
}, {
key: 'ccTR',
value: function ccTR() {
// Text Restart in text mode (not supported, however)
logger.log('INFO', 'TR');
this.setMode('MODE_TEXT');
}
}, {
key: 'ccRTD',
value: function ccRTD() {
// Resume Text Display in Text mode (not supported, however)
logger.log('INFO', 'RTD');
this.setMode('MODE_TEXT');
}
}, {
key: 'ccEDM',
value: function ccEDM() {
// Erase Displayed Memory
logger.log('INFO', 'EDM - Erase Displayed Memory');
this.displayedMemory.reset();
this.outputDataUpdate();
}
}, {
key: 'ccCR',
value: function ccCR() {
// Carriage Return
logger.log('CR - Carriage Return');
this.writeScreen.rollUp();
this.outputDataUpdate();
}
}, {
key: 'ccENM',
value: function ccENM() {
//Erase Non-Displayed Memory
logger.log('INFO', 'ENM - Erase Non-displayed Memory');
this.nonDisplayedMemory.reset();
}
}, {
key: 'ccEOC',
value: function ccEOC() {
//End of Caption (Flip Memories)
logger.log('INFO', 'EOC - End Of Caption');
if (this.mode === 'MODE_POP-ON') {
var tmp = this.displayedMemory;
this.displayedMemory = this.nonDisplayedMemory;
this.nonDisplayedMemory = tmp;
this.writeScreen = this.nonDisplayedMemory;
logger.log('TEXT', 'DISP: ' + this.displayedMemory.getDisplayText());
}
this.outputDataUpdate();
}
}, {
key: 'ccTO',
value: function ccTO(nrCols) {
// Tab Offset 1,2, or 3 columns
logger.log('INFO', 'TO(' + nrCols + ') - Tab Offset');
this.writeScreen.moveCursor(nrCols);
}
}, {
key: 'ccMIDROW',
value: function ccMIDROW(secondByte) {
// Parse MIDROW command
var styles = { flash: false };
styles.underline = secondByte % 2 === 1;
styles.italics = secondByte >= 0x2e;
if (!styles.italics) {
var colorIndex = Math.floor(secondByte / 2) - 0x10;
var colors = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta'];
styles.foreground = colors[colorIndex];
} else {
styles.foreground = 'white';
}
logger.log('INFO', 'MIDROW: ' + JSON.stringify(styles));
this.writeScreen.setPen(styles);
}
}, {
key: 'outputDataUpdate',
value: function outputDataUpdate() {
var t = logger.time;
if (t === null) {
return;
}
if (this.outputFilter) {
if (this.outputFilter.updateData) {
this.outputFilter.updateData(t, this.displayedMemory);
}
if (this.cueStartTime === null && !this.displayedMemory.isEmpty()) {
// Start of a new cue
this.cueStartTime = t;
} else {
if (!this.displayedMemory.equals(this.lastOutputScreen)) {
if (this.outputFilter.newCue) {
this.outputFilter.newCue(this.cueStartTime, t, this.lastOutputScreen);
}
this.cueStartTime = this.displayedMemory.isEmpty() ? null : t;
}
}
this.lastOutputScreen.copy(this.displayedMemory);
}
}
}, {
key: 'cueSplitAtTime',
value: function cueSplitAtTime(t) {
if (this.outputFilter) {
if (!this.displayedMemory.isEmpty()) {
if (this.outputFilter.newCue) {
this.outputFilter.newCue(this.cueStartTime, t, this.displayedMemory);
}
this.cueStartTime = t;
}
}
}
}]);
return Cea608Channel;
}();
var Cea608Parser = function () {
function Cea608Parser(field, out1, out2) {
_classCallCheck(this, Cea608Parser);
this.field = field || 1;
this.outputs = [out1, out2];
this.channels = [new Cea608Channel(1, out1), new Cea608Channel(2, out2)];
this.currChNr = -1; // Will be 1 or 2
this.lastCmdA = null; // First byte of last command
this.lastCmdB = null; // Second byte of last command
this.bufferedData = [];
this.startTime = null;
this.lastTime = null;
this.dataCounters = { 'padding': 0, 'char': 0, 'cmd': 0, 'other': 0 };
}
_createClass(Cea608Parser, [{
key: 'getHandler',
value: function getHandler(index) {
return this.channels[index].getHandler();
}
}, {
key: 'setHandler',
value: function setHandler(index, newHandler) {
this.channels[index].setHandler(newHandler);
}
/**
* Add data for time t in forms of list of bytes (unsigned ints). The bytes are treated as pairs.
*/
}, {
key: 'addData',
value: function addData(t, byteList) {
var cmdFound,
a,
b,
charsFound = false;
this.lastTime = t;
logger.setTime(t);
for (var i = 0; i < byteList.length; i += 2) {
a = byteList[i] & 0x7f;
b = byteList[i + 1] & 0x7f;
if (a === 0 && b === 0) {
this.dataCounters.padding += 2;
continue;
} else {
logger.log('DATA', '[' + numArrayToHexArray([byteList[i], byteList[i + 1]]) + '] -> (' + numArrayToHexArray([a, b]) + ')');
}
cmdFound = this.parseCmd(a, b);
if (!cmdFound) {
cmdFound = this.parseMidrow(a, b);
}
if (!cmdFound) {
cmdFound = this.parsePAC(a, b);
}
if (!cmdFound) {
cmdFound = this.parseBackgroundAttributes(a, b);
}
if (!cmdFound) {
charsFound = this.parseChars(a, b);
if (charsFound) {
if (this.currChNr && this.currChNr >= 0) {
var channel = this.channels[this.currChNr - 1];
channel.insertChars(charsFound);
} else {
logger.log('WARNING', 'No channel found yet. TEXT-MODE?');
}
}
}
if (cmdFound) {
this.dataCounters.cmd += 2;
} else if (charsFound) {
this.dataCounters.char += 2;
} else {
this.dataCounters.other += 2;
logger.log('WARNING', 'Couldn\'t parse cleaned data ' + numArrayToHexArray([a, b]) + ' orig: ' + numArrayToHexArray([byteList[i], byteList[i + 1]]));
}
}
}
/**
* Parse Command.
* @returns {Boolean} Tells if a command was found
*/
}, {
key: 'parseCmd',
value: function parseCmd(a, b) {
var chNr = null;
var cond1 = (a === 0x14 || a === 0x1C) && 0x20 <= b && b <= 0x2F;
var cond2 = (a === 0x17 || a === 0x1F) && 0x21 <= b && b <= 0x23;
if (!(cond1 || cond2)) {
return false;
}
if (a === this.lastCmdA && b === this.lastCmdB) {
this.lastCmdA = null;
this.lastCmdB = null; // Repeated commands are dropped (once)
logger.log('DEBUG', 'Repeated command (' + numArrayToHexArray([a, b]) + ') is dropped');
return true;
}
if (a === 0x14 || a === 0x17) {
chNr = 1;
} else {
chNr = 2; // (a === 0x1C || a=== 0x1f)
}
var channel = this.channels[chNr - 1];
if (a === 0x14 || a === 0x1C) {
if (b === 0x20) {
channel.ccRCL();
} else if (b === 0x21) {
channel.ccBS();
} else if (b === 0x22) {
channel.ccAOF();
} else if (b === 0x23) {
channel.ccAON();
} else if (b === 0x24) {
channel.ccDER();
} else if (b === 0x25) {
channel.ccRU(2);
} else if (b === 0x26) {
channel.ccRU(3);
} else if (b === 0x27) {
channel.ccRU(4);
} else if (b === 0x28) {
channel.ccFON();
} else if (b === 0x29) {
channel.ccRDC();
} else if (b === 0x2A) {
channel.ccTR();
} else if (b === 0x2B) {
channel.ccRTD();
} else if (b === 0x2C) {
channel.ccEDM();
} else if (b === 0x2D) {
channel.ccCR();
} else if (b === 0x2E) {
channel.ccENM();
} else if (b === 0x2F) {
channel.ccEOC();
}
} else {
//a == 0x17 || a == 0x1F
channel.ccTO(b - 0x20);
}
this.lastCmdA = a;
this.lastCmdB = b;
this.currChNr = chNr;
return true;
}
/**
* Parse midrow styling command
* @returns {Boolean}
*/
}, {
key: 'parseMidrow',
value: function parseMidrow(a, b) {
var chNr = null;
if ((a === 0x11 || a === 0x19) && 0x20 <= b && b <= 0x2f) {
if (a === 0x11) {
chNr = 1;
} else {
chNr = 2;
}
if (chNr !== this.currChNr) {
logger.log('ERROR', 'Mismatch channel in midrow parsing');
return false;
}
var channel = this.channels[chNr - 1];
channel.ccMIDROW(b);
logger.log('DEBUG', 'MIDROW (' + numArrayToHexArray([a, b]) + ')');
return true;
}
return false;
}
/**
* Parse Preable Access Codes (Table 53).
* @returns {Boolean} Tells if PAC found
*/
}, {
key: 'parsePAC',
value: function parsePAC(a, b) {
var chNr = null;
var row = null;
var case1 = (0x11 <= a && a <= 0x17 || 0x19 <= a && a <= 0x1F) && 0x40 <= b && b <= 0x7F;
var case2 = (a === 0x10 || a === 0x18) && 0x40 <= b && b <= 0x5F;
if (!(case1 || case2)) {
return false;
}
if (a === this.lastCmdA && b === this.lastCmdB) {
this.lastCmdA = null;
this.lastCmdB = null;
return true; // Repeated commands are dropped (once)
}
chNr = a <= 0x17 ? 1 : 2;
if (0x40 <= b && b <= 0x5F) {
row = chNr === 1 ? rowsLowCh1[a] : rowsLowCh2[a];
} else {
// 0x60 <= b <= 0x7F
row = chNr === 1 ? rowsHighCh1[a] : rowsHighCh2[a];
}
var pacData = this.interpretPAC(row, b);
var channel = this.channels[chNr - 1];
channel.setPAC(pacData);
this.lastCmdA = a;
this.lastCmdB = b;
this.currChNr = chNr;
return true;
}
/**
* Interpret the second byte of the pac, and return the information.
* @returns {Object} pacData with style parameters.
*/
}, {
key: 'interpretPAC',
value: function interpretPAC(row, byte) {
var pacIndex = byte;
var pacData = { color: null, italics: false, indent: null, underline: false, row: row };
if (byte > 0x5F) {
pacIndex = byte - 0x60;
} else {
pacIndex = byte - 0x40;
}
pacData.underline = (pacIndex & 1) === 1;
if (pacIndex <= 0xd) {
pacData.color = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta', 'white'][Math.floor(pacIndex / 2)];
} else if (pacIndex <= 0xf) {
pacData.italics = true;
pacData.color = 'white';
} else {
pacData.indent = Math.floor((pacIndex - 0x10) / 2) * 4;
}
return pacData; // Note that row has zero offset. The spec uses 1.
}
/**
* Parse characters.
* @returns An array with 1 to 2 codes corresponding to chars, if found. null otherwise.
*/
}, {
key: 'parseChars',
value: function parseChars(a, b) {
var channelNr = null,
charCodes = null,
charCode1 = null;
if (a >= 0x19) {
channelNr = 2;
charCode1 = a - 8;
} else {
channelNr = 1;
charCode1 = a;
}
if (0x11 <= charCode1 && charCode1 <= 0x13) {
// Special character
var oneCode = b;
if (charCode1 === 0x11) {
oneCode = b + 0x50;
} else if (charCode1 === 0x12) {
oneCode = b + 0x70;
} else {
oneCode = b + 0x90;
}
logger.log('INFO', 'Special char \'' + getCharForByte(oneCode) + '\' in channel ' + channelNr);
charCodes = [oneCode];
} else if (0x20 <= a && a <= 0x7f) {
charCodes = b === 0 ? [a] : [a, b];
}
if (charCodes) {
var hexCodes = numArrayToHexArray(charCodes);
logger.log('DEBUG', 'Char codes = ' + hexCodes.join(','));
this.lastCmdA = null;
this.lastCmdB = null;
}
return charCodes;
}
/**
* Parse extended background attributes as well as new foreground color black.
* @returns{Boolean} Tells if background attributes are found
*/
}, {
key: 'parseBackgroundAttributes',
value: function parseBackgroundAttributes(a, b) {
var bkgData, index, chNr, channel;
var case1 = (a === 0x10 || a === 0x18) && 0x20 <= b && b <= 0x2f;
var case2 = (a === 0x17 || a === 0x1f) && 0x2d <= b && b <= 0x2f;
if (!(case1 || case2)) {
return false;
}
bkgData = {};
if (a === 0x10 || a === 0x18) {
index = Math.floor((b - 0x20) / 2);
bkgData.background = backgroundColors[index];
if (b % 2 === 1) {
bkgData.background = bkgData.background + '_semi';
}
} else if (b === 0x2d) {
bkgData.background = 'transparent';
} else {
bkgData.foreground = 'black';
if (b === 0x2f) {
bkgData.underline = true;
}
}
chNr = a < 0x18 ? 1 : 2;
channel = this.channels[chNr - 1];
channel.setBkgData(bkgData);
this.lastCmdA = null;
this.lastCmdB = null;
return true;
}
/**
* Reset state of parser and its channels.
*/
}, {
key: 'reset',
value: function reset() {
for (var i = 0; i < this.channels.length; i++) {
if (this.channels[i]) {
this.channels[i].reset();
}
}
this.lastCmdA = null;
this.lastCmdB = null;
}
/**
* Trigger the generation of a cue, and the start of a new one if displayScreens are not empty.
*/
}, {
key: 'cueSplitAtTime',
value: function cueSplitAtTime(t) {
for (var i = 0; i < this.channels.length; i++) {
if (this.channels[i]) {
this.channels[i].cueSplitAtTime(t);
}
}
}
}]);
return Cea608Parser;
}();
exports.default = Cea608Parser;
},{}],37:[function(require,module,exports){
'use strict';
var Cues = {
newCue: function newCue(track, startTime, endTime, captionScreen) {
var row;
var cue;
var indenting;
var indent;
var text;
var VTTCue = window.VTTCue || window.TextTrackCue;
for (var r = 0; r < captionScreen.rows.length; r++) {
row = captionScreen.rows[r];
indenting = true;
indent = 0;
text = '';
if (!row.isEmpty()) {
for (var c = 0; c < row.chars.length; c++) {
if (row.chars[c].uchar.match(/\s/) && indenting) {
indent++;
} else {
text += row.chars[c].uchar;
indenting = false;
}
}
cue = new VTTCue(startTime, endTime, text.trim());
if (indent >= 16) {
indent--;
} else {
indent++;
}
// VTTCue.line get's flakey when using controls, so let's now include line 13&14
// also, drop line 1 since it's to close to the top
if (navigator.userAgent.match(/Firefox\//)) {
cue.line = r + 1;
} else {
cue.line = r > 7 ? r - 2 : r + 1;
}
cue.align = 'left';
cue.position = 100 * (indent / 32) + (navigator.userAgent.match(/Firefox\//) ? 50 : 0);
track.addCue(cue);
}
}
}
};
module.exports = Cues;
},{}],38:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
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 formatMsg(type, msg) {
msg = '[' + type + '] > ' + msg;
return msg;
}
function consolePrintFn(type) {
var func = window.console[type];
if (func) {
return function () {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
if (args[0]) {
args[0] = formatMsg(type, args[0]);
}
func.apply(window.console, args);
};
}
return noop;
}
function checkRepeatWrapper(func) {
var lastMsg;
return function () {
for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
if (args.join(' ') === lastMsg) {
return;
}
lastMsg = args.join(' ');
func.apply(null, args);
};
}
function exportLoggerFunctions(debugConfig) {
for (var _len3 = arguments.length, functions = Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
functions[_key3 - 1] = arguments[_key3];
}
functions.forEach(function (type) {
exportedLogger[type] = checkRepeatWrapper(debugConfig[type] ? debugConfig[type].bind(debugConfig) : consolePrintFn(type));
});
}
var enableLogs = exports.enableLogs = function enableLogs(debugConfig) {
if (debugConfig === true || (typeof debugConfig === 'undefined' ? 'undefined' : _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 = exports.logger = exportedLogger;
},{}],39:[function(require,module,exports){
"use strict";
if (!ArrayBuffer.prototype.slice) {
ArrayBuffer.prototype.slice = function (start, end) {
var that = new Uint8Array(this);
if (end === undefined) {
end = that.length;
}
var result = new ArrayBuffer(end - start);
var resultArray = new Uint8Array(result);
for (var i = 0; i < resultArray.length; i++) {
resultArray[i] = that[i + start];
}
return result;
};
}
if (!Object.assign) {
Object.assign = function (obj) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
if (!source) {
continue;
}
for (var prop in source) {
if (source.hasOwnProperty(prop)) {
obj[prop] = source[prop];
}
}
}
return obj;
};
}
},{}],40:[function(require,module,exports){
'use strict';
var URLHelper = {
// build an absolute URL from a relative one using the provided baseURL
// if relativeURL is an absolute URL it will be returned as is.
buildAbsoluteURL: function buildAbsoluteURL(baseURL, relativeURL) {
// remove any remaining space and CRLF
relativeURL = relativeURL.trim();
if (/^[a-z]+:/i.test(relativeURL)) {
// complete url, not relative
return (' ' + relativeURL).slice(1);
}
var relativeURLQuery = null;
var relativeURLHash = null;
var relativeURLHashSplit = /^([^#]*)(.*)$/.exec(relativeURL);
if (relativeURLHashSplit) {
relativeURLHash = relativeURLHashSplit[2];
relativeURL = relativeURLHashSplit[1];
}
var relativeURLQuerySplit = /^([^\?]*)(.*)$/.exec(relativeURL);
if (relativeURLQuerySplit) {
relativeURLQuery = relativeURLQuerySplit[2];
relativeURL = relativeURLQuerySplit[1];
}
var baseURLHashSplit = /^([^#]*)(.*)$/.exec(baseURL);
if (baseURLHashSplit) {
baseURL = baseURLHashSplit[1];
}
var baseURLQuerySplit = /^([^\?]*)(.*)$/.exec(baseURL);
if (baseURLQuerySplit) {
baseURL = baseURLQuerySplit[1];
}
var baseURLDomainSplit = /^(([a-z]+:)?\/\/[a-z0-9\.\-_~]+(:[0-9]+)?)?(\/.*)$/i.exec(baseURL);
if (!baseURLDomainSplit) {
throw new Error('Error trying to parse base URL.');
}
// e.g. 'http:', 'https:', ''
var baseURLProtocol = baseURLDomainSplit[2] || '';
// e.g. 'http://example.com', '//example.com', ''
var baseURLProtocolDomain = baseURLDomainSplit[1] || '';
// e.g. '/a/b/c/playlist.m3u8'
var baseURLPath = baseURLDomainSplit[4];
var builtURL = null;
if (/^\/\//.test(relativeURL)) {
// relative url starts wth '//' so copy protocol (which may be '' if baseUrl didn't provide one)
builtURL = baseURLProtocol + '//' + URLHelper.buildAbsolutePath('', relativeURL.substring(2));
} else if (/^\//.test(relativeURL)) {
// relative url starts with '/' so start from root of domain
builtURL = baseURLProtocolDomain + '/' + URLHelper.buildAbsolutePath('', relativeURL.substring(1));
} else {
builtURL = URLHelper.buildAbsolutePath(baseURLProtocolDomain + baseURLPath, relativeURL);
}
// put the query and hash parts back
if (relativeURLQuery) {
builtURL += relativeURLQuery;
}
if (relativeURLHash) {
builtURL += relativeURLHash;
}
return builtURL;
},
// build an absolute path using the provided basePath
// adapted from https://developer.mozilla.org/en-US/docs/Web/API/document/cookie#Using_relative_URLs_in_the_path_parameter
// this does not handle the case where relativePath is "/" or "//". These cases should be handled outside this.
buildAbsolutePath: function buildAbsolutePath(basePath, relativePath) {
var sRelPath = relativePath;
var nUpLn,
sDir = '',
sPath = basePath.replace(/[^\/]*$/, sRelPath.replace(/(\/|^)(?:\.?\/+)+/g, '$1'));
for (var nEnd, nStart = 0; nEnd = sPath.indexOf('/../', nStart), nEnd > -1; nStart = nEnd + nUpLn) {
nUpLn = /^\/(?:\.\.\/)*/.exec(sPath.slice(nEnd))[0].length;
sDir = (sDir + sPath.substring(nStart, nEnd)).replace(new RegExp('(?:\\\/+[^\\\/]*){0,' + (nUpLn - 1) / 3 + '}$'), '/');
}
return sDir + sPath.substr(nStart);
}
};
module.exports = URLHelper;
},{}],41:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
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; }; }(); /**
* XHR based logger
*/
var _logger = require('../utils/logger');
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var XhrLoader = function () {
function XhrLoader(config) {
_classCallCheck(this, XhrLoader);
if (config && config.xhrSetup) {
this.xhrSetup = config.xhrSetup;
}
}
_createClass(XhrLoader, [{
key: 'destroy',
value: function destroy() {
this.abort();
this.loader = null;
}
}, {
key: 'abort',
value: function abort() {
var loader = this.loader,
timeoutHandle = this.timeoutHandle,
retryHandle = this.retryHandle;
if (loader && loader.readyState !== 4) {
this.stats.aborted = true;
loader.abort();
}
if (timeoutHandle) {
window.clearTimeout(timeoutHandle);
}
if (retryHandle) {
window.clearTimeout(retryHandle);
}
}
}, {
key: 'load',
value: function load(url, responseType, onSuccess, onError, onTimeout, timeout, maxRetry, retryDelay) {
var onProgress = arguments.length > 8 && arguments[8] !== undefined ? arguments[8] : null;
var frag = arguments.length > 9 && arguments[9] !== undefined ? arguments[9] : null;
this.url = url;
if (frag && !isNaN(frag.byteRangeStartOffset) && !isNaN(frag.byteRangeEndOffset)) {
this.byteRange = frag.byteRangeStartOffset + '-' + (frag.byteRangeEndOffset - 1);
}
this.responseType = responseType;
this.onSuccess = onSuccess;
this.onProgress = onProgress;
this.onTimeout = onTimeout;
this.onError = onError;
this.stats = { trequest: performance.now(), retry: 0 };
this.timeout = timeout;
this.maxRetry = maxRetry;
this.retryDelay = retryDelay;
this.loadInternal();
}
}, {
key: 'loadInternal',
value: function loadInternal() {
var xhr;
if (typeof XDomainRequest !== 'undefined') {
xhr = this.loader = new XDomainRequest();
} else {
xhr = this.loader = new XMLHttpRequest();
}
xhr.onloadend = this.loadend.bind(this);
xhr.onprogress = this.loadprogress.bind(this);
var url = this.url;
if (location.protocol === 'https:' && /^http:\/\//.test(url)) {
url = url.replace(/^http:\/\//, 'https://');
}
xhr.open('GET', url, true);
if (this.byteRange) {
xhr.setRequestHeader('Range', 'bytes=' + this.byteRange);
}
xhr.responseType = this.responseType;
this.stats.tfirst = null;
this.stats.loaded = 0;
if (this.xhrSetup) {
this.xhrSetup(xhr, url);
}
this.timeoutHandle = window.setTimeout(this.loadtimeout.bind(this), this.timeout);
xhr.send();
}
}, {
key: 'loadend',
value: function loadend(event) {
var xhr = event.currentTarget,
status = xhr.status,
stats = this.stats;
// don't proceed if xhr has been aborted
if (!stats.aborted) {
// http status between 200 to 299 are all successful
if (status >= 200 && status < 300) {
window.clearTimeout(this.timeoutHandle);
stats.tload = performance.now();
this.onSuccess(event, stats);
} else {
// error ...
if (stats.retry < this.maxRetry) {
_logger.logger.warn(status + ' while loading ' + this.url + ', retrying in ' + this.retryDelay + '...');
this.destroy();
this.retryHandle = window.setTimeout(this.loadInternal.bind(this), this.retryDelay);
// exponential backoff
this.retryDelay = Math.min(2 * this.retryDelay, 64000);
stats.retry++;
} else {
window.clearTimeout(this.timeoutHandle);
_logger.logger.error(status + ' while loading ' + this.url);
this.onError(event);
}
}
}
}
}, {
key: 'loadtimeout',
value: function loadtimeout(event) {
_logger.logger.warn('timeout while loading ' + this.url);
this.onTimeout(event, this.stats);
}
}, {
key: 'loadprogress',
value: function loadprogress(event) {
var stats = this.stats;
if (stats.tfirst === null) {
stats.tfirst = performance.now();
}
stats.loaded = event.loaded;
if (event.lengthComputable) {
stats.total = event.total;
}
if (this.onProgress) {
this.onProgress(stats);
}
}
}]);
return XhrLoader;
}();
exports.default = XhrLoader;
},{"../utils/logger":38}],42:[function(require,module,exports){
'use strict';
var EventEmitter = require('eventemitter3');
var E = module.exports = HlsProv;
var ls = window.localStorage;
var provider_name = 'Hola JW HLS provider';
var provider_attached = false, provider_disabled = false;
var script_conf = (function script_conf_init(){
var attrs = {register: 'register-percent', manual_init: 'manual-init'};
var script = document.currentScript||
document.querySelector('#hola_jwplayer_hls_provider');
if (!script)
return {};
var rpercent = '{[=it.HOLA_REGISTER_PERCENT]}';
if (rpercent.startsWith('{['))
{
if (!script.hasAttribute(attrs.register))
return {};
rpercent = +script.getAttribute(attrs.register);
}
if (isNaN(rpercent)||rpercent<0||rpercent>100)
{
console.error(provider_name+': invalid '+attrs.register+
' attribute, expected a value between 0 and 100 but '+
script.getAttribute(attrs.register)+' found');
return {disabled: true};
}
if (ls && ls.getItem('hola_provider_register_percent'))
{
rpercent = +ls.getItem('hola_provider_register_percent');
console.info(provider_name+': '+attrs.register+' forced to '+rpercent+
'% by localStorage configuration');
}
return {autoinit: !script.hasAttribute(attrs.manual_init),
disabled: !rpercent||Math.random()*100>rpercent};
})();
// XXX arik: protect against exceptions in api. currently jwplayer will be
// stuck + add test
function HlsProv(id){
var jwplayer = E.jwplayer||window.jwplayer, Hls = E.Hls||window.Hls;
var jwe = jwplayer.events, jw = id && jwplayer(id);
jw.provider = this;
function empty_fn(name){ return function(){}; }
var _this = this;
this.hls_restore_pos = function(){
var new_pos = this.hls_queued.seek;
var old_pos = video.currentTime;
if (hls.streamController.state == 'STOPPED')
{
// XXX pavelki: hack to use our start position
hls.streamController.startPosition = 0;
hls.startLoad(new_pos||0);
}
if (!new_pos)
return;
this._in_seek = true;
video.currentTime = new_pos;
this.trigger(jwe.JWPLAYER_MEDIA_SEEK, {position: old_pos,
offset: new_pos});
// XXX pavelki: hack to override W3 algorithm of media
// seeking: when video element has HAVE_NOTHING state,
// seeking event doesn't fire and loading doesn't start
if (!video.readyState)
video.dispatchEvent(new Event('seeking'));
this.hls_queued.seek = 0;
};
function hls_play(){
if (!(_this.hls_queued.play = _this.hls_state!='ready'))
{
_this.hls_restore_pos();
video.play();
}
}
function hls_load(src){
if (!src)
return;
if (_this.hls_state=='ready')
_this.hls_state = 'idle';
_this.level_cb = function(){
hls.off(Hls.Events.LEVEL_LOADED, _this.level_cb);
_this.level_cb = undefined;
_this.hls_state = 'ready';
if (_this.hls_queued.play)
hls_play();
_this.trigger(jwe.JWPLAYER_MEDIA_BUFFER_FULL);
};
hls.on(Hls.Events.LEVEL_LOADED, _this.level_cb);
hls.loadSource(src);
if (!hls.media)
_this.attachMedia();
}
function get_default_src(sources){
return sources &&
sources.find(function(s){ return s.default; }) || sources[0];
}
function _log(method, message){
if (_this.hls.hola_log && _this.hls.hola_log[method])
_this.hls.hola_log[method].call(_this.hls.hola_log, message);
}
// XXX marka: jwplayer inherits provider from DefaultProvider, so it will
// override our inheritance from EventEmitter, do it manually
this.events = new EventEmitter();
this.addEventListener = this.on = this.events.on.bind(this.events);
this.once = this.events.once.bind(this.events);
this.removeEventListener = this.off = this.events.off.bind(this.events);
this.trigger = this.emit = function(e){
var args = [].slice.call(arguments);
_this.events.emit.apply(this.events, args);
if (e!='all')
{
args.unshift('all');
_this.events.emit.apply(this.events, args);
}
};
this.removeAllListeners = function(e){
this.events.removeAllListeners(e); };
this.hls_queued = {play: false, seek: 0};
this.attached = true;
this.hls_state = 'idle';
this.supports_captions = function(){
var ua = navigator.userAgent;
return /(iPhone|iPad|iPod|iPod touch);.*?OS/.test(ua)
|| / (Chrome|Version)\/\d+(\.\d+)+.* Safari\/\d+(\.\d+)+/.test(ua)
|| /Firefox\/(\d+(?:\.\d+)+)/.test(ua);
};
var element = document.getElementById(id), container;
var video = element ? element.querySelector('video') : undefined, hls;
video = video || document.createElement('video');
video.className = 'jw-video jw-reset';
// XXX marka: mark html5 element to skip autodetection of dm/hls
video.hola_dm_hls_attached = true;
// XXX pavelki: hack to override ozee's wrong src set
var o = video;
while (o && !(o = Object.getPrototypeOf(o)).hasOwnProperty('src'));
if (o)
{
var prop = Object.getOwnPropertyDescriptor(o, 'src');
Object.defineProperty(video, 'src', {
configurable: true,
enumerable: false,
set: function(src){
if (src == prop.get.call(video)+'?')
return;
prop.set.call(video, src);
},
get: prop.get,
});
}
var hls_params = {}, hola_log;
this.ad_count = 0;
if (jw)
{
jw.on('captionsList', caption_track);
jw.on('captionsChanged', caption_track);
// XXX pavelki: counters for ad, need to make loading deferred
jw.on('adImpression', function(){
_this.ad_count++;
});
jw.on('adComplete', function(){ _this.ad_count--; });
jw.on('adSkipped', function(){ _this.ad_count--; });
Object.assign(hls_params, jw.hola_config);
if (hls_params.debug!='undefined')
{
hola_log = hls_params.debug;
delete hls_params.debug;
}
}
hls_params.debug = {};
['debug', 'info', 'log', 'warn','error'].forEach(function(method){
hls_params.debug[method] = _log.bind(null, method); });
this.hls = hls = new Hls(hls_params);
hls.hola_log = hola_log;
if (jw)
jw.hls = hls;
var _buffered, _duration, _position;
function caption_track(cc){
if (!_this.renderNatively)
return;
var tracks = video.textTracks, new_id = cc.tracks[cc.track].id;
for (var i=0; i<tracks.length; i++)
tracks[i].mode = tracks[i]._id==new_id ? 'showing' : 'hidden';
}
function get_seekable_end(){
var i, end, len = video.seekable ? video.seekable.length : 0;
for (end = 0, i = 0; i<len; i++)
end = Math.max(end, video.seekable.end(i));
return end;
}
function get_duration(){
var duration = video.duration, end = get_seekable_end();
if (duration==Infinity && end)
{
var seekable_dur = end-video.seekable.start(0);
if (seekable_dur!=Infinity && seekable_dur>120)
duration = -seekable_dur;
}
return duration;
}
function get_duration_inf(){
return is_live() ? 1/0 : get_duration();
}
function is_live(){
var live, sc;
try {
sc = hls.streamController;
live = sc.levels[sc.currentLevel].details.live;
} catch(e){}
return live;
}
function get_buffered(){
var buf = video.buffered, dur = video.duration;
if (!buf || !buf.length || dur<=0 || dur==Infinity)
return 0;
return Math.min(buf.end(buf.length-1)/dur, 1.0);
}
function set_buffered(buffered, pos, duration){
if (buffered==_buffered && duration==_duration)
return;
_buffered = buffered;
_this.trigger(jwe.JWPLAYER_MEDIA_BUFFER, {bufferPercent: buffered*100,
position: pos, duration: get_duration_inf()});
}
function playback_complete(){
_this.setState('complete');
_this.before_complete = false;
_this.trigger(jwe.JWPLAYER_MEDIA_COMPLETE);
}
var video_listeners = {
durationchange: function(){
_duration = get_duration();
set_buffered(get_buffered(), _position, _duration);
},
ended: function(){
if (_this.state=='idle' || _this.state=='complete')
return;
_this.before_complete = true;
_this.trigger(jwe.JWPLAYER_MEDIA_BEFORECOMPLETE);
if (_this.attached)
playback_complete();
},
error: function(){
_this.trigger(jwe.JWPLAYER_MEDIA_ERROR, {
message: 'Error loading media: File could not be played'});
},
loadstart: function(){ video.setAttribute('jw-loaded', 'started'); },
loadeddata: function(){
video.setAttribute('jw-loaded', 'data');
if (!_this.supports_captions())
return;
video.textTracks.onaddtrack = function(){
_this.renderNatively = true;
_this.trigger('subtitlesTracks', {tracks: video.textTracks});
};
// XXX pavelki: add checking of playlist
if (video.textTracks.length)
video.textTracks.onaddtrack();
},
loadedmetadata: function(){
if (video.muted)
{
video.muted = false;
video.muted = true;
}
video.setAttribute('jw-loaded', 'meta');
_duration = get_duration();
_this.trigger(jwe.JWPLAYER_MEDIA_META, {duration:
get_duration_inf(), height: video.videoHeight,
width: video.videoWidth});
},
canplay: function(){ _this.trigger(jwe.JWPLAYER_MEDIA_BUFFER_FULL); },
playing: function(){
_this.setState('playing');
if (!video.hasAttribute('jw-played'))
video.setAttribute('jw-played', '');
_this.trigger(jwe.JWPLAYER_PROVIDER_FIRST_FRAME, {});
},
pause: function(){
if (_this.state=='complete' || video.currentTime==video.duration)
return;
_this.setState('paused');
},
seeking: function(){
if (!_this._in_seek)
{
_this._in_seek = true;
_this.trigger(jwe.JWPLAYER_MEDIA_SEEK, {position: _position,
offset: video.currentTime});
}
},
seeked: function(){
_this._in_seek = false;
_this.trigger(jwe.JWPLAYER_MEDIA_SEEKED);
},
progress: function(){
set_buffered(get_buffered(), _position, _duration); },
timeupdate: function(){
_duration = get_duration();
_position = _duration<0 ? -(get_seekable_end()-video.currentTime) :
video.currentTime;
set_buffered(get_buffered(), _position, _duration);
if (_this.state=='playing')
{
_this.trigger(jwe.JWPLAYER_MEDIA_TIME, {position: _position,
duration: get_duration_inf()});
}
},
};
function wrap_gen(e){
return function(){
if (!_this.attached)
return;
video_listeners[e]();
};
}
for (var e in video_listeners)
video.addEventListener(e, wrap_gen(e), false);
function scaled_number(num){
if (num===undefined)
return '';
if (!num)
return '0';
var k = 1024;
var sizes = ['', 'K', 'M', 'G', 'T', 'P'];
var i = Math.floor(Math.log(num)/Math.log(k));
num /= Math.pow(k, i);
if (num<0.001)
return '0';
if (num>=k-1)
num = Math.trunc(num);
var str = num.toFixed(num<1 ? 3 : num<10 ? 2 : num<100 ? 1 : 0);
return str.replace(/\.0*$/, '')+sizes[i];
}
// XXX yurij: duplicate from videojs5-hlsjs to avoid deps
function level_label(level){
if (level.height)
return level.height+'p';
if (level.width)
return Math.round(level.width*9/16)+'p';
if (level.bitrate)
return scaled_number(level.bitrate)+'bps';
return 0;
}
function get_levels(){
// level 0 mimics native jw's hls provider behavior
var levels = [{bitrate: 1, width: 1, height: 1, label: 'Auto'}];
hls.levels.forEach(function(level){
levels.push({bitrate: level.bitrate, height: level.height,
label: level_label(level), width: level.width});
});
return levels;
}
hls.on(Hls.Events.ERROR, function(event, data){
if (!data.fatal)
return;
var msg;
switch (data.details)
{
case Hls.ErrorDetails.MANIFEST_LOAD_ERROR:
case Hls.ErrorDetails.MANIFEST_LOAD_TIMEOUT:
msg = 'Cannot load M3U8: '+data.response.statusText;
break;
default:
msg = 'Error loading media: '+data.details;
break;
}
_this.trigger(jwe.JWPLAYER_MEDIA_ERROR, {message: msg});
});
hls.on(Hls.Events.MANIFEST_LOADED, function(){
_this.trigger(jwe.JWPLAYER_MEDIA_LEVELS, {
currentQuality: hls.autoLevelEnabled ? 0 : hls.currentLevel+1,
levels: get_levels()
});
});
hls.on(Hls.Events.LEVEL_SWITCH, function(e, data){
_this.trigger(jwe.JWPLAYER_MEDIA_LEVEL_CHANGED, {
// level 0 is dummy for 'Auto' option in jwplayer's UI
currentQuality: hls.manual_level==-1 ? 0 : data.level+1,
levels: get_levels()
});
});
this.init = function(item){ video.setAttribute('jw-loaded', 'init'); };
this.load = function(item){
if (!this.attached)
return;
var newsource = get_default_src(item.sources).file;
var video_state = video.getAttribute('jw-loaded');
var hq = this.hls_queued;
this.setState('loading');
hq.seek = Math.max(item.starttime-(hq.rw_sec||0), 0);
if (this.hls_state!='ready' || (this.source||'') != newsource ||
['init', 'started'].includes(video_state))
{
video.load();
hls.stopLoad();
hls_load(this.source = newsource);
video.setAttribute('jw-loaded', 'init');
}
else
hls_play();
};
this.play = function(){ hls_play(); };
this.pause = function(){
video.pause();
_this.setState('paused');
};
this.stop = function(){
hls.stopLoad();
_this.setState('idle');
};
this.volume = function(vol){ video.volume = Math.min(vol/100, 1.0); };
this.mute = function(state){ video.muted = !!state; };
this.seek = function(pos){
this._in_seek = true;
if (this.hls_state=='ready')
{
var sv = video.currentTime;
video.currentTime = pos;
this.trigger(jwe.JWPLAYER_MEDIA_SEEK, {position: sv, offset: pos});
}
else
this.hls_queued.seek = pos;
};
// XXX arik: todo, without it video resize will be wrong.
// eg. http://www.ozee.com/shows/muddha-mandaram#hola_mode=cdn&hola_zone=ozee_hap
this.resize = function(width, height, stretching){};
this.remove = function(){
this.in_container = false;
hls.stopLoad();
this.source = undefined;
if (container === video.parentNode)
container.removeChild(video);
};
this.destroy = function(){
for (var e in video_listeners)
video.removeEventListener(e, video_listeners[e], false);
this.removeAllListeners();
};
this.setVisibility = function(state){
container.style.visibility = state ? 'visible' : '';
container.style.opacity = state ? 1 : 0;
};
this.setFullscreen = function(){ return false; };
this.getFullscreen = empty_fn('getFullscreen');
this.getContainer = function(){ return container; };
this.setContainer = function(element){
container = element;
container.appendChild(video);
this.in_container = true;
};
hls.manual_level = -1;
this.setCurrentQuality = function(level){
if (level == hls.manual_level+1)
return;
hls.manual_level = level-1;
if (!hls.hola_adaptive)
hls.loadLevel = hls.manual_level;
_this.trigger(jwe.JWPLAYER_MEDIA_LEVEL_CHANGED,
{currentQuality: level, levels: get_levels()});
};
this.getName = function(){ return {name: 'dm/hls'}; };
this.get_position = function(){ return video.currentTime; };
this.getQualityLevels = function(){ return get_levels(); };
this.getCurrentQuality = function(){ return hls.loadLevel+1; };
this.getAudioTracks = empty_fn('getAudioTracks');
this.getCurrentAudioTrack = empty_fn('getCurrentAudioTrack');
this.setCurrentAudioTrack = empty_fn('setCurrentAudioTrack');
this.checkComplete = function(){ return !!this.before_complete; };
this.setControls = empty_fn('setControls');
this.attachMedia = function(){
if (this.before_complete)
return playback_complete();
if (this.ad_count && hls_params.debug)
hls_params.debug.log('jwprovider attach inside ad '+this.ad_count);
this.attached = true;
hls.attachMedia(video);
};
this.detachMedia = function(){
hls.trigger(Hls.Events.BUFFER_RESET);
hls.detachMedia();
if (this.level_cb)
{
hls.off(Hls.Events.LEVEL_LOADED, this.level_cb);
this.level_cb = undefined;
}
// XXX pavelki: hack to remove pending segments
delete hls.bufferController.segments;
this.attached = false;
// XXX yurij: remove when detachMedia->bufferring issue fixed
this.setState('paused');
return video;
};
this.setState = function(state){
var oldState = this.state||'idle';
this.state = state;
if (state==oldState)
return;
this.trigger(jwe.JWPLAYER_PLAYER_STATE, {newstate: state});
};
this.sendMediaType = function(levels){
var is_audio = ['oga', 'aac', 'mp3', 'mpeg', 'vorbis']
.includes(levels[0].type);
this.trigger(jwe.JWPLAYER_MEDIA_TYPE, {mediaType: is_audio ?
'audio' : 'video'});
};
}
E.getName = function(){ return {name: 'dm/hls'}; };
// XXX yurij: copied from zjwplayer3.js to not depend on our code
function get_player_instances(){
var jwplayer = E.jwplayer||window.jwplayer;
var i = 0, res = [], jw;
// XXX marka/vadiml: a real instance will contain pause(), otherwise it
// will be {registerPlugin: ...} with anything the customer adds
while ((jw = jwplayer(i++)) && jw.pause)
res.push(jw);
return res;
}
E.supports = function(src){
var Hls = E.Hls||window.Hls;
var is_ad = get_player_instances().every(function(j){
// XXX yurij: jw.getPlaylist returns playlist item on early call
var pl = j.getPlaylist();
return (pl.every ? pl : [{sources: [pl]}]).every(function(p){
// XXX pavlo: playlist item can be w/o sources/allSources
return (p.allSources||p.sources||[{file: p.file}])
.every(function(s){ return s.file!=src.file; });
});
});
if (is_ad) // XXX yurij: we are not supporting adaptive ads
return false;
return !E.disabled && src.type=='hls' && Hls && Hls.isSupported();
};
E.attach = function(){
var jwplayer = E.jwplayer||window.jwplayer;
provider_disabled = false;
if (!provider_attached)
{
provider_attached = true;
// XXX arik: unregister on error/fallback
jwplayer.api.registerProvider(this);
}
};
E.detach = function(){
// we don't remove provider from list, just set it as disabled so it will
// return false in supports()
provider_disabled = true;
};
// XXX vadiml copied from loader.js&zjwplayer3.js to not depend on our code.
// For use by HolaCDN Onboarding Tool extension
E.reload_jwplayer_instances = function(){
get_player_instances().forEach(function(jw){
var c = jw.getConfig();
if (!c)
return;
// XXX marka: JW removes conf.advertising.client, try to restore it
if (c.advertising && !c.advertising.client && c.plugins)
{
for (var url in c.plugins)
{
if (c.plugins[url]!==c.advertising)
continue;
var m = url.match(/\/(\w+)\.js$/);
c.advertising.client = m && m[1];
break;
}
}
jw.setup(c);
});
};
E.VERSION = '0.0.39';
if (script_conf.disabled)
E.attach = E.detach = E.supports = function(){};
else if (script_conf.autoinit)
E.attach();
},{"eventemitter3":43}],43:[function(require,module,exports){
'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
* @api 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 {Mixed} context The context to invoke the listener with.
* @param {Boolean} [once=false] Specify if the listener is a one-time listener.
* @constructor
* @api private
*/
function EE(fn, context, once) {
this.fn = fn;
this.context = context;
this.once = once || false;
}
/**
* Minimal `EventEmitter` interface that is molded against the Node.js
* `EventEmitter` interface.
*
* @constructor
* @api 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}
* @api 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.
* @param {Boolean} exists Only check if there are listeners.
* @returns {Array|Boolean}
* @api public
*/
EventEmitter.prototype.listeners = function listeners(event, exists) {
var evt = prefix ? prefix + event : event
, available = this._events[evt];
if (exists) return !!available;
if (!available) return [];
if (available.fn) return [available.fn];
for (var i = 0, l = available.length, ee = new Array(l); i < l; i++) {
ee[i] = available[i].fn;
}
return ee;
};
/**
* 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`.
* @api 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 {Mixed} [context=this] The context to invoke the listener with.
* @returns {EventEmitter} `this`.
* @api public
*/
EventEmitter.prototype.on = function on(event, fn, context) {
var listener = new EE(fn, context || this)
, evt = prefix ? prefix + event : event;
if (!this._events[evt]) this._events[evt] = listener, this._eventsCount++;
else if (!this._events[evt].fn) this._events[evt].push(listener);
else this._events[evt] = [this._events[evt], listener];
return this;
};
/**
* Add a one-time listener for a given event.
*
* @param {String|Symbol} event The event name.
* @param {Function} fn The listener function.
* @param {Mixed} [context=this] The context to invoke the listener with.
* @returns {EventEmitter} `this`.
* @api public
*/
EventEmitter.prototype.once = function once(event, fn, context) {
var listener = new EE(fn, context || this, true)
, evt = prefix ? prefix + event : event;
if (!this._events[evt]) this._events[evt] = listener, this._eventsCount++;
else if (!this._events[evt].fn) this._events[evt].push(listener);
else this._events[evt] = [this._events[evt], listener];
return this;
};
/**
* 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 {Mixed} context Only remove the listeners that have this context.
* @param {Boolean} once Only remove one-time listeners.
* @returns {EventEmitter} `this`.
* @api public
*/
EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
var evt = prefix ? prefix + event : event;
if (!this._events[evt]) return this;
if (!fn) {
if (--this._eventsCount === 0) this._events = new Events();
else delete this._events[evt];
return this;
}
var listeners = this._events[evt];
if (listeners.fn) {
if (
listeners.fn === fn
&& (!once || listeners.once)
&& (!context || listeners.context === context)
) {
if (--this._eventsCount === 0) this._events = new Events();
else delete this._events[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 if (--this._eventsCount === 0) this._events = new Events();
else delete this._events[evt];
}
return this;
};
/**
* Remove all listeners, or those of the specified event.
*
* @param {String|Symbol} [event] The event name.
* @returns {EventEmitter} `this`.
* @api public
*/
EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
var evt;
if (event) {
evt = prefix ? prefix + event : event;
if (this._events[evt]) {
if (--this._eventsCount === 0) this._events = new Events();
else delete this._events[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;
//
// This function doesn't apply anymore.
//
EventEmitter.prototype.setMaxListeners = function setMaxListeners() {
return this;
};
//
// Expose the prefix.
//
EventEmitter.prefixed = prefix;
//
// Allow `EventEmitter` to be imported as module namespace.
//
EventEmitter.EventEmitter = EventEmitter;
//
// Expose the module.
//
if ('undefined' !== typeof module) {
module.exports = EventEmitter;
}
},{}],44:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// 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 EventEmitter() {
this._events = this._events || {};
this._maxListeners = this._maxListeners || undefined;
}
module.exports = EventEmitter;
// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = undefined;
EventEmitter.prototype._maxListeners = undefined;
// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
EventEmitter.defaultMaxListeners = 10;
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function(n) {
if (!isNumber(n) || n < 0 || isNaN(n))
throw TypeError('n must be a positive number');
this._maxListeners = n;
return this;
};
EventEmitter.prototype.emit = function(type) {
var er, handler, len, args, i, listeners;
if (!this._events)
this._events = {};
// If there is no 'error' event listener then throw.
if (type === 'error') {
if (!this._events.error ||
(isObject(this._events.error) && !this._events.error.length)) {
er = arguments[1];
if (er instanceof Error) {
throw er; // Unhandled 'error' event
} else {
// At least give some kind of context to the user
var err = new Error('Uncaught, unspecified "error" event. (' + er + ')');
err.context = er;
throw err;
}
}
}
handler = this._events[type];
if (isUndefined(handler))
return false;
if (isFunction(handler)) {
switch (arguments.length) {
// fast cases
case 1:
handler.call(this);
break;
case 2:
handler.call(this, arguments[1]);
break;
case 3:
handler.call(this, arguments[1], arguments[2]);
break;
// slower
default:
args = Array.prototype.slice.call(arguments, 1);
handler.apply(this, args);
}
} else if (isObject(handler)) {
args = Array.prototype.slice.call(arguments, 1);
listeners = handler.slice();
len = listeners.length;
for (i = 0; i < len; i++)
listeners[i].apply(this, args);
}
return true;
};
EventEmitter.prototype.addListener = function(type, listener) {
var m;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events)
this._events = {};
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (this._events.newListener)
this.emit('newListener', type,
isFunction(listener.listener) ?
listener.listener : listener);
if (!this._events[type])
// Optimize the case of one listener. Don't need the extra array object.
this._events[type] = listener;
else if (isObject(this._events[type]))
// If we've already got an array, just append.
this._events[type].push(listener);
else
// Adding the second element, need to change to array.
this._events[type] = [this._events[type], listener];
// Check for listener leak
if (isObject(this._events[type]) && !this._events[type].warned) {
if (!isUndefined(this._maxListeners)) {
m = this._maxListeners;
} else {
m = EventEmitter.defaultMaxListeners;
}
if (m && m > 0 && this._events[type].length > m) {
this._events[type].warned = true;
console.error('(node) warning: possible EventEmitter memory ' +
'leak detected. %d listeners added. ' +
'Use emitter.setMaxListeners() to increase limit.',
this._events[type].length);
if (typeof console.trace === 'function') {
// not supported in IE 10
console.trace();
}
}
}
return this;
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.once = function(type, listener) {
if (!isFunction(listener))
throw TypeError('listener must be a function');
var fired = false;
function g() {
this.removeListener(type, g);
if (!fired) {
fired = true;
listener.apply(this, arguments);
}
}
g.listener = listener;
this.on(type, g);
return this;
};
// emits a 'removeListener' event iff the listener was removed
EventEmitter.prototype.removeListener = function(type, listener) {
var list, position, length, i;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events || !this._events[type])
return this;
list = this._events[type];
length = list.length;
position = -1;
if (list === listener ||
(isFunction(list.listener) && list.listener === listener)) {
delete this._events[type];
if (this._events.removeListener)
this.emit('removeListener', type, listener);
} else if (isObject(list)) {
for (i = length; i-- > 0;) {
if (list[i] === listener ||
(list[i].listener && list[i].listener === listener)) {
position = i;
break;
}
}
if (position < 0)
return this;
if (list.length === 1) {
list.length = 0;
delete this._events[type];
} else {
list.splice(position, 1);
}
if (this._events.removeListener)
this.emit('removeListener', type, listener);
}
return this;
};
EventEmitter.prototype.removeAllListeners = function(type) {
var key, listeners;
if (!this._events)
return this;
// not listening for removeListener, no need to emit
if (!this._events.removeListener) {
if (arguments.length === 0)
this._events = {};
else if (this._events[type])
delete this._events[type];
return this;
}
// emit removeListener for all listeners on all events
if (arguments.length === 0) {
for (key in this._events) {
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = {};
return this;
}
listeners = this._events[type];
if (isFunction(listeners)) {
this.removeListener(type, listeners);
} else if (listeners) {
// LIFO order
while (listeners.length)
this.removeListener(type, listeners[listeners.length - 1]);
}
delete this._events[type];
return this;
};
EventEmitter.prototype.listeners = function(type) {
var ret;
if (!this._events || !this._events[type])
ret = [];
else if (isFunction(this._events[type]))
ret = [this._events[type]];
else
ret = this._events[type].slice();
return ret;
};
EventEmitter.prototype.listenerCount = function(type) {
if (this._events) {
var evlistener = this._events[type];
if (isFunction(evlistener))
return 1;
else if (evlistener)
return evlistener.length;
}
return 0;
};
EventEmitter.listenerCount = function(emitter, type) {
return emitter.listenerCount(type);
};
function isFunction(arg) {
return typeof arg === 'function';
}
function isNumber(arg) {
return typeof arg === 'number';
}
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
function isUndefined(arg) {
return arg === void 0;
}
},{}],45:[function(require,module,exports){
var bundleFn = arguments[3];
var sources = arguments[4];
var cache = arguments[5];
var stringify = JSON.stringify;
module.exports = function (fn, options) {
var wkey;
var cacheKeys = Object.keys(cache);
for (var i = 0, l = cacheKeys.length; i < l; i++) {
var key = cacheKeys[i];
var exp = cache[key].exports;
// Using babel as a transpiler to use esmodule, the export will always
// be an object with the default export as a property of it. To ensure
// the existing api and babel esmodule exports are both supported we
// check for both
if (exp === fn || exp && exp.default === fn) {
wkey = key;
break;
}
}
if (!wkey) {
wkey = Math.floor(Math.pow(16, 8) * Math.random()).toString(16);
var wcache = {};
for (var i = 0, l = cacheKeys.length; i < l; i++) {
var key = cacheKeys[i];
wcache[key] = key;
}
sources[wkey] = [
Function(['require','module','exports'], '(' + fn + ')(self)'),
wcache
];
}
var skey = Math.floor(Math.pow(16, 8) * Math.random()).toString(16);
var scache = {}; scache[wkey] = wkey;
sources[skey] = [
Function(['require'], (
// try to call default if defined to also support babel esmodule
// exports
'var f = require(' + stringify(wkey) + ');' +
'(f.default ? f.default : f)(self);'
)),
scache
];
var workerSources = {};
resolveSources(skey);
function resolveSources(key) {
workerSources[key] = true;
for (var depPath in sources[key][1]) {
var depKey = sources[key][1][depPath];
if (!workerSources[depKey]) {
resolveSources(depKey);
}
}
}
var src = '(' + bundleFn + ')({'
+ Object.keys(workerSources).map(function (key) {
return stringify(key) + ':['
+ sources[key][0]
+ ',' + stringify(sources[key][1]) + ']'
;
}).join(',')
+ '},{},[' + stringify(skey) + '])'
;
var URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
var blob = new Blob([src], { type: 'text/javascript' });
if (options && options.bare) { return blob; }
var workerUrl = URL.createObjectURL(blob);
var worker = new Worker(workerUrl);
worker.objectURL = workerUrl;
return worker;
};
},{}]},{},[1])(1)
});
//# sourceMappingURL=hola_jwplayer_hls.js.map
|
/*!
* Module dependencies.
*/
var _ = require('underscore'),
moment = require('moment'),
keystone = require('../../'),
async = require('async'),
util = require('util'),
azure = require('azure'),
utils = require('keystone-utils'),
super_ = require('../field');
/**
* AzureFile FieldType Constructor
* @extends Field
* @api public
*/
function azurefile(list, path, options) {
this._underscoreMethods = ['format', 'uploadFile'];
// event queues
this._pre = {
upload: []
};
// TODO: implement filtering, usage disabled for now
options.nofilter = true;
// TODO: implement initial form, usage disabled for now
if (options.initial) {
throw new Error('Invalid Configuration\n\nAzureFile fields (' + list.key + '.' + path + ') do not currently support being used as initial fields.\n');
}
azurefile.super_.call(this, list, path, options);
// validate azurefile config (has to happen after super_.call)
if (!this.azurefileconfig) {
throw new Error('Invalid Configuration\n\n' +
'AzureFile fields (' + list.key + '.' + path + ') require the "azurefile config" option to be set.\n\n' +
'See http://keystonejs.com/docs/configuration#services-azure for more information.\n');
}
process.env.AZURE_STORAGE_ACCOUNT = this.azurefileconfig.account;
process.env.AZURE_STORAGE_ACCESS_KEY = this.azurefileconfig.key;
this.azurefileconfig.container = this.azurefileconfig.container || 'keystone';
options.filenameFormatter = options.filenameFormatter || function(item, filename) { return filename; };
options.containerFormatter = options.containerFormatter || function(item, filename) { return self.azurefileconfig.container; };
// Could be more pre- hooks, just upload for now
if (options.pre && options.pre.upload) {
this._pre.upload = this._pre.upload.concat(options.pre.upload);
}
}
/*!
* Inherit from Field
*/
util.inherits(azurefile, super_);
/**
* Exposes the custom or keystone s3 config settings
*/
Object.defineProperty(azurefile.prototype, 'azurefileconfig', { get: function() {
return this.options.azurefileconfig || keystone.get('azurefile config');
}});
/**
* Allows you to add pre middleware after the field has been initialised
*
* @api public
*/
azurefile.prototype.pre = function(event, fn) {
if (!this._pre[event]) {
throw new Error('AzureFile (' + this.list.key + '.' + this.path + ') error: azurefile.pre()\n\n' +
'Event ' + event + ' is not supported.\n');
}
this._pre[event].push(fn);
return this;
};
/**
* Registers the field on the List's Mongoose Schema.
*
* @api public
*/
azurefile.prototype.addToSchema = function() {
var field = this,
schema = this.list.schema;
var paths = this.paths = {
// fields
filename: this._path.append('.filename'),
path: this._path.append('.path'),
size: this._path.append('.size'),
filetype: this._path.append('.filetype'),
url: this._path.append('.url'),
etag: this._path.append('.etag'),
container: this._path.append('.container'),
// virtuals
exists: this._path.append('.exists'),
upload: this._path.append('_upload'),
action: this._path.append('_action')
};
var schemaPaths = this._path.addTo({}, {
filename: String,
path: String,
size: Number,
filetype: String,
url: String,
etag: String,
container: String
});
schema.add(schemaPaths);
var exists = function(item) {
return (item.get(paths.url) ? true : false);
};
// The .exists virtual indicates whether a file is stored
schema.virtual(paths.exists).get(function() {
return schemaMethods.exists.apply(this);
});
var reset = function(item) {
item.set(field.path, {
filename: '',
path: '',
size: 0,
filetype: '',
url: ''
});
};
var schemaMethods = {
exists: function() {
return exists(this);
},
/**
* Resets the value of the field
*
* @api public
*/
reset: function() {
var self = this;
try {
azure.createBlobService().deleteBlob(this.get(paths.container), this.get(paths.filename), function(error) {});
} catch(e) {}
reset(self);
},
/**
* Deletes the file from AzureFile and resets the field
*
* @api public
*/
delete: function() {
var self = this;
try {
azure.createBlobService().blobService.deleteBlob(this.get(paths.container), this.get(paths.filename), function(error) {
if(!error){}
});
} catch(e) {}
reset(self);
}
};
_.each(schemaMethods, function(fn, key) {
field.underscoreMethod(key, fn);
});
// expose a method on the field to call schema methods
this.apply = function(item, method) {
return schemaMethods[method].apply(item, Array.prototype.slice.call(arguments, 2));
};
this.bindUnderscoreMethods();
};
/**
* Formats the field value
*
* @api public
*/
azurefile.prototype.format = function(item) {
return item.get(this.paths.url);
};
/**
* Detects whether the field has been modified
*
* @api public
*/
azurefile.prototype.isModified = function(item) {
return item.isModified(this.paths.url);
};
/**
* Validates that a value for this field has been provided in a data object
*
* @api public
*/
azurefile.prototype.validateInput = function(data) {
// TODO - how should file field input be validated?
return true;
};
/**
* Updates the value for this field in the item from a data object
*
* @api public
*/
azurefile.prototype.updateItem = function(item, data) {
// TODO - direct updating of data (not via upload)
};
/**
* Uploads the file for this field
*
* @api public
*/
azurefile.prototype.uploadFile = function(item, file, update, callback) {
var field = this,
prefix = field.options.datePrefix ? moment().format(field.options.datePrefix) + '-' : '',
name = prefix + file.name;
if (field.options.allowedTypes && !_.contains(field.options.allowedTypes, file.type)){
return callback(new Error('Unsupported File Type: '+file.type));
}
if ('function' == typeof update) {
callback = update;
update = false;
}
var doUpload = function() {
var blobService = azure.createBlobService();
var container = field.options.containerFormatter(item, file.name);
blobService.createContainerIfNotExists(container, {publicAccessLevel : 'blob'}, function(error){
if(error){
return callback(error);
}
blobService.createBlockBlobFromFile(container, field.options.filenameFormatter(item, file.name), file.path, function(error, blob, res){
if(error){
return callback(error);
} else {
var fileData = {
filename: blob.blob,
size: file.size,
filetype: file.type,
etag: blob.etag,
container: container,
url: 'http://' + field.azurefileconfig.account + '.blob.core.windows.net/' + container + '/' + blob.blob
};
if (update) {
item.set(field.path, fileData);
}
callback(null, fileData);
}
});
});
};
async.eachSeries(this._pre.upload, function(fn, next) {
fn(item, file, next);
}, function(err) {
if (err) return callback(err);
doUpload();
});
};
/**
* Returns a callback that handles a standard form submission for the field
*
* Expected form parts are
* - `field.paths.action` in `req.body` (`clear` or `delete`)
* - `field.paths.upload` in `req.files` (uploads the file to s3file)
*
* @api public
*/
azurefile.prototype.getRequestHandler = function(item, req, paths, callback) {
var field = this;
if (utils.isFunction(paths)) {
callback = paths;
paths = field.paths;
} else if (!paths) {
paths = field.paths;
}
callback = callback || function() {};
return function() {
if (req.body) {
var action = req.body[paths.action];
if (/^(delete|reset)$/.test(action))
field.apply(item, action);
}
if (req.files && req.files[paths.upload] && req.files[paths.upload].size) {
return field.uploadFile(item, req.files[paths.upload], true, callback);
}
return callback();
};
};
/**
* Immediately handles a standard form submission for the field (see `getRequestHandler()`)
*
* @api public
*/
azurefile.prototype.handleRequest = function(item, req, paths, callback) {
this.getRequestHandler(item, req, paths, callback)();
};
/*!
* Export class
*/
exports = module.exports = azurefile;
|
var loadState = {
preload: function () {
game.stage.disableVisibilityChange = true
/*
Load all game assets
Place your load bar, some messages.
In this case of loading, only text is placed...
*/
var loadingLabel = game.add.text(80, 150, 'loading...', {font: '20px press_start_2pregular', fill: '#fff'});
//Load your images, spritesheets, bitmaps...
game.load.image('ship', 'assets/img/nave 4.png')
//background game
game.load.image('starfield', 'assets/img/campo_de_estrellas.png');
// homescreen background
game.load.image('background-414x736', 'assets/img/menú inicio/Inicio_414x736.png');
game.load.image('background-384x640', 'assets/img/menú inicio/Inicio_384x640.png');
game.load.image('background-360x640', 'assets/img/menú inicio/Inicio_360x640.png');
game.load.image('background-320x568', 'assets/img/menú inicio/Inicio_320x568.png');
//buttons
game.load.image('start', 'assets/img/start.png');
game.load.image('highScore', 'assets/img/hight score.png');
//sprites
game.load.spritesheet('bala', 'assets/img/balas/balas_1.png', 15, 15);
game.load.spritesheet('balaEnemigo', 'assets/img/balas/balas_4.png', 15, 15);
game.load.spritesheet('enemy', 'assets/img/invader.png', 45, 36 );
game.load.spritesheet('player', 'assets/img/nave4_explosión.png', 30, 15);
//Load your sounds, efx, music...
//Example: game.load.audio('rockas', 'assets/snd/rockas.wav');
game.load.audio('laser1', 'assets/sound/laser4.wav');
game.load.audio('laser2', 'assets/sound/laser5.wav');
game.load.audio('music', 'assets/sound/high tech lab.wav');
game.load.audio('explosion2', 'assets/sound/Explosion_02.wav');
game.load.audio('explosion1', 'assets/sound/Explosion.wav')
//Load your data, JSON, Querys...
//Example: game.load.json('version', 'http://phaser.io/version.json');
},
create: function () {
game.stage.setBackgroundColor('#000');
game.scale.fullScreenScaleMode = Phaser.ScaleManager.EXACT_FIT;
game.state.start('menu');
}
};
|
/**
* # manager/file
*
* Methods for loading files to the canvas and giving updates on their
* progress
*
* > http://draeton.github.io/stitches<br/>
* > Copyright 2013 Matthew Cobbs<br/>
* > Licensed under the MIT license.
*/
define([
"wrap/jquery",
"util/util"
],
function ($, util) {
"use strict";
// **Module definition**
return {
total: 0, // total count of files
processed: 0, // total count of processed files
queue: [], // queue after reading; used to process
/**
* ### file.set
* Set the file manager handlers
*
* @param {object} handlers The handlers for various events
*/
set: function (handlers) {
handlers = handlers || {};
this.onload = handlers.onload || util.noop;
this.onprogress = handlers.onprogress || util.noop;
this.onerror = handlers.onerror || util.noop;
},
/**
* ### @processFiles
* Reset the queue and start processing a list of files
*
* @param {array} files An array of files from one of the file inputs
*/
processFiles: function (files) {
var self = this;
this.total = files.length;
this.processed = 0;
this.queue = [];
$.map(files, function (file) {
if (/jpeg|png|gif/.test(file.type)) {
self.processFile(file);
}
});
this.onprogress(0, "info");
},
/**
* ### @processFile
* Use the FileReader to read in image files from input, and add
* them to the queue. When all files are read, the queue is then
* processed
*
* @param {object} file From a file input
*/
processFile: function (file) {
var self = this;
var reader;
try {
reader = new FileReader();
reader.onloadend = function (e) {
var name = file.name;
var src = e.target.result;
var progress = ++self.processed / self.total;
self.onprogress(progress);
self.queue.push([name, src]);
if (self.queue.length === self.total) {
self.processQueue();
}
};
reader.readAsDataURL(file);
} catch (e) {
this.onerror(e);
}
},
/**
* ### @processQueue
* Loop over the queue and apply the onload callback to each
* item
*/
processQueue: function () {
var self = this;
$.map(this.queue, function (args) {
self.onload.apply(self, args);
});
}
};
});
|
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
(function(global) {
global.ng = global.ng || {};
global.ng.common = global.ng.common || {};
global.ng.common.locales = global.ng.common.locales || {};
const u = undefined;
function plural(n) {
let i = Math.floor(Math.abs(n));
if (i === Math.floor(i) && i >= 0 && i <= 1) return 1;
return 5;
}
global.ng.common.locales['pt'] = [
'pt',
[['AM', 'PM'], u, u],
u,
[
['D', 'S', 'T', 'Q', 'Q', 'S', 'S'],
['dom.', 'seg.', 'ter.', 'qua.', 'qui.', 'sex.', 'sáb.'],
[
'domingo', 'segunda-feira', 'terça-feira', 'quarta-feira', 'quinta-feira', 'sexta-feira',
'sábado'
],
['dom.', 'seg.', 'ter.', 'qua.', 'qui.', 'sex.', 'sáb.']
],
u,
[
['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'],
[
'jan.', 'fev.', 'mar.', 'abr.', 'mai.', 'jun.', 'jul.', 'ago.', 'set.', 'out.', 'nov.',
'dez.'
],
[
'janeiro', 'fevereiro', 'março', 'abril', 'maio', 'junho', 'julho', 'agosto', 'setembro',
'outubro', 'novembro', 'dezembro'
]
],
u,
[['a.C.', 'd.C.'], u, ['antes de Cristo', 'depois de Cristo']],
0,
[6, 0],
['dd/MM/y', 'd \'de\' MMM \'de\' y', 'd \'de\' MMMM \'de\' y', 'EEEE, d \'de\' MMMM \'de\' y'],
['HH:mm', 'HH:mm:ss', 'HH:mm:ss z', 'HH:mm:ss zzzz'],
['{1} {0}', u, u, u],
[',', '.', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'NaN', ':'],
['#,##0.###', '#,##0%', '¤ #,##0.00', '#E0'],
'BRL',
'R$',
'Real brasileiro',
{
'AUD': ['AU$', '$'],
'JPY': ['JP¥', '¥'],
'PTE': ['Esc.'],
'RON': [u, 'L'],
'SYP': [u, 'S£'],
'THB': ['฿'],
'TWD': ['NT$'],
'USD': ['US$', '$']
},
'ltr',
plural,
[
[['meia-noite', 'meio-dia', 'da manhã', 'da tarde', 'da noite', 'da madrugada'], u, u],
[['meia-noite', 'meio-dia', 'manhã', 'tarde', 'noite', 'madrugada'], u, u],
[
'00:00', '12:00', ['06:00', '12:00'], ['12:00', '19:00'], ['19:00', '24:00'],
['00:00', '06:00']
]
]
];
})(typeof globalThis !== 'undefined' && globalThis || typeof global !== 'undefined' && global ||
typeof window !== 'undefined' && window);
|
class SpreadTestClass {
constructor(x, y) {
this.SpreadTestClass = SpreadTestClass;
this.self = this;
this.x = x;
this.y = y;
}
}
var object = new SpreadTestClass(...[0, 1]);
// ----------------------------------------------------------------------------
expect(object.x).toBe(0);
expect(object.y).toBe(1);
expect(object.self).toBe(object);
expect(object).toBeInstanceOf(object.SpreadTestClass);
|
import React from 'react';
import styles from './policyBanner.css';
const policyPageLink = '/policy';
// replace commented out bannertext below with new text if this component is needed for reuse in the future
const PolicyBanner = () => (
<div className={styles.banner}>
<h4 className={styles.bannerText}>
{/* On April 19, 2018, we're heading to Washington, D.C. to modernize the G.I. Bill.{' '} */}
<a href={policyPageLink} className={styles.bannerLink}>
Click here for details!
</a>
</h4>
</div>
);
export default PolicyBanner;
|
/*
Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang("widget","hr",{move:"Klikni i povuci da pomakneš",label:"%1 widget"});
|
import dns from 'dns';
import { Meteor } from 'meteor/meteor';
import { emailDomainDefaultBlackList } from './defaultBlockedDomainsList';
import { settings } from '../../../settings';
let emailDomainBlackList = [];
let emailDomainWhiteList = [];
let useDefaultBlackList = false;
let useDNSDomainCheck = false;
settings.get('Accounts_BlockedDomainsList', function(key, value) {
emailDomainBlackList = value.split(',').filter(Boolean).map((domain) => domain.trim());
});
settings.get('Accounts_AllowedDomainsList', function(key, value) {
emailDomainWhiteList = value.split(',').filter(Boolean).map((domain) => domain.trim());
});
settings.get('Accounts_UseDefaultBlockedDomainsList', function(key, value) {
useDefaultBlackList = value;
});
settings.get('Accounts_UseDNSDomainCheck', function(key, value) {
useDNSDomainCheck = value;
});
export const validateEmailDomain = function(email) {
const emailValidation = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
if (!emailValidation.test(email)) {
throw new Meteor.Error('error-invalid-email', `Invalid email ${ email }`, { function: 'RocketChat.validateEmailDomain', email });
}
const emailDomain = email.substr(email.lastIndexOf('@') + 1);
if (emailDomainWhiteList.length && !emailDomainWhiteList.includes(emailDomain)) {
throw new Meteor.Error('error-invalid-domain', 'The email domain is not in whitelist', { function: 'RocketChat.validateEmailDomain' });
}
if (emailDomainBlackList.length && (emailDomainBlackList.indexOf(emailDomain) !== -1 || (useDefaultBlackList && emailDomainDefaultBlackList.indexOf(emailDomain) !== -1))) {
throw new Meteor.Error('error-email-domain-blacklisted', 'The email domain is blacklisted', { function: 'RocketChat.validateEmailDomain' });
}
if (useDNSDomainCheck) {
try {
Meteor.wrapAsync(dns.resolveMx)(emailDomain);
} catch (e) {
throw new Meteor.Error('error-invalid-domain', 'Invalid domain', { function: 'RocketChat.validateEmailDomain' });
}
}
};
|
/**
* Heir v3.0.0 - http://git.io/F87mKg
* Oliver Caldwell - http://oli.me.uk/
* Unlicense - http://unlicense.org/
*/
(function (name, root, factory) {
if (typeof define === 'function' && define.amd) {
define(factory);
}
else if (typeof exports === 'object') {
module.exports = factory();
}
else {
root[name] = factory();
}
}('heir', this, function () {
/*global define,module*/
'use strict';
var heir = {
/**
* Causes your desired class to inherit from a source class. This uses
* prototypical inheritance so you can override methods without ruining
* the parent class.
*
* This will alter the actual destination class though, it does not
* create a new class.
*
* @param {Function} destination The target class for the inheritance.
* @param {Function} source Class to inherit from.
* @param {Boolean} addSuper Should we add the _super property to the prototype? Defaults to true.
*/
inherit: function inherit(destination, source, addSuper) {
var proto = destination.prototype = heir.createObject(source.prototype);
proto.constructor = destination;
if (addSuper || typeof addSuper === 'undefined') {
destination._super = source.prototype;
}
},
/**
* Creates a new object with the source object nestled within its
* prototype chain.
*
* @param {Object} source Method to insert into the new object's prototype.
* @return {Object} An empty object with the source object in it's prototype chain.
*/
createObject: Object.create || function createObject(source) {
var Host = function () {};
Host.prototype = source;
return new Host();
},
/**
* Mixes the specified object into your class. This can be used to add
* certain capabilities and helper methods to a class that is already
* inheriting from some other class. You can mix in as many object as
* you want, but only inherit from one.
*
* These values are mixed into the actual prototype object of your
* class, they are not added to the prototype chain like inherit.
*
* @param {Function} destination Class to mix the object into.
* @param {Object} source Object to mix into the class.
*/
mixin: function mixin(destination, source) {
return heir.merge(destination.prototype, source);
},
/**
* Merges one object into another, change the object in place.
*
* @param {Object} destination The destination for the merge.
* @param {Object} source The source of the properties to merge.
*/
merge: function merge(destination, source) {
var key;
for (key in source) {
if (heir.hasOwn(source, key)) {
destination[key] = source[key];
}
}
},
/**
* Shortcut for `Object.prototype.hasOwnProperty`.
*
* Uses `Object.prototype.hasOwnPropety` rather than
* `object.hasOwnProperty` as it could be overwritten.
*
* @param {Object} object The object to check
* @param {String} key The key to check for.
* @return {Boolean} Does object have key as an own propety?
*/
hasOwn: function hasOwn(object, key) {
return Object.prototype.hasOwnProperty.call(object, key);
}
};
return heir;
}));
|
/**
@module ember
@submodule ember-templates
*/
import Object from 'ember-runtime/system/object';
/**
Ember Helpers are functions that can compute values, and are used in templates.
For example, this code calls a helper named `format-currency`:
```handlebars
<div>{{format-currency cents currency="$"}}</div>
```
Additionally, a helper can be called as a nested helper (sometimes called a
subexpression). In this example, the computed value of a helper is passed
to a component named `show-money`:
```handlebars
{{show-money amount=(format-currency cents currency="$")}}
```
Helpers defined using a class must provide a `compute` function. For example:
```js
export default Ember.Helper.extend({
compute(params, hash) {
let cents = params[0];
let currency = hash.currency;
return `${currency}${cents * 0.01}`;
}
});
```
Each time the input to a helper changes, the `compute` function will be
called again.
As instances, these helpers also have access to the container and will accept
injected dependencies.
Additionally, class helpers can call `recompute` to force a new computation.
@class Ember.Helper
@public
@since 1.13.0
*/
var Helper = Object.extend({
isHelperInstance: true,
/**
On a class-based helper, it may be useful to force a recomputation of that
helpers value. This is akin to `rerender` on a component.
For example, this component will rerender when the `currentUser` on a
session service changes:
```js
// app/helpers/current-user-email.js
export default Ember.Helper.extend({
session: Ember.inject.service(),
onNewUser: Ember.observer('session.currentUser', function() {
this.recompute();
}),
compute() {
return this.get('session.currentUser.email');
}
});
```
@method recompute
@public
@since 1.13.0
*/
recompute() {
this._stream.notify();
}
/**
Override this function when writing a class-based helper.
@method compute
@param {Array} params The positional arguments to the helper
@param {Object} hash The named arguments to the helper
@public
@since 1.13.0
*/
});
Helper.reopenClass({
isHelperFactory: true
});
/**
In many cases, the ceremony of a full `Ember.Helper` class is not required.
The `helper` method create pure-function helpers without instances. For
example:
```js
// app/helpers/format-currency.js
export default Ember.Helper.helper(function(params, hash) {
let cents = params[0];
let currency = hash.currency;
return `${currency}${cents * 0.01}`;
});
```
@static
@param {Function} helper The helper function
@method helper
@public
@since 1.13.0
*/
export function helper(helperFn) {
return {
isHelperInstance: true,
compute: helperFn
};
}
export default Helper;
|
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { Observable } from 'rxjs/Observable';
import { fromPromise } from 'rxjs/observable/fromPromise';
import { of } from 'rxjs/observable/of';
import { concatAll } from 'rxjs/operator/concatAll';
import { every } from 'rxjs/operator/every';
import * as l from 'rxjs/operator/last';
import { map } from 'rxjs/operator/map';
import { mergeAll } from 'rxjs/operator/mergeAll';
import { PRIMARY_OUTLET } from '../shared';
/**
* @param {?} a
* @param {?} b
* @return {?}
*/
export function shallowEqualArrays(a, b) {
if (a.length !== b.length)
return false;
for (var /** @type {?} */ i = 0; i < a.length; ++i) {
if (!shallowEqual(a[i], b[i]))
return false;
}
return true;
}
/**
* @param {?} a
* @param {?} b
* @return {?}
*/
export function shallowEqual(a, b) {
var /** @type {?} */ k1 = Object.keys(a);
var /** @type {?} */ k2 = Object.keys(b);
if (k1.length != k2.length) {
return false;
}
var /** @type {?} */ key;
for (var /** @type {?} */ i = 0; i < k1.length; i++) {
key = k1[i];
if (a[key] !== b[key]) {
return false;
}
}
return true;
}
/**
* @param {?} a
* @return {?}
*/
export function flatten(a) {
var /** @type {?} */ target = [];
for (var /** @type {?} */ i = 0; i < a.length; ++i) {
for (var /** @type {?} */ j = 0; j < a[i].length; ++j) {
target.push(a[i][j]);
}
}
return target;
}
/**
* @param {?} a
* @return {?}
*/
export function first(a) {
return a.length > 0 ? a[0] : null;
}
/**
* @param {?} a
* @return {?}
*/
export function last(a) {
return a.length > 0 ? a[a.length - 1] : null;
}
/**
* @param {?} bools
* @return {?}
*/
export function and(bools) {
return bools.reduce(function (a, b) { return a && b; }, true);
}
/**
* @param {?} m1
* @param {?} m2
* @return {?}
*/
export function merge(m1, m2) {
var /** @type {?} */ m = {};
for (var attr in m1) {
if (m1.hasOwnProperty(attr)) {
m[attr] = m1[attr];
}
}
for (var attr in m2) {
if (m2.hasOwnProperty(attr)) {
m[attr] = m2[attr];
}
}
return m;
}
/**
* @param {?} map
* @param {?} callback
* @return {?}
*/
export function forEach(map, callback) {
for (var prop in map) {
if (map.hasOwnProperty(prop)) {
callback(map[prop], prop);
}
}
}
/**
* @param {?} obj
* @param {?} fn
* @return {?}
*/
export function waitForMap(obj, fn) {
var /** @type {?} */ waitFor = [];
var /** @type {?} */ res = {};
forEach(obj, function (a, k) {
if (k === PRIMARY_OUTLET) {
waitFor.push(map.call(fn(k, a), function (_) {
res[k] = _;
return _;
}));
}
});
forEach(obj, function (a, k) {
if (k !== PRIMARY_OUTLET) {
waitFor.push(map.call(fn(k, a), function (_) {
res[k] = _;
return _;
}));
}
});
if (waitFor.length > 0) {
var /** @type {?} */ concatted$ = concatAll.call(of.apply(void 0, waitFor));
var /** @type {?} */ last$ = l.last.call(concatted$);
return map.call(last$, function () { return res; });
}
else {
return of(res);
}
}
/**
* @param {?} observables
* @return {?}
*/
export function andObservables(observables) {
var /** @type {?} */ merged$ = mergeAll.call(observables);
return every.call(merged$, function (result) { return result === true; });
}
/**
* @param {?} value
* @return {?}
*/
export function wrapIntoObservable(value) {
if (value instanceof Observable) {
return value;
}
else if (value instanceof Promise) {
return fromPromise(value);
}
else {
return of(value);
}
}
//# sourceMappingURL=collection.js.map
|
(function(b){var g="(ଡିସେମ୍ବର",f="ସେପ୍ଟେମ୍ବର",e="ଏପ୍ରିଲ୍",d="ଫ୍ରେବୃୟାରୀ",c="ଜାନୁୟାରୀ",a=b.cultures,i=a.en,j=i.calendars.standard,h=a.or=b.extend(true,{},i,{name:"or",englishName:"Oriya",nativeName:"ଓଡ଼ିଆ",language:"or",numberFormat:{groupSizes:[3,2],percent:{groupSizes:[3,2]},currency:{pattern:["$ -n","$ n"],groupSizes:[3,2],symbol:"ଟ"}},calendars:{standard:b.extend(true,{},j,{"/":"-",days:{names:["ରବିବାର","ସୋମବାର","ମଙ୍ଗଳବାର","ବୁଧବାର","ଗୁରୁବାର","ଶୁକ୍ରବାର","ଶନିବାର"],namesAbbr:["ରବି.","ସୋମ.","ମଙ୍ଗଳ.","ବୁଧ.","ଗୁରୁ.","ଶୁକ୍ର.","ଶନି."],namesShort:["ର","ସୋ","ମ","ବୁ","ଗୁ","ଶୁ","ଶ"]},months:{names:[c,d,"ମାର୍ଚ୍ଚ",e,"ମେ","ଜୁନ୍","ଜୁଲାଇ","ଅଗଷ୍ଟ",f,"ଅକ୍ଟୋବର","ନଭେମ୍ବର",g,""],namesAbbr:[c,d,"ମାର୍ଚ୍ଚ",e,"ମେ","ଜୁନ୍","ଜୁଲାଇ","ଅଗଷ୍ଟ",f,"ଅକ୍ଟୋବର","ନଭେମ୍ବର",g,""]},eras:[{name:"ଖ୍ରୀଷ୍ଟାବ୍ଦ",start:null,offset:0}],patterns:{d:"dd-MM-yy",D:"dd MMMM yyyy",t:"HH:mm",T:"HH:mm:ss",f:"dd MMMM yyyy HH:mm",F:"dd MMMM yyyy HH:mm:ss",M:"dd MMMM"}})}},a.or);h.calendar=h.calendars.standard})(jQuery)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.