code stringlengths 2 1.05M |
|---|
var gulp = require('gulp');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var connect = require('gulp-connect');
var watch = require('gulp-watch');
var colors = require('colors');
gulp.task('build', function() {
gulp.src([
'./src/js/delegate-service.js',
'./src/js/pdf-viewer-delegate.js',
'./src/js/pdf-ctrl.js',
'./src/js/pdf-viewer-toolbar.js',
'./src/js/pdf-viewer.js'
])
.pipe(concat('angular-pdf-viewer.min.js'))
//.pipe(uglify())
.pipe(gulp.dest('./dist/'));
});
gulp.task('dev', function() {
// Start a server
connect.server({
root: '',
port: 3000,
livereload: true
});
console.log('[CONNECT] Listening on port 3000'.yellow.inverse);
// Watch HTML files for changes
console.log('[CONNECT] Watching HTML, JS and CSS files for live-reload'.blue);
watch({
glob: ['./src/**/*.*']
})
.pipe(connect.reload());
}); |
var EditableTable = function () {
return {
//main function to initiate the module
init: function () {
function restoreRow(oTable, nRow) {
var aData = oTable.fnGetData(nRow);
var jqTds = $('>td', nRow);
for (var i = 0, iLen = jqTds.length; i < iLen; i++) {
oTable.fnUpdate(aData[i], nRow, i, false);
}
oTable.fnDraw();
}
function editRow(oTable, nRow) {
var aData = oTable.fnGetData(nRow);
var jqTds = $('>td', nRow);
jqTds[0].innerHTML = '<input type="text" class="form-control small" value="' + aData[0] + '">';
jqTds[1].innerHTML = '<input type="text" class="form-control small" value="' + aData[1] + '">';
jqTds[2].innerHTML = '<a data-toggle="modal" href="#modalNego" class="btn btn-primary btn-sm" href="">upload rule</a>';
jqTds[3].innerHTML = '<input type="date" value="'+ aData[3] +'">';
jqTds[4].innerHTML = '<a class="edit" href="">Save</a>';
jqTds[5].innerHTML = '<a class="cancel" href="">Cancel</a>';
}
function saveRow(oTable, nRow) {
var jqInputs = $('input', nRow);
oTable.fnUpdate(jqInputs[0].value, nRow, 0, false);
oTable.fnUpdate(jqInputs[1].value, nRow, 1, false);
oTable.fnUpdate("<a title='Unduh rule' href='#'>rule nego</a>", nRow, 2, false);
oTable.fnUpdate(jqInputs[2].value, nRow, 3, false);
oTable.fnUpdate('<a class="edit" href=""><i class="fa fa-pencil"></i></a>', nRow, 4, false);
oTable.fnUpdate('<a class="delete" href=""><i class="fa fa-trash-o"></i></a>', nRow, 5, false);
oTable.fnDraw();
}
function cancelEditRow(oTable, nRow) {
var jqInputs = $('input', nRow);
oTable.fnUpdate(jqInputs[0].value, nRow, 0, false);
oTable.fnUpdate(jqInputs[1].value, nRow, 1, false);
oTable.fnUpdate(jqInputs[2].value, nRow, 2, false);
oTable.fnUpdate(jqInputs[3].value, nRow, 3, false);
oTable.fnUpdate('<a class="edit" href=""><i class="fa fa-pencil"></i></a>', nRow, 4, false);
oTable.fnDraw();
}
var oTable = $('#editable-sample').dataTable({
"aLengthMenu": [
[10, 50, 100, -1],
[10, 50, 100, "All"] // change per page values here
],
// set the initial value
"iDisplayLength": 10,
"sDom": "<'row'<'col-lg-6'l><'col-lg-6'f>r>t<'row'<'col-lg-6'i><'col-lg-6'p>>",
"sPaginationType": "bootstrap",
"oLanguage": {
"sLengthMenu": "_MENU_ records per page",
"oPaginate": {
"sPrevious": "Prev",
"sNext": "Next"
}
},
"aoColumnDefs": [{
'bSortable': false,
'aTargets': [-1,-2]
}
]
});
jQuery('#editable-sample_wrapper .dataTables_filter input').addClass("form-control medium"); // modify table search input
jQuery('#editable-sample_wrapper .dataTables_length select').addClass("form-control xsmall"); // modify table per page dropdown
var nEditing = null;
$('#editable-sample_new').click(function (e) {
e.preventDefault();
var aiNew = oTable.fnAddData(['', '', '', '',
'<a class="edit" href=""><i class="fa fa-pencil"></i></a>', '<a class="cancel" data-mode="new" href="">Cancel</a>'
]);
var nRow = oTable.fnGetNodes(aiNew[0]);
editRow(oTable, nRow);
nEditing = nRow;
});
$('#editable-sample a.delete').live('click', function (e) {
e.preventDefault();
if (confirm("Are you sure to delete this row ?") == false) {
return;
}
var nRow = $(this).parents('tr')[0];
oTable.fnDeleteRow(nRow);
alert("Deleted! Do not forget to do some ajax to sync with backend :)");
});
$('#editable-sample a.cancel').live('click', function (e) {
e.preventDefault();
if ($(this).attr("data-mode") == "new") {
var nRow = $(this).parents('tr')[0];
oTable.fnDeleteRow(nRow);
} else {
restoreRow(oTable, nEditing);
nEditing = null;
}
});
$('#editable-sample a.edit').live('click', function (e) {
e.preventDefault();
/* Get the row as a parent of the link that was clicked on */
var nRow = $(this).parents('tr')[0];
if (nEditing !== null && nEditing != nRow) {
/* Currently editing - but not this row - restore the old before continuing to edit mode */
restoreRow(oTable, nEditing);
editRow(oTable, nRow);
nEditing = nRow;
} else if (nEditing == nRow && this.innerHTML == "Save") {
/* Editing this row and want to save it */
saveRow(oTable, nEditing);
nEditing = null;
alert("Updated! Do not forget to do some ajax to sync with backend :)");
} else {
/* No edit in progress - let's start one */
editRow(oTable, nRow);
nEditing = nRow;
}
});
}
};
}(); |
App.SongsIndexRoute = Ember.Route.extend({
model: function() {
return this.get('store').findAll('song');
}
}); |
/**
*
* InlineInputField
*
*/
import React from 'react';
import PropTypes from 'prop-types';
import { MediTheme } from 'utils/theme';
import TextFieldWrapper from './Wrapper';
// input styles
const floatingColor = {
color: MediTheme.palette.accent1Color,
borderColor: MediTheme.palette.accent1Color,
};
class InlineInputField extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
initialValue: undefined,
value: undefined,
error: undefined,
};
this.handleOnKeydown = this.handleOnKeydown.bind(this);
this.handleOnChange = this.handleOnChange.bind(this);
this.handleOnBlur = this.handleOnBlur.bind(this);
this.handleOnFocus = this.handleOnFocus.bind(this);
}
componentWillMount() {
this.setState({ value: this.props.value, initialValue: this.props.value });
}
componentWillReceiveProps(nextProps) {
this.setState({ value: nextProps.value, initialValue: nextProps.value });
}
handleOnKeydown(event) {
if (event.key === 'Enter' && event.shiftKey === false) {
this.handleOnBlur();
}
}
handleOnChange(event, value) {
this.setState({
value,
error: this.props.validate(value),
});
}
handleOnBlur() {
const valid = !this.state.error;
if (valid) {
if (this.state.value !== this.state.initialValue) {
this.props.handleOnBlur({ value: this.state.value });
}
} else {
this.setState({
value: this.state.initialValue,
error: undefined,
});
}
}
handleOnFocus() {
if (this.props.reinitialize) {
this.setState({
initialValue: this.state.value,
});
}
}
render() {
if (this.props.align) {
floatingColor.textAlign = this.props.align;
} else {
delete floatingColor.textAlign;
}
return (
<TextFieldWrapper
name={this.props.name}
value={this.state.value}
fullWidth
floatingLabelStyle={floatingColor}
floatingLabelFixed
underlineFocusStyle={floatingColor}
floatingLabelText={this.props.label}
autoComplete="off"
autoCorrect="off"
autoCapitalize="off"
spellCheck="false"
onBlur={this.handleOnBlur}
onChange={this.handleOnChange}
onFocus={this.handleOnFocus}
errorText={this.state.error && <span />}
onKeyDown={this.handleOnKeydown}
inputStyle={{ textAlign: this.props.align }}
/>
);
}
}
InlineInputField.propTypes = {
// properties
name: PropTypes.string.isRequired,
label: PropTypes.string.isRequired,
value: PropTypes.string.isRequired,
validate: PropTypes.func,
reinitialize: PropTypes.bool.isRequired,
align: PropTypes.string,
// actions
handleOnBlur: PropTypes.func.isRequired,
};
InlineInputField.defaultProps = {
value: '',
reinitialize: true,
};
export default InlineInputField;
|
import React from 'react'
import { connect } from 'react-redux'
import Typography from 'material-ui/Typography'
import returnWinnerStyle from './returnWinnerStyle'
import returnDissentingAdjudicatorStyle from './returnDissentingAdjudicatorStyle'
export default connect(mapStateToProps)(({
breakRoom,
breakBallotsThisRoom,
adjudicatorsById,
venuesById,
teamsById,
breakTeamsById,
institutionsById,
breakAdjudicatorsById
}) => {
const adjudicatorLabel = (adjudicatorId) =>
`${adjudicatorsById[breakAdjudicatorsById[adjudicatorId].adjudicator].firstName} ${adjudicatorsById[breakAdjudicatorsById[adjudicatorId].adjudicator].lastName} (${institutionsById[adjudicatorsById[breakAdjudicatorsById[adjudicatorId].adjudicator].institution].name})`
return (
<div
className={'flex flex-row w-100'}
>
<Typography
className={'w-10'}
>
{`Rank ${breakRoom.rank}`}
</Typography>
<Typography
className={'w-20'}
>
{venuesById[breakRoom.venue].name}
</Typography>
<Typography
className={'w-30'}
>
<span
className={returnWinnerStyle(
breakBallotsThisRoom,
breakRoom,
breakRoom.gov
)}
>
{teamsById[breakTeamsById[breakRoom.gov].team].name}
</span>
<br />
<span
className={returnWinnerStyle(
breakBallotsThisRoom,
breakRoom,
breakRoom.opp
)}
>
{teamsById[breakTeamsById[breakRoom.opp].team].name}
</span>
</Typography>
<Typography
className={'w-20'}
>
<span
className={returnDissentingAdjudicatorStyle(
breakBallotsThisRoom,
breakRoom,
breakRoom.chair
)}
>
{adjudicatorLabel(breakRoom.chair)}
</span>
</Typography>
<Typography
className={'w-20'}
>
{breakRoom.panels.map(panel =>
<span
key={panel}
className={returnDissentingAdjudicatorStyle(
breakBallotsThisRoom,
breakRoom,
panel
)}
>
{adjudicatorLabel(panel)}
<br />
</span>
)}
</Typography>
</div>
)
})
function mapStateToProps (state, ownProps) {
return {
adjudicatorsById: state.adjudicators.data,
teamsById: state.teams.data,
breakTeamsById: state.breakTeams.data,
breakAdjudicatorsById: state.breakAdjudicators.data,
venuesById: state.venues.data,
institutionsById: state.institutions.data
}
}
|
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react'), require('react-dom')) :
typeof define === 'function' && define.amd ? define(['exports', 'react', 'react-dom'], factory) :
(global = global || self, factory(global.ReactBootstrapTypeahead = {}, global.React, global.ReactDOM));
}(this, (function (exports, React, ReactDOM) { 'use strict';
var React__default = 'default' in React ? React['default'] : React;
ReactDOM = ReactDOM && Object.prototype.hasOwnProperty.call(ReactDOM, 'default') ? ReactDOM['default'] : ReactDOM;
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _extends() {
_extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
return _extends.apply(this, arguments);
}
function _inheritsLoose(subClass, superClass) {
subClass.prototype = Object.create(superClass.prototype);
subClass.prototype.constructor = subClass;
subClass.__proto__ = superClass;
}
function _objectWithoutPropertiesLoose(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i;
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
function unwrapExports (x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
}
function createCommonjsModule(fn, module) {
return module = { exports: {} }, fn(module, module.exports), module.exports;
}
/**
* lodash (Custom Build) <https://lodash.com/>
* Build: `lodash modularize exports="npm" -o ./`
* Copyright jQuery Foundation and other contributors <https://jquery.org/>
* Released under MIT license <https://lodash.com/license>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
*/
/** Used as the `TypeError` message for "Functions" methods. */
var FUNC_ERROR_TEXT = 'Expected a function';
/** Used as references for various `Number` constants. */
var NAN = 0 / 0;
/** `Object#toString` result references. */
var symbolTag = '[object Symbol]';
/** Used to match leading and trailing whitespace. */
var reTrim = /^\s+|\s+$/g;
/** Used to detect bad signed hexadecimal string values. */
var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
/** Used to detect binary string values. */
var reIsBinary = /^0b[01]+$/i;
/** Used to detect octal string values. */
var reIsOctal = /^0o[0-7]+$/i;
/** Built-in method references without a dependency on `root`. */
var freeParseInt = parseInt;
/** Detect free variable `global` from Node.js. */
var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
/** Detect free variable `self`. */
var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
/** Used as a reference to the global object. */
var root = freeGlobal || freeSelf || Function('return this')();
/** Used for built-in method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var objectToString = objectProto.toString;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max,
nativeMin = Math.min;
/**
* Gets the timestamp of the number of milliseconds that have elapsed since
* the Unix epoch (1 January 1970 00:00:00 UTC).
*
* @static
* @memberOf _
* @since 2.4.0
* @category Date
* @returns {number} Returns the timestamp.
* @example
*
* _.defer(function(stamp) {
* console.log(_.now() - stamp);
* }, _.now());
* // => Logs the number of milliseconds it took for the deferred invocation.
*/
var now = function() {
return root.Date.now();
};
/**
* Creates a debounced function that delays invoking `func` until after `wait`
* milliseconds have elapsed since the last time the debounced function was
* invoked. The debounced function comes with a `cancel` method to cancel
* delayed `func` invocations and a `flush` method to immediately invoke them.
* Provide `options` to indicate whether `func` should be invoked on the
* leading and/or trailing edge of the `wait` timeout. The `func` is invoked
* with the last arguments provided to the debounced function. Subsequent
* calls to the debounced function return the result of the last `func`
* invocation.
*
* **Note:** If `leading` and `trailing` options are `true`, `func` is
* invoked on the trailing edge of the timeout only if the debounced function
* is invoked more than once during the `wait` timeout.
*
* If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
* until to the next tick, similar to `setTimeout` with a timeout of `0`.
*
* See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
* for details over the differences between `_.debounce` and `_.throttle`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to debounce.
* @param {number} [wait=0] The number of milliseconds to delay.
* @param {Object} [options={}] The options object.
* @param {boolean} [options.leading=false]
* Specify invoking on the leading edge of the timeout.
* @param {number} [options.maxWait]
* The maximum time `func` is allowed to be delayed before it's invoked.
* @param {boolean} [options.trailing=true]
* Specify invoking on the trailing edge of the timeout.
* @returns {Function} Returns the new debounced function.
* @example
*
* // Avoid costly calculations while the window size is in flux.
* jQuery(window).on('resize', _.debounce(calculateLayout, 150));
*
* // Invoke `sendMail` when clicked, debouncing subsequent calls.
* jQuery(element).on('click', _.debounce(sendMail, 300, {
* 'leading': true,
* 'trailing': false
* }));
*
* // Ensure `batchLog` is invoked once after 1 second of debounced calls.
* var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });
* var source = new EventSource('/stream');
* jQuery(source).on('message', debounced);
*
* // Cancel the trailing debounced invocation.
* jQuery(window).on('popstate', debounced.cancel);
*/
function debounce(func, wait, options) {
var lastArgs,
lastThis,
maxWait,
result,
timerId,
lastCallTime,
lastInvokeTime = 0,
leading = false,
maxing = false,
trailing = true;
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
wait = toNumber(wait) || 0;
if (isObject(options)) {
leading = !!options.leading;
maxing = 'maxWait' in options;
maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;
trailing = 'trailing' in options ? !!options.trailing : trailing;
}
function invokeFunc(time) {
var args = lastArgs,
thisArg = lastThis;
lastArgs = lastThis = undefined;
lastInvokeTime = time;
result = func.apply(thisArg, args);
return result;
}
function leadingEdge(time) {
// Reset any `maxWait` timer.
lastInvokeTime = time;
// Start the timer for the trailing edge.
timerId = setTimeout(timerExpired, wait);
// Invoke the leading edge.
return leading ? invokeFunc(time) : result;
}
function remainingWait(time) {
var timeSinceLastCall = time - lastCallTime,
timeSinceLastInvoke = time - lastInvokeTime,
result = wait - timeSinceLastCall;
return maxing ? nativeMin(result, maxWait - timeSinceLastInvoke) : result;
}
function shouldInvoke(time) {
var timeSinceLastCall = time - lastCallTime,
timeSinceLastInvoke = time - lastInvokeTime;
// Either this is the first call, activity has stopped and we're at the
// trailing edge, the system time has gone backwards and we're treating
// it as the trailing edge, or we've hit the `maxWait` limit.
return (lastCallTime === undefined || (timeSinceLastCall >= wait) ||
(timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait));
}
function timerExpired() {
var time = now();
if (shouldInvoke(time)) {
return trailingEdge(time);
}
// Restart the timer.
timerId = setTimeout(timerExpired, remainingWait(time));
}
function trailingEdge(time) {
timerId = undefined;
// Only invoke if we have `lastArgs` which means `func` has been
// debounced at least once.
if (trailing && lastArgs) {
return invokeFunc(time);
}
lastArgs = lastThis = undefined;
return result;
}
function cancel() {
if (timerId !== undefined) {
clearTimeout(timerId);
}
lastInvokeTime = 0;
lastArgs = lastCallTime = lastThis = timerId = undefined;
}
function flush() {
return timerId === undefined ? result : trailingEdge(now());
}
function debounced() {
var time = now(),
isInvoking = shouldInvoke(time);
lastArgs = arguments;
lastThis = this;
lastCallTime = time;
if (isInvoking) {
if (timerId === undefined) {
return leadingEdge(lastCallTime);
}
if (maxing) {
// Handle invocations in a tight loop.
timerId = setTimeout(timerExpired, wait);
return invokeFunc(lastCallTime);
}
}
if (timerId === undefined) {
timerId = setTimeout(timerExpired, wait);
}
return result;
}
debounced.cancel = cancel;
debounced.flush = flush;
return debounced;
}
/**
* Checks if `value` is the
* [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
* of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(_.noop);
* // => true
*
* _.isObject(null);
* // => false
*/
function isObject(value) {
var type = typeof value;
return !!value && (type == 'object' || type == 'function');
}
/**
* Checks if `value` is object-like. A value is object-like if it's not `null`
* and has a `typeof` result of "object".
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
* @example
*
* _.isObjectLike({});
* // => true
*
* _.isObjectLike([1, 2, 3]);
* // => true
*
* _.isObjectLike(_.noop);
* // => false
*
* _.isObjectLike(null);
* // => false
*/
function isObjectLike(value) {
return !!value && typeof value == 'object';
}
/**
* Checks if `value` is classified as a `Symbol` primitive or object.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
* @example
*
* _.isSymbol(Symbol.iterator);
* // => true
*
* _.isSymbol('abc');
* // => false
*/
function isSymbol(value) {
return typeof value == 'symbol' ||
(isObjectLike(value) && objectToString.call(value) == symbolTag);
}
/**
* Converts `value` to a number.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to process.
* @returns {number} Returns the number.
* @example
*
* _.toNumber(3.2);
* // => 3.2
*
* _.toNumber(Number.MIN_VALUE);
* // => 5e-324
*
* _.toNumber(Infinity);
* // => Infinity
*
* _.toNumber('3.2');
* // => 3.2
*/
function toNumber(value) {
if (typeof value == 'number') {
return value;
}
if (isSymbol(value)) {
return NAN;
}
if (isObject(value)) {
var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
value = isObject(other) ? (other + '') : other;
}
if (typeof value != 'string') {
return value === 0 ? value : +value;
}
value = value.replace(reTrim, '');
var isBinary = reIsBinary.test(value);
return (isBinary || reIsOctal.test(value))
? freeParseInt(value.slice(2), isBinary ? 2 : 8)
: (reIsBadHex.test(value) ? NAN : +value);
}
var lodash_debounce = debounce;
var reactIs_development = createCommonjsModule(function (module, exports) {
{
(function() {
// The Symbol used to tag the ReactElement-like types. If there is no native Symbol
// nor polyfill, then a plain number is used for performance.
var hasSymbol = typeof Symbol === 'function' && Symbol.for;
var REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for('react.element') : 0xeac7;
var REACT_PORTAL_TYPE = hasSymbol ? Symbol.for('react.portal') : 0xeaca;
var REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for('react.fragment') : 0xeacb;
var REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for('react.strict_mode') : 0xeacc;
var REACT_PROFILER_TYPE = hasSymbol ? Symbol.for('react.profiler') : 0xead2;
var REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for('react.provider') : 0xeacd;
var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for('react.context') : 0xeace; // TODO: We don't use AsyncMode or ConcurrentMode anymore. They were temporary
// (unstable) APIs that have been removed. Can we remove the symbols?
var REACT_ASYNC_MODE_TYPE = hasSymbol ? Symbol.for('react.async_mode') : 0xeacf;
var REACT_CONCURRENT_MODE_TYPE = hasSymbol ? Symbol.for('react.concurrent_mode') : 0xeacf;
var REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for('react.forward_ref') : 0xead0;
var REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for('react.suspense') : 0xead1;
var REACT_SUSPENSE_LIST_TYPE = hasSymbol ? Symbol.for('react.suspense_list') : 0xead8;
var REACT_MEMO_TYPE = hasSymbol ? Symbol.for('react.memo') : 0xead3;
var REACT_LAZY_TYPE = hasSymbol ? Symbol.for('react.lazy') : 0xead4;
var REACT_BLOCK_TYPE = hasSymbol ? Symbol.for('react.block') : 0xead9;
var REACT_FUNDAMENTAL_TYPE = hasSymbol ? Symbol.for('react.fundamental') : 0xead5;
var REACT_RESPONDER_TYPE = hasSymbol ? Symbol.for('react.responder') : 0xead6;
var REACT_SCOPE_TYPE = hasSymbol ? Symbol.for('react.scope') : 0xead7;
function isValidElementType(type) {
return typeof type === 'string' || typeof type === 'function' || // Note: its typeof might be other than 'symbol' or 'number' if it's a polyfill.
type === REACT_FRAGMENT_TYPE || type === REACT_CONCURRENT_MODE_TYPE || type === REACT_PROFILER_TYPE || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || typeof type === 'object' && type !== null && (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || type.$$typeof === REACT_FUNDAMENTAL_TYPE || type.$$typeof === REACT_RESPONDER_TYPE || type.$$typeof === REACT_SCOPE_TYPE || type.$$typeof === REACT_BLOCK_TYPE);
}
function typeOf(object) {
if (typeof object === 'object' && object !== null) {
var $$typeof = object.$$typeof;
switch ($$typeof) {
case REACT_ELEMENT_TYPE:
var type = object.type;
switch (type) {
case REACT_ASYNC_MODE_TYPE:
case REACT_CONCURRENT_MODE_TYPE:
case REACT_FRAGMENT_TYPE:
case REACT_PROFILER_TYPE:
case REACT_STRICT_MODE_TYPE:
case REACT_SUSPENSE_TYPE:
return type;
default:
var $$typeofType = type && type.$$typeof;
switch ($$typeofType) {
case REACT_CONTEXT_TYPE:
case REACT_FORWARD_REF_TYPE:
case REACT_LAZY_TYPE:
case REACT_MEMO_TYPE:
case REACT_PROVIDER_TYPE:
return $$typeofType;
default:
return $$typeof;
}
}
case REACT_PORTAL_TYPE:
return $$typeof;
}
}
return undefined;
} // AsyncMode is deprecated along with isAsyncMode
var AsyncMode = REACT_ASYNC_MODE_TYPE;
var ConcurrentMode = REACT_CONCURRENT_MODE_TYPE;
var ContextConsumer = REACT_CONTEXT_TYPE;
var ContextProvider = REACT_PROVIDER_TYPE;
var Element = REACT_ELEMENT_TYPE;
var ForwardRef = REACT_FORWARD_REF_TYPE;
var Fragment = REACT_FRAGMENT_TYPE;
var Lazy = REACT_LAZY_TYPE;
var Memo = REACT_MEMO_TYPE;
var Portal = REACT_PORTAL_TYPE;
var Profiler = REACT_PROFILER_TYPE;
var StrictMode = REACT_STRICT_MODE_TYPE;
var Suspense = REACT_SUSPENSE_TYPE;
var hasWarnedAboutDeprecatedIsAsyncMode = false; // AsyncMode should be deprecated
function isAsyncMode(object) {
{
if (!hasWarnedAboutDeprecatedIsAsyncMode) {
hasWarnedAboutDeprecatedIsAsyncMode = true; // Using console['warn'] to evade Babel and ESLint
console['warn']('The ReactIs.isAsyncMode() alias has been deprecated, ' + 'and will be removed in React 17+. Update your code to use ' + 'ReactIs.isConcurrentMode() instead. It has the exact same API.');
}
}
return isConcurrentMode(object) || typeOf(object) === REACT_ASYNC_MODE_TYPE;
}
function isConcurrentMode(object) {
return typeOf(object) === REACT_CONCURRENT_MODE_TYPE;
}
function isContextConsumer(object) {
return typeOf(object) === REACT_CONTEXT_TYPE;
}
function isContextProvider(object) {
return typeOf(object) === REACT_PROVIDER_TYPE;
}
function isElement(object) {
return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
}
function isForwardRef(object) {
return typeOf(object) === REACT_FORWARD_REF_TYPE;
}
function isFragment(object) {
return typeOf(object) === REACT_FRAGMENT_TYPE;
}
function isLazy(object) {
return typeOf(object) === REACT_LAZY_TYPE;
}
function isMemo(object) {
return typeOf(object) === REACT_MEMO_TYPE;
}
function isPortal(object) {
return typeOf(object) === REACT_PORTAL_TYPE;
}
function isProfiler(object) {
return typeOf(object) === REACT_PROFILER_TYPE;
}
function isStrictMode(object) {
return typeOf(object) === REACT_STRICT_MODE_TYPE;
}
function isSuspense(object) {
return typeOf(object) === REACT_SUSPENSE_TYPE;
}
exports.AsyncMode = AsyncMode;
exports.ConcurrentMode = ConcurrentMode;
exports.ContextConsumer = ContextConsumer;
exports.ContextProvider = ContextProvider;
exports.Element = Element;
exports.ForwardRef = ForwardRef;
exports.Fragment = Fragment;
exports.Lazy = Lazy;
exports.Memo = Memo;
exports.Portal = Portal;
exports.Profiler = Profiler;
exports.StrictMode = StrictMode;
exports.Suspense = Suspense;
exports.isAsyncMode = isAsyncMode;
exports.isConcurrentMode = isConcurrentMode;
exports.isContextConsumer = isContextConsumer;
exports.isContextProvider = isContextProvider;
exports.isElement = isElement;
exports.isForwardRef = isForwardRef;
exports.isFragment = isFragment;
exports.isLazy = isLazy;
exports.isMemo = isMemo;
exports.isPortal = isPortal;
exports.isProfiler = isProfiler;
exports.isStrictMode = isStrictMode;
exports.isSuspense = isSuspense;
exports.isValidElementType = isValidElementType;
exports.typeOf = typeOf;
})();
}
});
var reactIs_development_1 = reactIs_development.AsyncMode;
var reactIs_development_2 = reactIs_development.ConcurrentMode;
var reactIs_development_3 = reactIs_development.ContextConsumer;
var reactIs_development_4 = reactIs_development.ContextProvider;
var reactIs_development_5 = reactIs_development.Element;
var reactIs_development_6 = reactIs_development.ForwardRef;
var reactIs_development_7 = reactIs_development.Fragment;
var reactIs_development_8 = reactIs_development.Lazy;
var reactIs_development_9 = reactIs_development.Memo;
var reactIs_development_10 = reactIs_development.Portal;
var reactIs_development_11 = reactIs_development.Profiler;
var reactIs_development_12 = reactIs_development.StrictMode;
var reactIs_development_13 = reactIs_development.Suspense;
var reactIs_development_14 = reactIs_development.isAsyncMode;
var reactIs_development_15 = reactIs_development.isConcurrentMode;
var reactIs_development_16 = reactIs_development.isContextConsumer;
var reactIs_development_17 = reactIs_development.isContextProvider;
var reactIs_development_18 = reactIs_development.isElement;
var reactIs_development_19 = reactIs_development.isForwardRef;
var reactIs_development_20 = reactIs_development.isFragment;
var reactIs_development_21 = reactIs_development.isLazy;
var reactIs_development_22 = reactIs_development.isMemo;
var reactIs_development_23 = reactIs_development.isPortal;
var reactIs_development_24 = reactIs_development.isProfiler;
var reactIs_development_25 = reactIs_development.isStrictMode;
var reactIs_development_26 = reactIs_development.isSuspense;
var reactIs_development_27 = reactIs_development.isValidElementType;
var reactIs_development_28 = reactIs_development.typeOf;
var reactIs = createCommonjsModule(function (module) {
{
module.exports = reactIs_development;
}
});
/*
object-assign
(c) Sindre Sorhus
@license MIT
*/
/* eslint-disable no-unused-vars */
var getOwnPropertySymbols = Object.getOwnPropertySymbols;
var hasOwnProperty = Object.prototype.hasOwnProperty;
var propIsEnumerable = Object.prototype.propertyIsEnumerable;
function toObject(val) {
if (val === null || val === undefined) {
throw new TypeError('Object.assign cannot be called with null or undefined');
}
return Object(val);
}
function shouldUseNative() {
try {
if (!Object.assign) {
return false;
}
// Detect buggy property enumeration order in older V8 versions.
// https://bugs.chromium.org/p/v8/issues/detail?id=4118
var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
test1[5] = 'de';
if (Object.getOwnPropertyNames(test1)[0] === '5') {
return false;
}
// https://bugs.chromium.org/p/v8/issues/detail?id=3056
var test2 = {};
for (var i = 0; i < 10; i++) {
test2['_' + String.fromCharCode(i)] = i;
}
var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
return test2[n];
});
if (order2.join('') !== '0123456789') {
return false;
}
// https://bugs.chromium.org/p/v8/issues/detail?id=3056
var test3 = {};
'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
test3[letter] = letter;
});
if (Object.keys(Object.assign({}, test3)).join('') !==
'abcdefghijklmnopqrst') {
return false;
}
return true;
} catch (err) {
// We don't expect any of the above to throw, but better to be safe.
return false;
}
}
var objectAssign = shouldUseNative() ? Object.assign : function (target, source) {
var from;
var to = toObject(target);
var symbols;
for (var s = 1; s < arguments.length; s++) {
from = Object(arguments[s]);
for (var key in from) {
if (hasOwnProperty.call(from, key)) {
to[key] = from[key];
}
}
if (getOwnPropertySymbols) {
symbols = getOwnPropertySymbols(from);
for (var i = 0; i < symbols.length; i++) {
if (propIsEnumerable.call(from, symbols[i])) {
to[symbols[i]] = from[symbols[i]];
}
}
}
}
return to;
};
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';
var ReactPropTypesSecret_1 = ReactPropTypesSecret;
var printWarning = function() {};
{
var ReactPropTypesSecret$1 = ReactPropTypesSecret_1;
var loggedTypeFailures = {};
var has = Function.call.bind(Object.prototype.hasOwnProperty);
printWarning = function(text) {
var message = 'Warning: ' + text;
if (typeof console !== 'undefined') {
console.error(message);
}
try {
// --- Welcome to debugging React ---
// This error was thrown as a convenience so that you can use this stack
// to find the callsite that caused this warning to fire.
throw new Error(message);
} catch (x) {}
};
}
/**
* Assert that the values match with the type specs.
* Error messages are memorized and will only be shown once.
*
* @param {object} typeSpecs Map of name to a ReactPropType
* @param {object} values Runtime values that need to be type-checked
* @param {string} location e.g. "prop", "context", "child context"
* @param {string} componentName Name of the component for error messages.
* @param {?Function} getStack Returns the component stack.
* @private
*/
function checkPropTypes(typeSpecs, values, location, componentName, getStack) {
{
for (var typeSpecName in typeSpecs) {
if (has(typeSpecs, typeSpecName)) {
var error;
// Prop type validation may throw. In case they do, we don't want to
// fail the render phase where it didn't fail before. So we log it.
// After these have been cleaned up, we'll let them throw.
try {
// This is intentionally an invariant that gets caught. It's the same
// behavior as without this statement except with a better message.
if (typeof typeSpecs[typeSpecName] !== 'function') {
var err = Error(
(componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' +
'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.'
);
err.name = 'Invariant Violation';
throw err;
}
error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret$1);
} catch (ex) {
error = ex;
}
if (error && !(error instanceof Error)) {
printWarning(
(componentName || 'React class') + ': type specification of ' +
location + ' `' + typeSpecName + '` is invalid; the type checker ' +
'function must return `null` or an `Error` but returned a ' + typeof error + '. ' +
'You may have forgotten to pass an argument to the type checker ' +
'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' +
'shape all require an argument).'
);
}
if (error instanceof Error && !(error.message in loggedTypeFailures)) {
// Only monitor this failure once because there tends to be a lot of the
// same error.
loggedTypeFailures[error.message] = true;
var stack = getStack ? getStack() : '';
printWarning(
'Failed ' + location + ' type: ' + error.message + (stack != null ? stack : '')
);
}
}
}
}
}
/**
* Resets warning cache when testing.
*
* @private
*/
checkPropTypes.resetWarningCache = function() {
{
loggedTypeFailures = {};
}
};
var checkPropTypes_1 = checkPropTypes;
var has$1 = Function.call.bind(Object.prototype.hasOwnProperty);
var printWarning$1 = function() {};
{
printWarning$1 = function(text) {
var message = 'Warning: ' + text;
if (typeof console !== 'undefined') {
console.error(message);
}
try {
// --- Welcome to debugging React ---
// This error was thrown as a convenience so that you can use this stack
// to find the callsite that caused this warning to fire.
throw new Error(message);
} catch (x) {}
};
}
function emptyFunctionThatReturnsNull() {
return null;
}
var factoryWithTypeCheckers = function(isValidElement, throwOnDirectAccess) {
/* global Symbol */
var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec.
/**
* Returns the iterator method function contained on the iterable object.
*
* Be sure to invoke the function with the iterable as context:
*
* var iteratorFn = getIteratorFn(myIterable);
* if (iteratorFn) {
* var iterator = iteratorFn.call(myIterable);
* ...
* }
*
* @param {?object} maybeIterable
* @return {?function}
*/
function getIteratorFn(maybeIterable) {
var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]);
if (typeof iteratorFn === 'function') {
return iteratorFn;
}
}
/**
* Collection of methods that allow declaration and validation of props that are
* supplied to React components. Example usage:
*
* var Props = require('ReactPropTypes');
* var MyArticle = React.createClass({
* propTypes: {
* // An optional string prop named "description".
* description: Props.string,
*
* // A required enum prop named "category".
* category: Props.oneOf(['News','Photos']).isRequired,
*
* // A prop named "dialog" that requires an instance of Dialog.
* dialog: Props.instanceOf(Dialog).isRequired
* },
* render: function() { ... }
* });
*
* A more formal specification of how these methods are used:
*
* type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...)
* decl := ReactPropTypes.{type}(.isRequired)?
*
* Each and every declaration produces a function with the same signature. This
* allows the creation of custom validation functions. For example:
*
* var MyLink = React.createClass({
* propTypes: {
* // An optional string or URI prop named "href".
* href: function(props, propName, componentName) {
* var propValue = props[propName];
* if (propValue != null && typeof propValue !== 'string' &&
* !(propValue instanceof URI)) {
* return new Error(
* 'Expected a string or an URI for ' + propName + ' in ' +
* componentName
* );
* }
* }
* },
* render: function() {...}
* });
*
* @internal
*/
var ANONYMOUS = '<<anonymous>>';
// Important!
// Keep this list in sync with production version in `./factoryWithThrowingShims.js`.
var ReactPropTypes = {
array: createPrimitiveTypeChecker('array'),
bool: createPrimitiveTypeChecker('boolean'),
func: createPrimitiveTypeChecker('function'),
number: createPrimitiveTypeChecker('number'),
object: createPrimitiveTypeChecker('object'),
string: createPrimitiveTypeChecker('string'),
symbol: createPrimitiveTypeChecker('symbol'),
any: createAnyTypeChecker(),
arrayOf: createArrayOfTypeChecker,
element: createElementTypeChecker(),
elementType: createElementTypeTypeChecker(),
instanceOf: createInstanceTypeChecker,
node: createNodeChecker(),
objectOf: createObjectOfTypeChecker,
oneOf: createEnumTypeChecker,
oneOfType: createUnionTypeChecker,
shape: createShapeTypeChecker,
exact: createStrictShapeTypeChecker,
};
/**
* inlined Object.is polyfill to avoid requiring consumers ship their own
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
*/
/*eslint-disable no-self-compare*/
function is(x, y) {
// SameValue algorithm
if (x === y) {
// Steps 1-5, 7-10
// Steps 6.b-6.e: +0 != -0
return x !== 0 || 1 / x === 1 / y;
} else {
// Step 6.a: NaN == NaN
return x !== x && y !== y;
}
}
/*eslint-enable no-self-compare*/
/**
* We use an Error-like object for backward compatibility as people may call
* PropTypes directly and inspect their output. However, we don't use real
* Errors anymore. We don't inspect their stack anyway, and creating them
* is prohibitively expensive if they are created too often, such as what
* happens in oneOfType() for any type before the one that matched.
*/
function PropTypeError(message) {
this.message = message;
this.stack = '';
}
// Make `instanceof Error` still work for returned errors.
PropTypeError.prototype = Error.prototype;
function createChainableTypeChecker(validate) {
{
var manualPropTypeCallCache = {};
var manualPropTypeWarningCount = 0;
}
function checkType(isRequired, props, propName, componentName, location, propFullName, secret) {
componentName = componentName || ANONYMOUS;
propFullName = propFullName || propName;
if (secret !== ReactPropTypesSecret_1) {
if (throwOnDirectAccess) {
// New behavior only for users of `prop-types` package
var err = new Error(
'Calling PropTypes validators directly is not supported by the `prop-types` package. ' +
'Use `PropTypes.checkPropTypes()` to call them. ' +
'Read more at http://fb.me/use-check-prop-types'
);
err.name = 'Invariant Violation';
throw err;
} else if ( typeof console !== 'undefined') {
// Old behavior for people using React.PropTypes
var cacheKey = componentName + ':' + propName;
if (
!manualPropTypeCallCache[cacheKey] &&
// Avoid spamming the console because they are often not actionable except for lib authors
manualPropTypeWarningCount < 3
) {
printWarning$1(
'You are manually calling a React.PropTypes validation ' +
'function for the `' + propFullName + '` prop on `' + componentName + '`. This is deprecated ' +
'and will throw in the standalone `prop-types` package. ' +
'You may be seeing this warning due to a third-party PropTypes ' +
'library. See https://fb.me/react-warning-dont-call-proptypes ' + 'for details.'
);
manualPropTypeCallCache[cacheKey] = true;
manualPropTypeWarningCount++;
}
}
}
if (props[propName] == null) {
if (isRequired) {
if (props[propName] === null) {
return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required ' + ('in `' + componentName + '`, but its value is `null`.'));
}
return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required in ' + ('`' + componentName + '`, but its value is `undefined`.'));
}
return null;
} else {
return validate(props, propName, componentName, location, propFullName);
}
}
var chainedCheckType = checkType.bind(null, false);
chainedCheckType.isRequired = checkType.bind(null, true);
return chainedCheckType;
}
function createPrimitiveTypeChecker(expectedType) {
function validate(props, propName, componentName, location, propFullName, secret) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== expectedType) {
// `propValue` being instance of, say, date/regexp, pass the 'object'
// check, but we can offer a more precise error message here rather than
// 'of type `object`'.
var preciseType = getPreciseType(propValue);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createAnyTypeChecker() {
return createChainableTypeChecker(emptyFunctionThatReturnsNull);
}
function createArrayOfTypeChecker(typeChecker) {
function validate(props, propName, componentName, location, propFullName) {
if (typeof typeChecker !== 'function') {
return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside arrayOf.');
}
var propValue = props[propName];
if (!Array.isArray(propValue)) {
var propType = getPropType(propValue);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an array.'));
}
for (var i = 0; i < propValue.length; i++) {
var error = typeChecker(propValue, i, componentName, location, propFullName + '[' + i + ']', ReactPropTypesSecret_1);
if (error instanceof Error) {
return error;
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function createElementTypeChecker() {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
if (!isValidElement(propValue)) {
var propType = getPropType(propValue);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createElementTypeTypeChecker() {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
if (!reactIs.isValidElementType(propValue)) {
var propType = getPropType(propValue);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement type.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createInstanceTypeChecker(expectedClass) {
function validate(props, propName, componentName, location, propFullName) {
if (!(props[propName] instanceof expectedClass)) {
var expectedClassName = expectedClass.name || ANONYMOUS;
var actualClassName = getClassName(props[propName]);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + actualClassName + '` supplied to `' + componentName + '`, expected ') + ('instance of `' + expectedClassName + '`.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createEnumTypeChecker(expectedValues) {
if (!Array.isArray(expectedValues)) {
{
if (arguments.length > 1) {
printWarning$1(
'Invalid arguments supplied to oneOf, expected an array, got ' + arguments.length + ' arguments. ' +
'A common mistake is to write oneOf(x, y, z) instead of oneOf([x, y, z]).'
);
} else {
printWarning$1('Invalid argument supplied to oneOf, expected an array.');
}
}
return emptyFunctionThatReturnsNull;
}
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
for (var i = 0; i < expectedValues.length; i++) {
if (is(propValue, expectedValues[i])) {
return null;
}
}
var valuesString = JSON.stringify(expectedValues, function replacer(key, value) {
var type = getPreciseType(value);
if (type === 'symbol') {
return String(value);
}
return value;
});
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of value `' + String(propValue) + '` ' + ('supplied to `' + componentName + '`, expected one of ' + valuesString + '.'));
}
return createChainableTypeChecker(validate);
}
function createObjectOfTypeChecker(typeChecker) {
function validate(props, propName, componentName, location, propFullName) {
if (typeof typeChecker !== 'function') {
return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside objectOf.');
}
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== 'object') {
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an object.'));
}
for (var key in propValue) {
if (has$1(propValue, key)) {
var error = typeChecker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret_1);
if (error instanceof Error) {
return error;
}
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function createUnionTypeChecker(arrayOfTypeCheckers) {
if (!Array.isArray(arrayOfTypeCheckers)) {
printWarning$1('Invalid argument supplied to oneOfType, expected an instance of array.') ;
return emptyFunctionThatReturnsNull;
}
for (var i = 0; i < arrayOfTypeCheckers.length; i++) {
var checker = arrayOfTypeCheckers[i];
if (typeof checker !== 'function') {
printWarning$1(
'Invalid argument supplied to oneOfType. Expected an array of check functions, but ' +
'received ' + getPostfixForTypeWarning(checker) + ' at index ' + i + '.'
);
return emptyFunctionThatReturnsNull;
}
}
function validate(props, propName, componentName, location, propFullName) {
for (var i = 0; i < arrayOfTypeCheckers.length; i++) {
var checker = arrayOfTypeCheckers[i];
if (checker(props, propName, componentName, location, propFullName, ReactPropTypesSecret_1) == null) {
return null;
}
}
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`.'));
}
return createChainableTypeChecker(validate);
}
function createNodeChecker() {
function validate(props, propName, componentName, location, propFullName) {
if (!isNode(props[propName])) {
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a ReactNode.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createShapeTypeChecker(shapeTypes) {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== 'object') {
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.'));
}
for (var key in shapeTypes) {
var checker = shapeTypes[key];
if (!checker) {
continue;
}
var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret_1);
if (error) {
return error;
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function createStrictShapeTypeChecker(shapeTypes) {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== 'object') {
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.'));
}
// We need to check all keys in case some are required but missing from
// props.
var allKeys = objectAssign({}, props[propName], shapeTypes);
for (var key in allKeys) {
var checker = shapeTypes[key];
if (!checker) {
return new PropTypeError(
'Invalid ' + location + ' `' + propFullName + '` key `' + key + '` supplied to `' + componentName + '`.' +
'\nBad object: ' + JSON.stringify(props[propName], null, ' ') +
'\nValid keys: ' + JSON.stringify(Object.keys(shapeTypes), null, ' ')
);
}
var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret_1);
if (error) {
return error;
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function isNode(propValue) {
switch (typeof propValue) {
case 'number':
case 'string':
case 'undefined':
return true;
case 'boolean':
return !propValue;
case 'object':
if (Array.isArray(propValue)) {
return propValue.every(isNode);
}
if (propValue === null || isValidElement(propValue)) {
return true;
}
var iteratorFn = getIteratorFn(propValue);
if (iteratorFn) {
var iterator = iteratorFn.call(propValue);
var step;
if (iteratorFn !== propValue.entries) {
while (!(step = iterator.next()).done) {
if (!isNode(step.value)) {
return false;
}
}
} else {
// Iterator will provide entry [k,v] tuples rather than values.
while (!(step = iterator.next()).done) {
var entry = step.value;
if (entry) {
if (!isNode(entry[1])) {
return false;
}
}
}
}
} else {
return false;
}
return true;
default:
return false;
}
}
function isSymbol(propType, propValue) {
// Native Symbol.
if (propType === 'symbol') {
return true;
}
// falsy value can't be a Symbol
if (!propValue) {
return false;
}
// 19.4.3.5 Symbol.prototype[@@toStringTag] === 'Symbol'
if (propValue['@@toStringTag'] === 'Symbol') {
return true;
}
// Fallback for non-spec compliant Symbols which are polyfilled.
if (typeof Symbol === 'function' && propValue instanceof Symbol) {
return true;
}
return false;
}
// Equivalent of `typeof` but with special handling for array and regexp.
function getPropType(propValue) {
var propType = typeof propValue;
if (Array.isArray(propValue)) {
return 'array';
}
if (propValue instanceof RegExp) {
// Old webkits (at least until Android 4.0) return 'function' rather than
// 'object' for typeof a RegExp. We'll normalize this here so that /bla/
// passes PropTypes.object.
return 'object';
}
if (isSymbol(propType, propValue)) {
return 'symbol';
}
return propType;
}
// This handles more types than `getPropType`. Only used for error messages.
// See `createPrimitiveTypeChecker`.
function getPreciseType(propValue) {
if (typeof propValue === 'undefined' || propValue === null) {
return '' + propValue;
}
var propType = getPropType(propValue);
if (propType === 'object') {
if (propValue instanceof Date) {
return 'date';
} else if (propValue instanceof RegExp) {
return 'regexp';
}
}
return propType;
}
// Returns a string that is postfixed to a warning about an invalid type.
// For example, "undefined" or "of type array"
function getPostfixForTypeWarning(value) {
var type = getPreciseType(value);
switch (type) {
case 'array':
case 'object':
return 'an ' + type;
case 'boolean':
case 'date':
case 'regexp':
return 'a ' + type;
default:
return type;
}
}
// Returns class name of the object, if any.
function getClassName(propValue) {
if (!propValue.constructor || !propValue.constructor.name) {
return ANONYMOUS;
}
return propValue.constructor.name;
}
ReactPropTypes.checkPropTypes = checkPropTypes_1;
ReactPropTypes.resetWarningCache = checkPropTypes_1.resetWarningCache;
ReactPropTypes.PropTypes = ReactPropTypes;
return ReactPropTypes;
};
var propTypes = createCommonjsModule(function (module) {
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
{
var ReactIs = reactIs;
// By explicitly using `prop-types` you are opting into new development behavior.
// http://fb.me/prop-types-in-prod
var throwOnDirectAccess = true;
module.exports = factoryWithTypeCheckers(ReactIs.isElement, throwOnDirectAccess);
}
});
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var invariant = function(condition, format, a, b, c, d, e, f) {
{
if (format === undefined) {
throw new Error('invariant requires an error message argument');
}
}
if (!condition) {
var error;
if (format === undefined) {
error = new Error(
'Minified exception occurred; use the non-minified dev environment ' +
'for the full error message and additional helpful warnings.'
);
} else {
var args = [a, b, c, d, e, f];
var argIndex = 0;
error = new Error(
format.replace(/%s/g, function() { return args[argIndex++]; })
);
error.name = 'Invariant Violation';
}
error.framesToPop = 1; // we don't care about invariant's own frame
throw error;
}
};
var invariant_1 = invariant;
/**
* Common (non-printable) keycodes for `keydown` and `keyup` events. Note that
* `keypress` handles things differently and may not return the same values.
*/
var BACKSPACE = 8;
var TAB = 9;
var RETURN = 13;
var ESC = 27;
var UP = 38;
var RIGHT = 39;
var DOWN = 40;
var DEFAULT_LABELKEY = 'label';
var ALIGN = {
JUSTIFY: 'justify',
LEFT: 'left',
RIGHT: 'right'
};
var SIZE = {
LARGE: 'large',
LG: 'lg',
SM: 'sm',
SMALL: 'small'
};
function getStringLabelKey(labelKey) {
return typeof labelKey === 'string' ? labelKey : DEFAULT_LABELKEY;
}
var idCounter = 0;
function head(arr) {
return Array.isArray(arr) && arr.length ? arr[0] : undefined;
}
function isFunction(value) {
return typeof value === 'function';
}
function isString(value) {
return typeof value === 'string';
}
function noop() {}
function pick(obj, keys) {
var result = {};
keys.forEach(function (k) {
if (Object.prototype.hasOwnProperty.call(obj, k)) {
result[k] = obj[k];
}
});
return result;
}
function uniqueId(prefix) {
idCounter += 1;
return (prefix == null ? '' : String(prefix)) + idCounter;
} // Export for testing purposes.
function valuesPolyfill(obj) {
return Object.keys(obj).reduce(function (accum, key) {
if (Object.prototype.propertyIsEnumerable.call(obj, key)) {
accum.push(obj[key]);
}
return accum;
}, []);
}
function values(obj) {
return isFunction(Object.values) ? Object.values(obj) : valuesPolyfill(obj);
}
/**
* Retrieves the display string from an option. Options can be the string
* themselves, or an object with a defined display string. Anything else throws
* an error.
*/
function getOptionLabel(option, labelKey) {
// Handle internally created options first.
if (!isString(option) && (option.paginationOption || option.customOption)) {
return option[getStringLabelKey(labelKey)];
}
var optionLabel;
if (isFunction(labelKey)) {
optionLabel = labelKey(option);
} else if (isString(option)) {
optionLabel = option;
} else {
// `option` is an object and `labelKey` is a string.
optionLabel = option[labelKey];
}
!isString(optionLabel) ? invariant_1(false, 'One or more options does not have a valid label string. Check the ' + '`labelKey` prop to ensure that it matches the correct option key and ' + 'provides a string for filtering and display.') : void 0;
return optionLabel;
}
function addCustomOption(results, props) {
var allowNew = props.allowNew,
labelKey = props.labelKey,
text = props.text;
if (!allowNew || !text.trim()) {
return false;
} // If the consumer has provided a callback, use that to determine whether or
// not to add the custom option.
if (typeof allowNew === 'function') {
return allowNew(results, props);
} // By default, don't add the custom option if there is an exact text match
// with an existing option.
return !results.some(function (o) {
return getOptionLabel(o, labelKey) === text;
});
}
// do not edit .js files directly - edit src/index.jst
var fastDeepEqual = function equal(a, b) {
if (a === b) return true;
if (a && b && typeof a == 'object' && typeof b == 'object') {
if (a.constructor !== b.constructor) return false;
var length, i, keys;
if (Array.isArray(a)) {
length = a.length;
if (length != b.length) return false;
for (i = length; i-- !== 0;)
if (!equal(a[i], b[i])) return false;
return true;
}
if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;
if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();
if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();
keys = Object.keys(a);
length = keys.length;
if (length !== Object.keys(b).length) return false;
for (i = length; i-- !== 0;)
if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;
for (i = length; i-- !== 0;) {
var key = keys[i];
if (!equal(a[key], b[key])) return false;
}
return true;
}
// true if both NaN, false otherwise
return a!==a && b!==b;
};
function getOptionProperty(option, key) {
if (isString(option)) {
return undefined;
}
return option[key];
}
/**
* 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.
*
* Taken from: http://stackoverflow.com/questions/990904/remove-accents-diacritics-in-a-string-in-javascript/18391901#18391901
*/
/* eslint-disable max-len */
var map = [{
base: 'A',
letters: "A\u24B6\uFF21\xC0\xC1\xC2\u1EA6\u1EA4\u1EAA\u1EA8\xC3\u0100\u0102\u1EB0\u1EAE\u1EB4\u1EB2\u0226\u01E0\xC4\u01DE\u1EA2\xC5\u01FA\u01CD\u0200\u0202\u1EA0\u1EAC\u1EB6\u1E00\u0104\u023A\u2C6F"
}, {
base: 'AA',
letters: "\uA732"
}, {
base: 'AE',
letters: "\xC6\u01FC\u01E2"
}, {
base: 'AO',
letters: "\uA734"
}, {
base: 'AU',
letters: "\uA736"
}, {
base: 'AV',
letters: "\uA738\uA73A"
}, {
base: 'AY',
letters: "\uA73C"
}, {
base: 'B',
letters: "B\u24B7\uFF22\u1E02\u1E04\u1E06\u0243\u0182\u0181"
}, {
base: 'C',
letters: "C\u24B8\uFF23\u0106\u0108\u010A\u010C\xC7\u1E08\u0187\u023B\uA73E"
}, {
base: 'D',
letters: "D\u24B9\uFF24\u1E0A\u010E\u1E0C\u1E10\u1E12\u1E0E\u0110\u018B\u018A\u0189\uA779\xD0"
}, {
base: 'DZ',
letters: "\u01F1\u01C4"
}, {
base: 'Dz',
letters: "\u01F2\u01C5"
}, {
base: 'E',
letters: "E\u24BA\uFF25\xC8\xC9\xCA\u1EC0\u1EBE\u1EC4\u1EC2\u1EBC\u0112\u1E14\u1E16\u0114\u0116\xCB\u1EBA\u011A\u0204\u0206\u1EB8\u1EC6\u0228\u1E1C\u0118\u1E18\u1E1A\u0190\u018E"
}, {
base: 'F',
letters: "F\u24BB\uFF26\u1E1E\u0191\uA77B"
}, {
base: 'G',
letters: "G\u24BC\uFF27\u01F4\u011C\u1E20\u011E\u0120\u01E6\u0122\u01E4\u0193\uA7A0\uA77D\uA77E"
}, {
base: 'H',
letters: "H\u24BD\uFF28\u0124\u1E22\u1E26\u021E\u1E24\u1E28\u1E2A\u0126\u2C67\u2C75\uA78D"
}, {
base: 'I',
letters: "I\u24BE\uFF29\xCC\xCD\xCE\u0128\u012A\u012C\u0130\xCF\u1E2E\u1EC8\u01CF\u0208\u020A\u1ECA\u012E\u1E2C\u0197"
}, {
base: 'J',
letters: "J\u24BF\uFF2A\u0134\u0248"
}, {
base: 'K',
letters: "K\u24C0\uFF2B\u1E30\u01E8\u1E32\u0136\u1E34\u0198\u2C69\uA740\uA742\uA744\uA7A2"
}, {
base: 'L',
letters: "L\u24C1\uFF2C\u013F\u0139\u013D\u1E36\u1E38\u013B\u1E3C\u1E3A\u0141\u023D\u2C62\u2C60\uA748\uA746\uA780"
}, {
base: 'LJ',
letters: "\u01C7"
}, {
base: 'Lj',
letters: "\u01C8"
}, {
base: 'M',
letters: "M\u24C2\uFF2D\u1E3E\u1E40\u1E42\u2C6E\u019C"
}, {
base: 'N',
letters: "N\u24C3\uFF2E\u01F8\u0143\xD1\u1E44\u0147\u1E46\u0145\u1E4A\u1E48\u0220\u019D\uA790\uA7A4"
}, {
base: 'NJ',
letters: "\u01CA"
}, {
base: 'Nj',
letters: "\u01CB"
}, {
base: 'O',
letters: "O\u24C4\uFF2F\xD2\xD3\xD4\u1ED2\u1ED0\u1ED6\u1ED4\xD5\u1E4C\u022C\u1E4E\u014C\u1E50\u1E52\u014E\u022E\u0230\xD6\u022A\u1ECE\u0150\u01D1\u020C\u020E\u01A0\u1EDC\u1EDA\u1EE0\u1EDE\u1EE2\u1ECC\u1ED8\u01EA\u01EC\xD8\u01FE\u0186\u019F\uA74A\uA74C"
}, {
base: 'OI',
letters: "\u01A2"
}, {
base: 'OO',
letters: "\uA74E"
}, {
base: 'OU',
letters: "\u0222"
}, {
base: 'OE',
letters: "\x8C\u0152"
}, {
base: 'oe',
letters: "\x9C\u0153"
}, {
base: 'P',
letters: "P\u24C5\uFF30\u1E54\u1E56\u01A4\u2C63\uA750\uA752\uA754"
}, {
base: 'Q',
letters: "Q\u24C6\uFF31\uA756\uA758\u024A"
}, {
base: 'R',
letters: "R\u24C7\uFF32\u0154\u1E58\u0158\u0210\u0212\u1E5A\u1E5C\u0156\u1E5E\u024C\u2C64\uA75A\uA7A6\uA782"
}, {
base: 'S',
letters: "S\u24C8\uFF33\u1E9E\u015A\u1E64\u015C\u1E60\u0160\u1E66\u1E62\u1E68\u0218\u015E\u2C7E\uA7A8\uA784"
}, {
base: 'T',
letters: "T\u24C9\uFF34\u1E6A\u0164\u1E6C\u021A\u0162\u1E70\u1E6E\u0166\u01AC\u01AE\u023E\uA786"
}, {
base: 'TZ',
letters: "\uA728"
}, {
base: 'U',
letters: "U\u24CA\uFF35\xD9\xDA\xDB\u0168\u1E78\u016A\u1E7A\u016C\xDC\u01DB\u01D7\u01D5\u01D9\u1EE6\u016E\u0170\u01D3\u0214\u0216\u01AF\u1EEA\u1EE8\u1EEE\u1EEC\u1EF0\u1EE4\u1E72\u0172\u1E76\u1E74\u0244"
}, {
base: 'V',
letters: "V\u24CB\uFF36\u1E7C\u1E7E\u01B2\uA75E\u0245"
}, {
base: 'VY',
letters: "\uA760"
}, {
base: 'W',
letters: "W\u24CC\uFF37\u1E80\u1E82\u0174\u1E86\u1E84\u1E88\u2C72"
}, {
base: 'X',
letters: "X\u24CD\uFF38\u1E8A\u1E8C"
}, {
base: 'Y',
letters: "Y\u24CE\uFF39\u1EF2\xDD\u0176\u1EF8\u0232\u1E8E\u0178\u1EF6\u1EF4\u01B3\u024E\u1EFE"
}, {
base: 'Z',
letters: "Z\u24CF\uFF3A\u0179\u1E90\u017B\u017D\u1E92\u1E94\u01B5\u0224\u2C7F\u2C6B\uA762"
}, {
base: 'a',
letters: "a\u24D0\uFF41\u1E9A\xE0\xE1\xE2\u1EA7\u1EA5\u1EAB\u1EA9\xE3\u0101\u0103\u1EB1\u1EAF\u1EB5\u1EB3\u0227\u01E1\xE4\u01DF\u1EA3\xE5\u01FB\u01CE\u0201\u0203\u1EA1\u1EAD\u1EB7\u1E01\u0105\u2C65\u0250"
}, {
base: 'aa',
letters: "\uA733"
}, {
base: 'ae',
letters: "\xE6\u01FD\u01E3"
}, {
base: 'ao',
letters: "\uA735"
}, {
base: 'au',
letters: "\uA737"
}, {
base: 'av',
letters: "\uA739\uA73B"
}, {
base: 'ay',
letters: "\uA73D"
}, {
base: 'b',
letters: "b\u24D1\uFF42\u1E03\u1E05\u1E07\u0180\u0183\u0253"
}, {
base: 'c',
letters: "c\u24D2\uFF43\u0107\u0109\u010B\u010D\xE7\u1E09\u0188\u023C\uA73F\u2184"
}, {
base: 'd',
letters: "d\u24D3\uFF44\u1E0B\u010F\u1E0D\u1E11\u1E13\u1E0F\u0111\u018C\u0256\u0257\uA77A"
}, {
base: 'dz',
letters: "\u01F3\u01C6"
}, {
base: 'e',
letters: "e\u24D4\uFF45\xE8\xE9\xEA\u1EC1\u1EBF\u1EC5\u1EC3\u1EBD\u0113\u1E15\u1E17\u0115\u0117\xEB\u1EBB\u011B\u0205\u0207\u1EB9\u1EC7\u0229\u1E1D\u0119\u1E19\u1E1B\u0247\u025B\u01DD"
}, {
base: 'f',
letters: "f\u24D5\uFF46\u1E1F\u0192\uA77C"
}, {
base: 'g',
letters: "g\u24D6\uFF47\u01F5\u011D\u1E21\u011F\u0121\u01E7\u0123\u01E5\u0260\uA7A1\u1D79\uA77F"
}, {
base: 'h',
letters: "h\u24D7\uFF48\u0125\u1E23\u1E27\u021F\u1E25\u1E29\u1E2B\u1E96\u0127\u2C68\u2C76\u0265"
}, {
base: 'hv',
letters: "\u0195"
}, {
base: 'i',
letters: "i\u24D8\uFF49\xEC\xED\xEE\u0129\u012B\u012D\xEF\u1E2F\u1EC9\u01D0\u0209\u020B\u1ECB\u012F\u1E2D\u0268\u0131"
}, {
base: 'j',
letters: "j\u24D9\uFF4A\u0135\u01F0\u0249"
}, {
base: 'k',
letters: "k\u24DA\uFF4B\u1E31\u01E9\u1E33\u0137\u1E35\u0199\u2C6A\uA741\uA743\uA745\uA7A3"
}, {
base: 'l',
letters: "l\u24DB\uFF4C\u0140\u013A\u013E\u1E37\u1E39\u013C\u1E3D\u1E3B\u017F\u0142\u019A\u026B\u2C61\uA749\uA781\uA747"
}, {
base: 'lj',
letters: "\u01C9"
}, {
base: 'm',
letters: "m\u24DC\uFF4D\u1E3F\u1E41\u1E43\u0271\u026F"
}, {
base: 'n',
letters: "n\u24DD\uFF4E\u01F9\u0144\xF1\u1E45\u0148\u1E47\u0146\u1E4B\u1E49\u019E\u0272\u0149\uA791\uA7A5"
}, {
base: 'nj',
letters: "\u01CC"
}, {
base: 'o',
letters: "o\u24DE\uFF4F\xF2\xF3\xF4\u1ED3\u1ED1\u1ED7\u1ED5\xF5\u1E4D\u022D\u1E4F\u014D\u1E51\u1E53\u014F\u022F\u0231\xF6\u022B\u1ECF\u0151\u01D2\u020D\u020F\u01A1\u1EDD\u1EDB\u1EE1\u1EDF\u1EE3\u1ECD\u1ED9\u01EB\u01ED\xF8\u01FF\u0254\uA74B\uA74D\u0275"
}, {
base: 'oi',
letters: "\u01A3"
}, {
base: 'ou',
letters: "\u0223"
}, {
base: 'oo',
letters: "\uA74F"
}, {
base: 'p',
letters: "p\u24DF\uFF50\u1E55\u1E57\u01A5\u1D7D\uA751\uA753\uA755"
}, {
base: 'q',
letters: "q\u24E0\uFF51\u024B\uA757\uA759"
}, {
base: 'r',
letters: "r\u24E1\uFF52\u0155\u1E59\u0159\u0211\u0213\u1E5B\u1E5D\u0157\u1E5F\u024D\u027D\uA75B\uA7A7\uA783"
}, {
base: 's',
letters: "s\u24E2\uFF53\xDF\u015B\u1E65\u015D\u1E61\u0161\u1E67\u1E63\u1E69\u0219\u015F\u023F\uA7A9\uA785\u1E9B"
}, {
base: 't',
letters: "t\u24E3\uFF54\u1E6B\u1E97\u0165\u1E6D\u021B\u0163\u1E71\u1E6F\u0167\u01AD\u0288\u2C66\uA787"
}, {
base: 'tz',
letters: "\uA729"
}, {
base: 'u',
letters: "u\u24E4\uFF55\xF9\xFA\xFB\u0169\u1E79\u016B\u1E7B\u016D\xFC\u01DC\u01D8\u01D6\u01DA\u1EE7\u016F\u0171\u01D4\u0215\u0217\u01B0\u1EEB\u1EE9\u1EEF\u1EED\u1EF1\u1EE5\u1E73\u0173\u1E77\u1E75\u0289"
}, {
base: 'v',
letters: "v\u24E5\uFF56\u1E7D\u1E7F\u028B\uA75F\u028C"
}, {
base: 'vy',
letters: "\uA761"
}, {
base: 'w',
letters: "w\u24E6\uFF57\u1E81\u1E83\u0175\u1E87\u1E85\u1E98\u1E89\u2C73"
}, {
base: 'x',
letters: "x\u24E7\uFF58\u1E8B\u1E8D"
}, {
base: 'y',
letters: "y\u24E8\uFF59\u1EF3\xFD\u0177\u1EF9\u0233\u1E8F\xFF\u1EF7\u1E99\u1EF5\u01B4\u024F\u1EFF"
}, {
base: 'z',
letters: "z\u24E9\uFF5A\u017A\u1E91\u017C\u017E\u1E93\u1E95\u01B6\u0225\u0240\u2C6C\uA763"
}];
/* eslint-enable max-len */
var diacriticsMap = {};
for (var ii = 0; ii < map.length; ii++) {
var letters = map[ii].letters;
for (var jj = 0; jj < letters.length; jj++) {
diacriticsMap[letters[jj]] = map[ii].base;
}
} // "what?" version ... http://jsperf.com/diacritics/12
function stripDiacritics(str) {
return str.replace(/[\u0300-\u036F]/g, '') // Remove combining diacritics
/* eslint-disable-next-line no-control-regex */
.replace(/[^\u0000-\u007E]/g, function (a) {
return diacriticsMap[a] || a;
});
}
/**
* Copyright (c) 2014-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var warning = function() {};
{
var printWarning$2 = function printWarning(format, args) {
var len = arguments.length;
args = new Array(len > 1 ? len - 1 : 0);
for (var key = 1; key < len; key++) {
args[key - 1] = arguments[key];
}
var argIndex = 0;
var message = 'Warning: ' +
format.replace(/%s/g, function() {
return args[argIndex++];
});
if (typeof console !== 'undefined') {
console.error(message);
}
try {
// --- Welcome to debugging React ---
// This error was thrown as a convenience so that you can use this stack
// to find the callsite that caused this warning to fire.
throw new Error(message);
} catch (x) {}
};
warning = function(condition, format, args) {
var len = arguments.length;
args = new Array(len > 2 ? len - 2 : 0);
for (var key = 2; key < len; key++) {
args[key - 2] = arguments[key];
}
if (format === undefined) {
throw new Error(
'`warning(condition, format, ...args)` requires a warning ' +
'message argument'
);
}
if (!condition) {
printWarning$2.apply(null, [format].concat(args));
}
};
}
var warning_1 = warning;
var warned = {};
/**
* Copied from: https://github.com/ReactTraining/react-router/blob/master/modules/routerWarning.js
*/
function warn(falseToWarn, message) {
// Only issue deprecation warnings once.
if (!falseToWarn && message.indexOf('deprecated') !== -1) {
if (warned[message]) {
return;
}
warned[message] = true;
}
for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
args[_key - 2] = arguments[_key];
}
warning_1.apply(void 0, [falseToWarn, "[react-bootstrap-typeahead] " + message].concat(args));
}
function isMatch(input, string, props) {
var searchStr = input;
var str = string;
if (!props.caseSensitive) {
searchStr = searchStr.toLowerCase();
str = str.toLowerCase();
}
if (props.ignoreDiacritics) {
searchStr = stripDiacritics(searchStr);
str = stripDiacritics(str);
}
return str.indexOf(searchStr) !== -1;
}
/**
* Default algorithm for filtering results.
*/
function defaultFilterBy(option, props) {
var filterBy = props.filterBy,
labelKey = props.labelKey,
multiple = props.multiple,
selected = props.selected,
text = props.text; // Don't show selected options in the menu for the multi-select case.
if (multiple && selected.some(function (o) {
return fastDeepEqual(o, option);
})) {
return false;
}
if (isFunction(labelKey) && isMatch(text, labelKey(option), props)) {
return true;
}
var fields = filterBy.slice();
if (isString(labelKey)) {
// Add the `labelKey` field to the list of fields if it isn't already there.
if (fields.indexOf(labelKey) === -1) {
fields.unshift(labelKey);
}
}
if (isString(option)) {
warn(fields.length <= 1, 'You cannot filter by properties when `option` is a string.');
return isMatch(text, option, props);
}
return fields.some(function (field) {
var value = getOptionProperty(option, field);
if (!isString(value)) {
warn(false, 'Fields passed to `filterBy` should have string values. Value will ' + 'be converted to a string; results may be unexpected.');
value = String(value);
}
return isMatch(text, value, props);
});
}
function getDisplayName(Component) {
return Component.displayName || Component.name || 'Component';
}
const matchOperatorsRegex = /[|\\{}()[\]^$+*?.-]/g;
var escapeStringRegexp = string => {
if (typeof string !== 'string') {
throw new TypeError('Expected a string');
}
return string.replace(matchOperatorsRegex, '\\$&');
};
var CASE_INSENSITIVE = 'i';
var COMBINING_MARKS = /[\u0300-\u036F]/;
function getMatchBounds(subject, str) {
var search = new RegExp(escapeStringRegexp(stripDiacritics(str)), CASE_INSENSITIVE);
var matches = search.exec(stripDiacritics(subject));
if (!matches) {
return null;
}
var start = matches.index;
var matchLength = matches[0].length; // Account for combining marks, which changes the indices.
if (COMBINING_MARKS.test(subject)) {
// Starting at the beginning of the subject string, check for the number of
// combining marks and increment the start index whenever one is found.
for (var ii = 0; ii <= start; ii++) {
if (COMBINING_MARKS.test(subject[ii])) {
start += 1;
}
} // Similarly, increment the length of the match string if it contains a
// combining mark.
for (var _ii = start; _ii <= start + matchLength; _ii++) {
if (COMBINING_MARKS.test(subject[_ii])) {
matchLength += 1;
}
}
}
return {
end: start + matchLength,
start: start
};
}
function getHintText(props) {
var activeIndex = props.activeIndex,
initialItem = props.initialItem,
isFocused = props.isFocused,
isMenuShown = props.isMenuShown,
labelKey = props.labelKey,
multiple = props.multiple,
selected = props.selected,
text = props.text; // Don't display a hint under the following conditions:
if ( // No text entered.
!text || // The input is not focused.
!isFocused || // The menu is hidden.
!isMenuShown || // No item in the menu.
!initialItem || // The initial item is a custom option.
initialItem.customOption || // One of the menu items is active.
activeIndex > -1 || // There's already a selection in single-select mode.
!!selected.length && !multiple) {
return '';
}
var initialItemStr = getOptionLabel(initialItem, labelKey);
var bounds = getMatchBounds(initialItemStr.toLowerCase(), text.toLowerCase());
if (!(bounds && bounds.start === 0)) {
return '';
} // Text matching is case- and accent-insensitive, so to display the hint
// correctly, splice the input string with the hint string.
return text + initialItemStr.slice(bounds.end, initialItemStr.length);
}
var classnames = createCommonjsModule(function (module) {
/*!
Copyright (c) 2017 Jed Watson.
Licensed under the MIT License (MIT), see
http://jedwatson.github.io/classnames
*/
/* global define */
(function () {
var hasOwn = {}.hasOwnProperty;
function classNames () {
var classes = [];
for (var i = 0; i < arguments.length; i++) {
var arg = arguments[i];
if (!arg) continue;
var argType = typeof arg;
if (argType === 'string' || argType === 'number') {
classes.push(arg);
} else if (Array.isArray(arg) && arg.length) {
var inner = classNames.apply(null, arg);
if (inner) {
classes.push(inner);
}
} else if (argType === 'object') {
for (var key in arg) {
if (hasOwn.call(arg, key) && arg[key]) {
classes.push(key);
}
}
}
}
return classes.join(' ');
}
if ( module.exports) {
classNames.default = classNames;
module.exports = classNames;
} else {
window.classNames = classNames;
}
}());
});
function getMenuItemId(id, position) {
return (id || '') + "-item-" + position;
}
var getInputProps = function getInputProps(_ref) {
var activeIndex = _ref.activeIndex,
id = _ref.id,
isFocused = _ref.isFocused,
isMenuShown = _ref.isMenuShown,
multiple = _ref.multiple,
onFocus = _ref.onFocus,
placeholder = _ref.placeholder,
rest = _objectWithoutPropertiesLoose(_ref, ["activeIndex", "id", "isFocused", "isMenuShown", "multiple", "onFocus", "placeholder"]);
return function (_ref2) {
var _cx;
if (_ref2 === void 0) {
_ref2 = {};
}
var _ref3 = _ref2,
className = _ref3.className,
inputProps = _objectWithoutPropertiesLoose(_ref3, ["className"]);
var props = _extends({
/* eslint-disable sort-keys */
// These props can be overridden by values in `inputProps`.
autoComplete: 'off',
placeholder: placeholder,
type: 'text'
}, inputProps, {}, rest, {
'aria-activedescendant': activeIndex >= 0 ? getMenuItemId(id, activeIndex) : undefined,
'aria-autocomplete': 'both',
'aria-expanded': isMenuShown,
'aria-haspopup': 'listbox',
'aria-owns': isMenuShown ? id : undefined,
className: classnames((_cx = {}, _cx[className || ''] = !multiple, _cx.focus = isFocused, _cx)),
// Re-open the menu, eg: if it's closed via ESC.
onClick: onFocus,
onFocus: onFocus,
// Comboboxes are single-select by definition:
// https://www.w3.org/TR/wai-aria-practices-1.1/#combobox
role: 'combobox'
/* eslint-enable sort-keys */
});
if (!multiple) {
return props;
}
return _extends({}, props, {
'aria-autocomplete': 'list',
'aria-expanded': undefined,
inputClassName: className,
role: undefined
});
};
};
function getInputText(props) {
var activeItem = props.activeItem,
labelKey = props.labelKey,
multiple = props.multiple,
selected = props.selected,
text = props.text;
if (activeItem) {
// Display the input value if the pagination item is active.
return getOptionLabel(activeItem, labelKey);
}
var selectedItem = !multiple && !!selected.length && head(selected);
if (selectedItem) {
return getOptionLabel(selectedItem, labelKey);
}
return text;
}
function getIsOnlyResult(props) {
var allowNew = props.allowNew,
highlightOnlyResult = props.highlightOnlyResult,
results = props.results;
if (!highlightOnlyResult || allowNew) {
return false;
}
return results.length === 1 && !getOptionProperty(head(results), 'disabled');
}
/**
* Truncates the result set based on `maxResults` and returns the new set.
*/
function getTruncatedOptions(options, maxResults) {
if (!maxResults || maxResults >= options.length) {
return options;
}
return options.slice(0, maxResults);
}
function skipDisabledOptions(currentIndex, keyCode, items) {
var newIndex = currentIndex;
while (items[newIndex] && items[newIndex].disabled) {
newIndex += keyCode === UP ? -1 : 1;
}
return newIndex;
}
function getUpdatedActiveIndex(currentIndex, keyCode, items) {
var newIndex = currentIndex; // Increment or decrement index based on user keystroke.
newIndex += keyCode === UP ? -1 : 1; // Skip over any disabled options.
newIndex = skipDisabledOptions(newIndex, keyCode, items); // If we've reached the end, go back to the beginning or vice-versa.
if (newIndex === items.length) {
newIndex = -1;
} else if (newIndex === -2) {
newIndex = items.length - 1; // Skip over any disabled options.
newIndex = skipDisabledOptions(newIndex, keyCode, items);
}
return newIndex;
}
/**
* Check if an input type is selectable, based on WHATWG spec.
*
* See:
* - https://stackoverflow.com/questions/21177489/selectionstart-selectionend-on-input-type-number-no-longer-allowed-in-chrome/24175357
* - https://html.spec.whatwg.org/multipage/input.html#do-not-apply
*/
function isSelectable(inputNode) {
return inputNode.selectionStart != null;
}
function isShown(props) {
var open = props.open,
minLength = props.minLength,
showMenu = props.showMenu,
text = props.text; // If menu visibility is controlled via props, that value takes precedence.
if (open || open === false) {
return open;
}
if (text.length < minLength) {
return false;
}
return showMenu;
}
/**
* Prevent the main input from blurring when a menu item or the clear button is
* clicked. (#226 & #310)
*/
function preventInputBlur(e) {
e.preventDefault();
}
function shouldSelectHint(_ref, _ref2) {
var currentTarget = _ref.currentTarget,
keyCode = _ref.keyCode;
var hintText = _ref2.hintText,
selectHintOnEnter = _ref2.selectHintOnEnter,
value = _ref2.value;
if (!hintText) {
return false;
}
if (keyCode === RIGHT) {
// For selectable input types ("text", "search"), only select the hint if
// it's at the end of the input value. For non-selectable types ("email",
// "number"), always select the hint.
return isSelectable(currentTarget) ? currentTarget.selectionStart === value.length : true;
}
if (keyCode === TAB) {
return true;
}
if (keyCode === RETURN && selectHintOnEnter) {
return true;
}
return false;
}
function isSizeLarge(size) {
return size === 'large' || size === 'lg';
}
function isSizeSmall(size) {
return size === 'small' || size === 'sm';
}
function validateSelectedPropChange(prevSelected, selected) {
var uncontrolledToControlled = !prevSelected && selected;
var controlledToUncontrolled = prevSelected && !selected;
var from, to, precedent;
if (uncontrolledToControlled) {
from = 'uncontrolled';
to = 'controlled';
precedent = 'an';
} else {
from = 'controlled';
to = 'uncontrolled';
precedent = 'a';
}
var message = "You are changing " + precedent + " " + from + " typeahead to be " + to + ". " + ("Input elements should not switch from " + from + " to " + to + " (or vice versa). ") + 'Decide between using a controlled or uncontrolled element for the ' + 'lifetime of the component.';
warn(!(uncontrolledToControlled || controlledToUncontrolled), message);
}
var INPUT_PROPS_BLACKLIST = [{
alt: 'onBlur',
prop: 'onBlur'
}, {
alt: 'onInputChange',
prop: 'onChange'
}, {
alt: 'onFocus',
prop: 'onFocus'
}, {
alt: 'onKeyDown',
prop: 'onKeyDown'
}];
var sizeType = propTypes.oneOf(values(SIZE));
/**
* Allows additional warnings or messaging related to prop validation.
*/
function checkPropType(validator, callback) {
return function (props, propName, componentName) {
var _PropTypes$checkPropT;
propTypes.checkPropTypes((_PropTypes$checkPropT = {}, _PropTypes$checkPropT[propName] = validator, _PropTypes$checkPropT), props, 'prop', componentName);
isFunction(callback) && callback(props, propName, componentName);
};
}
function caseSensitiveType(props, propName, componentName) {
var caseSensitive = props.caseSensitive,
filterBy = props.filterBy;
warn(!caseSensitive || typeof filterBy !== 'function', 'Your `filterBy` function will override the `caseSensitive` prop.');
}
function defaultInputValueType(props, propName, componentName) {
var defaultInputValue = props.defaultInputValue,
defaultSelected = props.defaultSelected,
multiple = props.multiple,
selected = props.selected;
var name = defaultSelected.length ? 'defaultSelected' : 'selected';
warn(!(!multiple && defaultInputValue && (defaultSelected.length || selected && selected.length)), "`defaultInputValue` will be overridden by the value from `" + name + "`.");
}
function defaultSelectedType(props, propName, componentName) {
var defaultSelected = props.defaultSelected,
multiple = props.multiple;
warn(multiple || defaultSelected.length <= 1, 'You are passing multiple options to the `defaultSelected` prop of a ' + 'Typeahead in single-select mode. The selections will be truncated to a ' + 'single selection.');
}
function highlightOnlyResultType(props, propName, componentName) {
var allowNew = props.allowNew,
highlightOnlyResult = props.highlightOnlyResult;
warn(!(highlightOnlyResult && allowNew), '`highlightOnlyResult` will not work with `allowNew`.');
}
function ignoreDiacriticsType(props, propName, componentName) {
var filterBy = props.filterBy,
ignoreDiacritics = props.ignoreDiacritics;
warn(ignoreDiacritics || typeof filterBy !== 'function', 'Your `filterBy` function will override the `ignoreDiacritics` prop.');
}
function inputPropsType(props, propName, componentName) {
var inputProps = props.inputProps;
if (!(inputProps && Object.prototype.toString.call(inputProps) === '[object Object]')) {
return;
} // Blacklisted properties.
INPUT_PROPS_BLACKLIST.forEach(function (_ref) {
var alt = _ref.alt,
prop = _ref.prop;
var msg = alt ? " Use the top-level `" + alt + "` prop instead." : null;
warn(!inputProps[prop], "The `" + prop + "` property of `inputProps` will be ignored." + msg);
});
}
function isRequiredForA11y(props, propName, componentName) {
warn(props[propName] != null, "The prop `" + propName + "` is required to make `" + componentName + "` " + 'accessible for users of assistive technologies such as screen readers.');
}
function labelKeyType(props, propName, componentName) {
var allowNew = props.allowNew,
labelKey = props.labelKey;
warn(!(isFunction(labelKey) && allowNew), '`labelKey` must be a string when `allowNew={true}`.');
}
var optionType = propTypes.oneOfType([propTypes.object, propTypes.string]);
function selectedType(props, propName, componentName) {
var multiple = props.multiple,
onChange = props.onChange,
selected = props.selected;
warn(multiple || !selected || selected.length <= 1, 'You are passing multiple options to the `selected` prop of a Typeahead ' + 'in single-select mode. This may lead to unexpected behaviors or errors.');
warn(!selected || selected && isFunction(onChange), 'You provided a `selected` prop without an `onChange` handler. If you ' + 'want the typeahead to be uncontrolled, use `defaultSelected`. ' + 'Otherwise, set `onChange`.');
}
var propTypes$1 = {
/**
* Delay, in milliseconds, before performing search.
*/
delay: propTypes.number,
/**
* Whether or not a request is currently pending. Necessary for the
* container to know when new results are available.
*/
isLoading: propTypes.bool.isRequired,
/**
* Number of input characters that must be entered before showing results.
*/
minLength: propTypes.number,
/**
* Callback to perform when the search is executed.
*/
onSearch: propTypes.func.isRequired,
/**
* Options to be passed to the typeahead. Will typically be the query
* results, but can also be initial default options.
*/
options: propTypes.arrayOf(optionType),
/**
* Message displayed in the menu when there is no user input.
*/
promptText: propTypes.node,
/**
* Message displayed in the menu while the request is pending.
*/
searchText: propTypes.node,
/**
* Whether or not the component should cache query results.
*/
useCache: propTypes.bool
};
var defaultProps = {
delay: 200,
minLength: 2,
options: [],
promptText: 'Type to search...',
searchText: 'Searching...',
useCache: true
};
/**
* HoC that encapsulates common behavior and functionality for doing
* asynchronous searches, including:
*
* - Debouncing user input
* - Optional query caching
* - Search prompt and empty results behaviors
*/
var asyncContainer = function asyncContainer(Typeahead) {
var _class, _temp;
return _temp = _class = /*#__PURE__*/function (_React$Component) {
_inheritsLoose(_class, _React$Component);
function _class() {
var _this;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;
_defineProperty(_assertThisInitialized(_this), "_cache", {});
_defineProperty(_assertThisInitialized(_this), "_handleSearchDebounced", void 0);
_defineProperty(_assertThisInitialized(_this), "_instance", void 0);
_defineProperty(_assertThisInitialized(_this), "_query", _this.props.defaultInputValue || '');
_defineProperty(_assertThisInitialized(_this), "_getEmptyLabel", function () {
var _this$props = _this.props,
emptyLabel = _this$props.emptyLabel,
isLoading = _this$props.isLoading,
promptText = _this$props.promptText,
searchText = _this$props.searchText;
if (!_this._query.length) {
return promptText;
}
if (isLoading) {
return searchText;
}
return emptyLabel;
});
_defineProperty(_assertThisInitialized(_this), "_handleInputChange", function (query, e) {
_this.props.onInputChange && _this.props.onInputChange(query, e);
_this._handleSearchDebounced(query);
});
_defineProperty(_assertThisInitialized(_this), "_handleSearch", function (query) {
_this._query = query;
var _this$props2 = _this.props,
minLength = _this$props2.minLength,
onSearch = _this$props2.onSearch,
useCache = _this$props2.useCache;
if (!query || minLength && query.length < minLength) {
return;
} // Use cached results, if applicable.
if (useCache && _this._cache[query]) {
// Re-render the component with the cached results.
_this.forceUpdate();
return;
} // Perform the search.
onSearch(query);
});
return _this;
}
var _proto = _class.prototype;
_proto.componentDidMount = function componentDidMount() {
this._handleSearchDebounced = lodash_debounce(this._handleSearch, this.props.delay);
};
_proto.componentDidUpdate = function componentDidUpdate(prevProps) {
var _this$props3 = this.props,
isLoading = _this$props3.isLoading,
options = _this$props3.options,
useCache = _this$props3.useCache; // Ensure that we've gone from a loading to a completed state. Otherwise
// an empty response could get cached if the component updates during the
// request (eg: if the parent re-renders for some reason).
if (!isLoading && prevProps.isLoading && useCache) {
this._cache[this._query] = options;
}
};
_proto.componentWillUnmount = function componentWillUnmount() {
this._cache = {};
this._query = '';
this._handleSearchDebounced && this._handleSearchDebounced.cancel();
};
_proto.render = function render() {
var _this2 = this;
var _this$props4 = this.props,
allowNew = _this$props4.allowNew,
isLoading = _this$props4.isLoading,
options = _this$props4.options,
useCache = _this$props4.useCache,
props = _objectWithoutPropertiesLoose(_this$props4, ["allowNew", "isLoading", "options", "useCache"]);
var cachedQuery = this._cache[this._query];
return React__default.createElement(Typeahead, _extends({}, props, {
allowNew: // Disable custom selections during a search unless
// `allowNew` is a function.
isFunction(allowNew) ? allowNew : allowNew && !isLoading,
emptyLabel: this._getEmptyLabel(),
isLoading: isLoading,
onInputChange: this._handleInputChange,
options: useCache && cachedQuery ? cachedQuery : options,
ref: function ref(instance) {
return _this2._instance = instance;
}
}));
}
/**
* Make the component instance available.
*/
;
_proto.getInstance = function getInstance() {
return this._instance && this._instance.getInstance();
};
return _class;
}(React__default.Component), _defineProperty(_class, "displayName", "asyncContainer(" + getDisplayName(Typeahead) + ")"), _defineProperty(_class, "propTypes", propTypes$1), _defineProperty(_class, "defaultProps", defaultProps), _temp;
};
function _objectWithoutPropertiesLoose$1(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i;
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
var objectWithoutPropertiesLoose = _objectWithoutPropertiesLoose$1;
var _extends_1 = createCommonjsModule(function (module) {
function _extends() {
module.exports = _extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
return _extends.apply(this, arguments);
}
module.exports = _extends;
});
function _assertThisInitialized$1(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
var assertThisInitialized = _assertThisInitialized$1;
function _inheritsLoose$1(subClass, superClass) {
subClass.prototype = Object.create(superClass.prototype);
subClass.prototype.constructor = subClass;
subClass.__proto__ = superClass;
}
var inheritsLoose = _inheritsLoose$1;
function _defineProperty$1(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
var defineProperty = _defineProperty$1;
var toStr = Object.prototype.toString;
var isArguments = function isArguments(value) {
var str = toStr.call(value);
var isArgs = str === '[object Arguments]';
if (!isArgs) {
isArgs = str !== '[object Array]' &&
value !== null &&
typeof value === 'object' &&
typeof value.length === 'number' &&
value.length >= 0 &&
toStr.call(value.callee) === '[object Function]';
}
return isArgs;
};
var keysShim;
if (!Object.keys) {
// modified from https://github.com/es-shims/es5-shim
var has$2 = Object.prototype.hasOwnProperty;
var toStr$1 = Object.prototype.toString;
var isArgs = isArguments; // eslint-disable-line global-require
var isEnumerable = Object.prototype.propertyIsEnumerable;
var hasDontEnumBug = !isEnumerable.call({ toString: null }, 'toString');
var hasProtoEnumBug = isEnumerable.call(function () {}, 'prototype');
var dontEnums = [
'toString',
'toLocaleString',
'valueOf',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'constructor'
];
var equalsConstructorPrototype = function (o) {
var ctor = o.constructor;
return ctor && ctor.prototype === o;
};
var excludedKeys = {
$applicationCache: true,
$console: true,
$external: true,
$frame: true,
$frameElement: true,
$frames: true,
$innerHeight: true,
$innerWidth: true,
$onmozfullscreenchange: true,
$onmozfullscreenerror: true,
$outerHeight: true,
$outerWidth: true,
$pageXOffset: true,
$pageYOffset: true,
$parent: true,
$scrollLeft: true,
$scrollTop: true,
$scrollX: true,
$scrollY: true,
$self: true,
$webkitIndexedDB: true,
$webkitStorageInfo: true,
$window: true
};
var hasAutomationEqualityBug = (function () {
/* global window */
if (typeof window === 'undefined') { return false; }
for (var k in window) {
try {
if (!excludedKeys['$' + k] && has$2.call(window, k) && window[k] !== null && typeof window[k] === 'object') {
try {
equalsConstructorPrototype(window[k]);
} catch (e) {
return true;
}
}
} catch (e) {
return true;
}
}
return false;
}());
var equalsConstructorPrototypeIfNotBuggy = function (o) {
/* global window */
if (typeof window === 'undefined' || !hasAutomationEqualityBug) {
return equalsConstructorPrototype(o);
}
try {
return equalsConstructorPrototype(o);
} catch (e) {
return false;
}
};
keysShim = function keys(object) {
var isObject = object !== null && typeof object === 'object';
var isFunction = toStr$1.call(object) === '[object Function]';
var isArguments = isArgs(object);
var isString = isObject && toStr$1.call(object) === '[object String]';
var theKeys = [];
if (!isObject && !isFunction && !isArguments) {
throw new TypeError('Object.keys called on a non-object');
}
var skipProto = hasProtoEnumBug && isFunction;
if (isString && object.length > 0 && !has$2.call(object, 0)) {
for (var i = 0; i < object.length; ++i) {
theKeys.push(String(i));
}
}
if (isArguments && object.length > 0) {
for (var j = 0; j < object.length; ++j) {
theKeys.push(String(j));
}
} else {
for (var name in object) {
if (!(skipProto && name === 'prototype') && has$2.call(object, name)) {
theKeys.push(String(name));
}
}
}
if (hasDontEnumBug) {
var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object);
for (var k = 0; k < dontEnums.length; ++k) {
if (!(skipConstructor && dontEnums[k] === 'constructor') && has$2.call(object, dontEnums[k])) {
theKeys.push(dontEnums[k]);
}
}
}
return theKeys;
};
}
var implementation = keysShim;
var slice = Array.prototype.slice;
var origKeys = Object.keys;
var keysShim$1 = origKeys ? function keys(o) { return origKeys(o); } : implementation;
var originalKeys = Object.keys;
keysShim$1.shim = function shimObjectKeys() {
if (Object.keys) {
var keysWorksWithArguments = (function () {
// Safari 5.0 bug
var args = Object.keys(arguments);
return args && args.length === arguments.length;
}(1, 2));
if (!keysWorksWithArguments) {
Object.keys = function keys(object) { // eslint-disable-line func-name-matching
if (isArguments(object)) {
return originalKeys(slice.call(object));
}
return originalKeys(object);
};
}
} else {
Object.keys = keysShim$1;
}
return Object.keys || keysShim$1;
};
var objectKeys = keysShim$1;
var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol';
var toStr$2 = Object.prototype.toString;
var isStandardArguments = function isArguments(value) {
if (hasToStringTag && value && typeof value === 'object' && Symbol.toStringTag in value) {
return false;
}
return toStr$2.call(value) === '[object Arguments]';
};
var isLegacyArguments = function isArguments(value) {
if (isStandardArguments(value)) {
return true;
}
return value !== null &&
typeof value === 'object' &&
typeof value.length === 'number' &&
value.length >= 0 &&
toStr$2.call(value) !== '[object Array]' &&
toStr$2.call(value.callee) === '[object Function]';
};
var supportsStandardArguments = (function () {
return isStandardArguments(arguments);
}());
isStandardArguments.isLegacyArguments = isLegacyArguments; // for tests
var isArguments$1 = supportsStandardArguments ? isStandardArguments : isLegacyArguments;
// http://www.ecma-international.org/ecma-262/6.0/#sec-object.is
var numberIsNaN = function (value) {
return value !== value;
};
var objectIs = function is(a, b) {
if (a === 0 && b === 0) {
return 1 / a === 1 / b;
}
if (a === b) {
return true;
}
if (numberIsNaN(a) && numberIsNaN(b)) {
return true;
}
return false;
};
/* eslint no-invalid-this: 1 */
var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible ';
var slice$1 = Array.prototype.slice;
var toStr$3 = Object.prototype.toString;
var funcType = '[object Function]';
var implementation$1 = function bind(that) {
var target = this;
if (typeof target !== 'function' || toStr$3.call(target) !== funcType) {
throw new TypeError(ERROR_MESSAGE + target);
}
var args = slice$1.call(arguments, 1);
var bound;
var binder = function () {
if (this instanceof bound) {
var result = target.apply(
this,
args.concat(slice$1.call(arguments))
);
if (Object(result) === result) {
return result;
}
return this;
} else {
return target.apply(
that,
args.concat(slice$1.call(arguments))
);
}
};
var boundLength = Math.max(0, target.length - args.length);
var boundArgs = [];
for (var i = 0; i < boundLength; i++) {
boundArgs.push('$' + i);
}
bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder);
if (target.prototype) {
var Empty = function Empty() {};
Empty.prototype = target.prototype;
bound.prototype = new Empty();
Empty.prototype = null;
}
return bound;
};
var functionBind = Function.prototype.bind || implementation$1;
var src = functionBind.call(Function.call, Object.prototype.hasOwnProperty);
var regexExec = RegExp.prototype.exec;
var gOPD = Object.getOwnPropertyDescriptor;
var tryRegexExecCall = function tryRegexExec(value) {
try {
var lastIndex = value.lastIndex;
value.lastIndex = 0; // eslint-disable-line no-param-reassign
regexExec.call(value);
return true;
} catch (e) {
return false;
} finally {
value.lastIndex = lastIndex; // eslint-disable-line no-param-reassign
}
};
var toStr$4 = Object.prototype.toString;
var regexClass = '[object RegExp]';
var hasToStringTag$1 = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol';
var isRegex = function isRegex(value) {
if (!value || typeof value !== 'object') {
return false;
}
if (!hasToStringTag$1) {
return toStr$4.call(value) === regexClass;
}
var descriptor = gOPD(value, 'lastIndex');
var hasLastIndexDataProperty = descriptor && src(descriptor, 'value');
if (!hasLastIndexDataProperty) {
return false;
}
return tryRegexExecCall(value);
};
var hasSymbols = typeof Symbol === 'function' && typeof Symbol('foo') === 'symbol';
var toStr$5 = Object.prototype.toString;
var concat = Array.prototype.concat;
var origDefineProperty = Object.defineProperty;
var isFunction$1 = function (fn) {
return typeof fn === 'function' && toStr$5.call(fn) === '[object Function]';
};
var arePropertyDescriptorsSupported = function () {
var obj = {};
try {
origDefineProperty(obj, 'x', { enumerable: false, value: obj });
// eslint-disable-next-line no-unused-vars, no-restricted-syntax
for (var _ in obj) { // jscs:ignore disallowUnusedVariables
return false;
}
return obj.x === obj;
} catch (e) { /* this is IE 8. */
return false;
}
};
var supportsDescriptors = origDefineProperty && arePropertyDescriptorsSupported();
var defineProperty$1 = function (object, name, value, predicate) {
if (name in object && (!isFunction$1(predicate) || !predicate())) {
return;
}
if (supportsDescriptors) {
origDefineProperty(object, name, {
configurable: true,
enumerable: false,
value: value,
writable: true
});
} else {
object[name] = value;
}
};
var defineProperties = function (object, map) {
var predicates = arguments.length > 2 ? arguments[2] : {};
var props = objectKeys(map);
if (hasSymbols) {
props = concat.call(props, Object.getOwnPropertySymbols(map));
}
for (var i = 0; i < props.length; i += 1) {
defineProperty$1(object, props[i], map[props[i]], predicates[props[i]]);
}
};
defineProperties.supportsDescriptors = !!supportsDescriptors;
var defineProperties_1 = defineProperties;
/* eslint complexity: [2, 18], max-statements: [2, 33] */
var shams = function hasSymbols() {
if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; }
if (typeof Symbol.iterator === 'symbol') { return true; }
var obj = {};
var sym = Symbol('test');
var symObj = Object(sym);
if (typeof sym === 'string') { return false; }
if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; }
if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; }
// temp disabled per https://github.com/ljharb/object.assign/issues/17
// if (sym instanceof Symbol) { return false; }
// temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4
// if (!(symObj instanceof Symbol)) { return false; }
// if (typeof Symbol.prototype.toString !== 'function') { return false; }
// if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; }
var symVal = 42;
obj[sym] = symVal;
for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax
if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; }
if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; }
var syms = Object.getOwnPropertySymbols(obj);
if (syms.length !== 1 || syms[0] !== sym) { return false; }
if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; }
if (typeof Object.getOwnPropertyDescriptor === 'function') {
var descriptor = Object.getOwnPropertyDescriptor(obj, sym);
if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; }
}
return true;
};
var origSymbol = commonjsGlobal.Symbol;
var hasSymbols$1 = function hasNativeSymbols() {
if (typeof origSymbol !== 'function') { return false; }
if (typeof Symbol !== 'function') { return false; }
if (typeof origSymbol('foo') !== 'symbol') { return false; }
if (typeof Symbol('bar') !== 'symbol') { return false; }
return shams();
};
/* globals
Atomics,
SharedArrayBuffer,
*/
var undefined$1;
var $TypeError = TypeError;
var $gOPD = Object.getOwnPropertyDescriptor;
if ($gOPD) {
try {
$gOPD({}, '');
} catch (e) {
$gOPD = null; // this is IE 8, which has a broken gOPD
}
}
var throwTypeError = function () { throw new $TypeError(); };
var ThrowTypeError = $gOPD
? (function () {
try {
// eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties
arguments.callee; // IE 8 does not throw here
return throwTypeError;
} catch (calleeThrows) {
try {
// IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '')
return $gOPD(arguments, 'callee').get;
} catch (gOPDthrows) {
return throwTypeError;
}
}
}())
: throwTypeError;
var hasSymbols$2 = hasSymbols$1();
var getProto = Object.getPrototypeOf || function (x) { return x.__proto__; }; // eslint-disable-line no-proto
var generatorFunction = undefined$1;
var asyncFunction = undefined$1;
var asyncGenFunction = undefined$1;
var TypedArray = typeof Uint8Array === 'undefined' ? undefined$1 : getProto(Uint8Array);
var INTRINSICS = {
'%Array%': Array,
'%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined$1 : ArrayBuffer,
'%ArrayBufferPrototype%': typeof ArrayBuffer === 'undefined' ? undefined$1 : ArrayBuffer.prototype,
'%ArrayIteratorPrototype%': hasSymbols$2 ? getProto([][Symbol.iterator]()) : undefined$1,
'%ArrayPrototype%': Array.prototype,
'%ArrayProto_entries%': Array.prototype.entries,
'%ArrayProto_forEach%': Array.prototype.forEach,
'%ArrayProto_keys%': Array.prototype.keys,
'%ArrayProto_values%': Array.prototype.values,
'%AsyncFromSyncIteratorPrototype%': undefined$1,
'%AsyncFunction%': asyncFunction,
'%AsyncFunctionPrototype%': undefined$1,
'%AsyncGenerator%': undefined$1,
'%AsyncGeneratorFunction%': asyncGenFunction,
'%AsyncGeneratorPrototype%': undefined$1,
'%AsyncIteratorPrototype%': undefined$1,
'%Atomics%': typeof Atomics === 'undefined' ? undefined$1 : Atomics,
'%Boolean%': Boolean,
'%BooleanPrototype%': Boolean.prototype,
'%DataView%': typeof DataView === 'undefined' ? undefined$1 : DataView,
'%DataViewPrototype%': typeof DataView === 'undefined' ? undefined$1 : DataView.prototype,
'%Date%': Date,
'%DatePrototype%': Date.prototype,
'%decodeURI%': decodeURI,
'%decodeURIComponent%': decodeURIComponent,
'%encodeURI%': encodeURI,
'%encodeURIComponent%': encodeURIComponent,
'%Error%': Error,
'%ErrorPrototype%': Error.prototype,
'%eval%': eval, // eslint-disable-line no-eval
'%EvalError%': EvalError,
'%EvalErrorPrototype%': EvalError.prototype,
'%Float32Array%': typeof Float32Array === 'undefined' ? undefined$1 : Float32Array,
'%Float32ArrayPrototype%': typeof Float32Array === 'undefined' ? undefined$1 : Float32Array.prototype,
'%Float64Array%': typeof Float64Array === 'undefined' ? undefined$1 : Float64Array,
'%Float64ArrayPrototype%': typeof Float64Array === 'undefined' ? undefined$1 : Float64Array.prototype,
'%Function%': Function,
'%FunctionPrototype%': Function.prototype,
'%Generator%': undefined$1,
'%GeneratorFunction%': generatorFunction,
'%GeneratorPrototype%': undefined$1,
'%Int8Array%': typeof Int8Array === 'undefined' ? undefined$1 : Int8Array,
'%Int8ArrayPrototype%': typeof Int8Array === 'undefined' ? undefined$1 : Int8Array.prototype,
'%Int16Array%': typeof Int16Array === 'undefined' ? undefined$1 : Int16Array,
'%Int16ArrayPrototype%': typeof Int16Array === 'undefined' ? undefined$1 : Int8Array.prototype,
'%Int32Array%': typeof Int32Array === 'undefined' ? undefined$1 : Int32Array,
'%Int32ArrayPrototype%': typeof Int32Array === 'undefined' ? undefined$1 : Int32Array.prototype,
'%isFinite%': isFinite,
'%isNaN%': isNaN,
'%IteratorPrototype%': hasSymbols$2 ? getProto(getProto([][Symbol.iterator]())) : undefined$1,
'%JSON%': typeof JSON === 'object' ? JSON : undefined$1,
'%JSONParse%': typeof JSON === 'object' ? JSON.parse : undefined$1,
'%Map%': typeof Map === 'undefined' ? undefined$1 : Map,
'%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols$2 ? undefined$1 : getProto(new Map()[Symbol.iterator]()),
'%MapPrototype%': typeof Map === 'undefined' ? undefined$1 : Map.prototype,
'%Math%': Math,
'%Number%': Number,
'%NumberPrototype%': Number.prototype,
'%Object%': Object,
'%ObjectPrototype%': Object.prototype,
'%ObjProto_toString%': Object.prototype.toString,
'%ObjProto_valueOf%': Object.prototype.valueOf,
'%parseFloat%': parseFloat,
'%parseInt%': parseInt,
'%Promise%': typeof Promise === 'undefined' ? undefined$1 : Promise,
'%PromisePrototype%': typeof Promise === 'undefined' ? undefined$1 : Promise.prototype,
'%PromiseProto_then%': typeof Promise === 'undefined' ? undefined$1 : Promise.prototype.then,
'%Promise_all%': typeof Promise === 'undefined' ? undefined$1 : Promise.all,
'%Promise_reject%': typeof Promise === 'undefined' ? undefined$1 : Promise.reject,
'%Promise_resolve%': typeof Promise === 'undefined' ? undefined$1 : Promise.resolve,
'%Proxy%': typeof Proxy === 'undefined' ? undefined$1 : Proxy,
'%RangeError%': RangeError,
'%RangeErrorPrototype%': RangeError.prototype,
'%ReferenceError%': ReferenceError,
'%ReferenceErrorPrototype%': ReferenceError.prototype,
'%Reflect%': typeof Reflect === 'undefined' ? undefined$1 : Reflect,
'%RegExp%': RegExp,
'%RegExpPrototype%': RegExp.prototype,
'%Set%': typeof Set === 'undefined' ? undefined$1 : Set,
'%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols$2 ? undefined$1 : getProto(new Set()[Symbol.iterator]()),
'%SetPrototype%': typeof Set === 'undefined' ? undefined$1 : Set.prototype,
'%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined$1 : SharedArrayBuffer,
'%SharedArrayBufferPrototype%': typeof SharedArrayBuffer === 'undefined' ? undefined$1 : SharedArrayBuffer.prototype,
'%String%': String,
'%StringIteratorPrototype%': hasSymbols$2 ? getProto(''[Symbol.iterator]()) : undefined$1,
'%StringPrototype%': String.prototype,
'%Symbol%': hasSymbols$2 ? Symbol : undefined$1,
'%SymbolPrototype%': hasSymbols$2 ? Symbol.prototype : undefined$1,
'%SyntaxError%': SyntaxError,
'%SyntaxErrorPrototype%': SyntaxError.prototype,
'%ThrowTypeError%': ThrowTypeError,
'%TypedArray%': TypedArray,
'%TypedArrayPrototype%': TypedArray ? TypedArray.prototype : undefined$1,
'%TypeError%': $TypeError,
'%TypeErrorPrototype%': $TypeError.prototype,
'%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined$1 : Uint8Array,
'%Uint8ArrayPrototype%': typeof Uint8Array === 'undefined' ? undefined$1 : Uint8Array.prototype,
'%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined$1 : Uint8ClampedArray,
'%Uint8ClampedArrayPrototype%': typeof Uint8ClampedArray === 'undefined' ? undefined$1 : Uint8ClampedArray.prototype,
'%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined$1 : Uint16Array,
'%Uint16ArrayPrototype%': typeof Uint16Array === 'undefined' ? undefined$1 : Uint16Array.prototype,
'%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined$1 : Uint32Array,
'%Uint32ArrayPrototype%': typeof Uint32Array === 'undefined' ? undefined$1 : Uint32Array.prototype,
'%URIError%': URIError,
'%URIErrorPrototype%': URIError.prototype,
'%WeakMap%': typeof WeakMap === 'undefined' ? undefined$1 : WeakMap,
'%WeakMapPrototype%': typeof WeakMap === 'undefined' ? undefined$1 : WeakMap.prototype,
'%WeakSet%': typeof WeakSet === 'undefined' ? undefined$1 : WeakSet,
'%WeakSetPrototype%': typeof WeakSet === 'undefined' ? undefined$1 : WeakSet.prototype
};
var $replace = functionBind.call(Function.call, String.prototype.replace);
/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */
var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g;
var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */
var stringToPath = function stringToPath(string) {
var result = [];
$replace(string, rePropName, function (match, number, quote, subString) {
result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : (number || match);
});
return result;
};
/* end adaptation */
var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) {
if (!(name in INTRINSICS)) {
throw new SyntaxError('intrinsic ' + name + ' does not exist!');
}
// istanbul ignore if // hopefully this is impossible to test :-)
if (typeof INTRINSICS[name] === 'undefined' && !allowMissing) {
throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!');
}
return INTRINSICS[name];
};
var GetIntrinsic = function GetIntrinsic(name, allowMissing) {
if (typeof name !== 'string' || name.length === 0) {
throw new TypeError('intrinsic name must be a non-empty string');
}
if (arguments.length > 1 && typeof allowMissing !== 'boolean') {
throw new TypeError('"allowMissing" argument must be a boolean');
}
var parts = stringToPath(name);
var value = getBaseIntrinsic('%' + (parts.length > 0 ? parts[0] : '') + '%', allowMissing);
for (var i = 1; i < parts.length; i += 1) {
if (value != null) {
if ($gOPD && (i + 1) >= parts.length) {
var desc = $gOPD(value, parts[i]);
if (!allowMissing && !(parts[i] in value)) {
throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.');
}
value = desc ? (desc.get || desc.value) : value[parts[i]];
} else {
value = value[parts[i]];
}
}
}
return value;
};
var $Function = GetIntrinsic('%Function%');
var $apply = $Function.apply;
var $call = $Function.call;
var callBind = function callBind() {
return functionBind.apply($call, arguments);
};
var apply = function applyBind() {
return functionBind.apply($apply, arguments);
};
callBind.apply = apply;
var $Object = Object;
var $TypeError$1 = TypeError;
var implementation$2 = function flags() {
if (this != null && this !== $Object(this)) {
throw new $TypeError$1('RegExp.prototype.flags getter called on non-object');
}
var result = '';
if (this.global) {
result += 'g';
}
if (this.ignoreCase) {
result += 'i';
}
if (this.multiline) {
result += 'm';
}
if (this.dotAll) {
result += 's';
}
if (this.unicode) {
result += 'u';
}
if (this.sticky) {
result += 'y';
}
return result;
};
var supportsDescriptors$1 = defineProperties_1.supportsDescriptors;
var $gOPD$1 = Object.getOwnPropertyDescriptor;
var $TypeError$2 = TypeError;
var polyfill = function getPolyfill() {
if (!supportsDescriptors$1) {
throw new $TypeError$2('RegExp.prototype.flags requires a true ES5 environment that supports property descriptors');
}
if ((/a/mig).flags === 'gim') {
var descriptor = $gOPD$1(RegExp.prototype, 'flags');
if (descriptor && typeof descriptor.get === 'function' && typeof (/a/).dotAll === 'boolean') {
return descriptor.get;
}
}
return implementation$2;
};
var supportsDescriptors$2 = defineProperties_1.supportsDescriptors;
var gOPD$1 = Object.getOwnPropertyDescriptor;
var defineProperty$2 = Object.defineProperty;
var TypeErr = TypeError;
var getProto$1 = Object.getPrototypeOf;
var regex = /a/;
var shim = function shimFlags() {
if (!supportsDescriptors$2 || !getProto$1) {
throw new TypeErr('RegExp.prototype.flags requires a true ES5 environment that supports property descriptors');
}
var polyfill$1 = polyfill();
var proto = getProto$1(regex);
var descriptor = gOPD$1(proto, 'flags');
if (!descriptor || descriptor.get !== polyfill$1) {
defineProperty$2(proto, 'flags', {
configurable: true,
enumerable: false,
get: polyfill$1
});
}
return polyfill$1;
};
var flagsBound = callBind(implementation$2);
defineProperties_1(flagsBound, {
getPolyfill: polyfill,
implementation: implementation$2,
shim: shim
});
var regexp_prototype_flags = flagsBound;
var getDay = Date.prototype.getDay;
var tryDateObject = function tryDateGetDayCall(value) {
try {
getDay.call(value);
return true;
} catch (e) {
return false;
}
};
var toStr$6 = Object.prototype.toString;
var dateClass = '[object Date]';
var hasToStringTag$2 = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol';
var isDateObject = function isDateObject(value) {
if (typeof value !== 'object' || value === null) {
return false;
}
return hasToStringTag$2 ? tryDateObject(value) : toStr$6.call(value) === dateClass;
};
var getTime = Date.prototype.getTime;
function deepEqual(actual, expected, options) {
var opts = options || {};
// 7.1. All identical values are equivalent, as determined by ===.
if (opts.strict ? objectIs(actual, expected) : actual === expected) {
return true;
}
// 7.3. Other pairs that do not both pass typeof value == 'object', equivalence is determined by ==.
if (!actual || !expected || (typeof actual !== 'object' && typeof expected !== 'object')) {
return opts.strict ? objectIs(actual, expected) : actual == expected;
}
/*
* 7.4. For all other Object pairs, including Array objects, equivalence is
* determined by having the same number of owned properties (as verified
* with Object.prototype.hasOwnProperty.call), the same set of keys
* (although not necessarily the same order), equivalent values for every
* corresponding key, and an identical 'prototype' property. Note: this
* accounts for both named and indexed properties on Arrays.
*/
// eslint-disable-next-line no-use-before-define
return objEquiv(actual, expected, opts);
}
function isUndefinedOrNull(value) {
return value === null || value === undefined;
}
function isBuffer(x) {
if (!x || typeof x !== 'object' || typeof x.length !== 'number') {
return false;
}
if (typeof x.copy !== 'function' || typeof x.slice !== 'function') {
return false;
}
if (x.length > 0 && typeof x[0] !== 'number') {
return false;
}
return true;
}
function objEquiv(a, b, opts) {
/* eslint max-statements: [2, 50] */
var i, key;
if (typeof a !== typeof b) { return false; }
if (isUndefinedOrNull(a) || isUndefinedOrNull(b)) { return false; }
// an identical 'prototype' property.
if (a.prototype !== b.prototype) { return false; }
if (isArguments$1(a) !== isArguments$1(b)) { return false; }
var aIsRegex = isRegex(a);
var bIsRegex = isRegex(b);
if (aIsRegex !== bIsRegex) { return false; }
if (aIsRegex || bIsRegex) {
return a.source === b.source && regexp_prototype_flags(a) === regexp_prototype_flags(b);
}
if (isDateObject(a) && isDateObject(b)) {
return getTime.call(a) === getTime.call(b);
}
var aIsBuffer = isBuffer(a);
var bIsBuffer = isBuffer(b);
if (aIsBuffer !== bIsBuffer) { return false; }
if (aIsBuffer || bIsBuffer) { // && would work too, because both are true or both false here
if (a.length !== b.length) { return false; }
for (i = 0; i < a.length; i++) {
if (a[i] !== b[i]) { return false; }
}
return true;
}
if (typeof a !== typeof b) { return false; }
try {
var ka = objectKeys(a);
var kb = objectKeys(b);
} catch (e) { // happens when one is a string literal and the other isn't
return false;
}
// having the same number of owned properties (keys incorporates hasOwnProperty)
if (ka.length !== kb.length) { return false; }
// the same set of keys (although not necessarily the same order),
ka.sort();
kb.sort();
// ~~~cheap key test
for (i = ka.length - 1; i >= 0; i--) {
if (ka[i] != kb[i]) { return false; }
}
// equivalent values for every corresponding key, and ~~~possibly expensive deep test
for (i = ka.length - 1; i >= 0; i--) {
key = ka[i];
if (!deepEqual(a[key], b[key], opts)) { return false; }
}
return true;
}
var deepEqual_1 = deepEqual;
/**!
* @fileOverview Kickass library to create and place poppers near their reference elements.
* @version 1.16.1
* @license
* Copyright (c) 2016 Federico Zivolo and 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.
*/
var isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined' && typeof navigator !== 'undefined';
var timeoutDuration = function () {
var longerTimeoutBrowsers = ['Edge', 'Trident', 'Firefox'];
for (var i = 0; i < longerTimeoutBrowsers.length; i += 1) {
if (isBrowser && navigator.userAgent.indexOf(longerTimeoutBrowsers[i]) >= 0) {
return 1;
}
}
return 0;
}();
function microtaskDebounce(fn) {
var called = false;
return function () {
if (called) {
return;
}
called = true;
window.Promise.resolve().then(function () {
called = false;
fn();
});
};
}
function taskDebounce(fn) {
var scheduled = false;
return function () {
if (!scheduled) {
scheduled = true;
setTimeout(function () {
scheduled = false;
fn();
}, timeoutDuration);
}
};
}
var supportsMicroTasks = isBrowser && window.Promise;
/**
* Create a debounced version of a method, that's asynchronously deferred
* but called in the minimum time possible.
*
* @method
* @memberof Popper.Utils
* @argument {Function} fn
* @returns {Function}
*/
var debounce$1 = supportsMicroTasks ? microtaskDebounce : taskDebounce;
/**
* Check if the given variable is a function
* @method
* @memberof Popper.Utils
* @argument {Any} functionToCheck - variable to check
* @returns {Boolean} answer to: is a function?
*/
function isFunction$2(functionToCheck) {
var getType = {};
return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
}
/**
* Get CSS computed property of the given element
* @method
* @memberof Popper.Utils
* @argument {Eement} element
* @argument {String} property
*/
function getStyleComputedProperty(element, property) {
if (element.nodeType !== 1) {
return [];
}
// NOTE: 1 DOM access here
var window = element.ownerDocument.defaultView;
var css = window.getComputedStyle(element, null);
return property ? css[property] : css;
}
/**
* Returns the parentNode or the host of the element
* @method
* @memberof Popper.Utils
* @argument {Element} element
* @returns {Element} parent
*/
function getParentNode(element) {
if (element.nodeName === 'HTML') {
return element;
}
return element.parentNode || element.host;
}
/**
* Returns the scrolling parent of the given element
* @method
* @memberof Popper.Utils
* @argument {Element} element
* @returns {Element} scroll parent
*/
function getScrollParent(element) {
// Return body, `getScroll` will take care to get the correct `scrollTop` from it
if (!element) {
return document.body;
}
switch (element.nodeName) {
case 'HTML':
case 'BODY':
return element.ownerDocument.body;
case '#document':
return element.body;
}
// Firefox want us to check `-x` and `-y` variations as well
var _getStyleComputedProp = getStyleComputedProperty(element),
overflow = _getStyleComputedProp.overflow,
overflowX = _getStyleComputedProp.overflowX,
overflowY = _getStyleComputedProp.overflowY;
if (/(auto|scroll|overlay)/.test(overflow + overflowY + overflowX)) {
return element;
}
return getScrollParent(getParentNode(element));
}
/**
* Returns the reference node of the reference object, or the reference object itself.
* @method
* @memberof Popper.Utils
* @param {Element|Object} reference - the reference element (the popper will be relative to this)
* @returns {Element} parent
*/
function getReferenceNode(reference) {
return reference && reference.referenceNode ? reference.referenceNode : reference;
}
var isIE11 = isBrowser && !!(window.MSInputMethodContext && document.documentMode);
var isIE10 = isBrowser && /MSIE 10/.test(navigator.userAgent);
/**
* Determines if the browser is Internet Explorer
* @method
* @memberof Popper.Utils
* @param {Number} version to check
* @returns {Boolean} isIE
*/
function isIE(version) {
if (version === 11) {
return isIE11;
}
if (version === 10) {
return isIE10;
}
return isIE11 || isIE10;
}
/**
* Returns the offset parent of the given element
* @method
* @memberof Popper.Utils
* @argument {Element} element
* @returns {Element} offset parent
*/
function getOffsetParent(element) {
if (!element) {
return document.documentElement;
}
var noOffsetParent = isIE(10) ? document.body : null;
// NOTE: 1 DOM access here
var offsetParent = element.offsetParent || null;
// Skip hidden elements which don't have an offsetParent
while (offsetParent === noOffsetParent && element.nextElementSibling) {
offsetParent = (element = element.nextElementSibling).offsetParent;
}
var nodeName = offsetParent && offsetParent.nodeName;
if (!nodeName || nodeName === 'BODY' || nodeName === 'HTML') {
return element ? element.ownerDocument.documentElement : document.documentElement;
}
// .offsetParent will return the closest TH, TD or TABLE in case
// no offsetParent is present, I hate this job...
if (['TH', 'TD', 'TABLE'].indexOf(offsetParent.nodeName) !== -1 && getStyleComputedProperty(offsetParent, 'position') === 'static') {
return getOffsetParent(offsetParent);
}
return offsetParent;
}
function isOffsetContainer(element) {
var nodeName = element.nodeName;
if (nodeName === 'BODY') {
return false;
}
return nodeName === 'HTML' || getOffsetParent(element.firstElementChild) === element;
}
/**
* Finds the root node (document, shadowDOM root) of the given element
* @method
* @memberof Popper.Utils
* @argument {Element} node
* @returns {Element} root node
*/
function getRoot(node) {
if (node.parentNode !== null) {
return getRoot(node.parentNode);
}
return node;
}
/**
* Finds the offset parent common to the two provided nodes
* @method
* @memberof Popper.Utils
* @argument {Element} element1
* @argument {Element} element2
* @returns {Element} common offset parent
*/
function findCommonOffsetParent(element1, element2) {
// This check is needed to avoid errors in case one of the elements isn't defined for any reason
if (!element1 || !element1.nodeType || !element2 || !element2.nodeType) {
return document.documentElement;
}
// Here we make sure to give as "start" the element that comes first in the DOM
var order = element1.compareDocumentPosition(element2) & Node.DOCUMENT_POSITION_FOLLOWING;
var start = order ? element1 : element2;
var end = order ? element2 : element1;
// Get common ancestor container
var range = document.createRange();
range.setStart(start, 0);
range.setEnd(end, 0);
var commonAncestorContainer = range.commonAncestorContainer;
// Both nodes are inside #document
if (element1 !== commonAncestorContainer && element2 !== commonAncestorContainer || start.contains(end)) {
if (isOffsetContainer(commonAncestorContainer)) {
return commonAncestorContainer;
}
return getOffsetParent(commonAncestorContainer);
}
// one of the nodes is inside shadowDOM, find which one
var element1root = getRoot(element1);
if (element1root.host) {
return findCommonOffsetParent(element1root.host, element2);
} else {
return findCommonOffsetParent(element1, getRoot(element2).host);
}
}
/**
* Gets the scroll value of the given element in the given side (top and left)
* @method
* @memberof Popper.Utils
* @argument {Element} element
* @argument {String} side `top` or `left`
* @returns {number} amount of scrolled pixels
*/
function getScroll(element) {
var side = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'top';
var upperSide = side === 'top' ? 'scrollTop' : 'scrollLeft';
var nodeName = element.nodeName;
if (nodeName === 'BODY' || nodeName === 'HTML') {
var html = element.ownerDocument.documentElement;
var scrollingElement = element.ownerDocument.scrollingElement || html;
return scrollingElement[upperSide];
}
return element[upperSide];
}
/*
* Sum or subtract the element scroll values (left and top) from a given rect object
* @method
* @memberof Popper.Utils
* @param {Object} rect - Rect object you want to change
* @param {HTMLElement} element - The element from the function reads the scroll values
* @param {Boolean} subtract - set to true if you want to subtract the scroll values
* @return {Object} rect - The modifier rect object
*/
function includeScroll(rect, element) {
var subtract = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
var scrollTop = getScroll(element, 'top');
var scrollLeft = getScroll(element, 'left');
var modifier = subtract ? -1 : 1;
rect.top += scrollTop * modifier;
rect.bottom += scrollTop * modifier;
rect.left += scrollLeft * modifier;
rect.right += scrollLeft * modifier;
return rect;
}
/*
* Helper to detect borders of a given element
* @method
* @memberof Popper.Utils
* @param {CSSStyleDeclaration} styles
* Result of `getStyleComputedProperty` on the given element
* @param {String} axis - `x` or `y`
* @return {number} borders - The borders size of the given axis
*/
function getBordersSize(styles, axis) {
var sideA = axis === 'x' ? 'Left' : 'Top';
var sideB = sideA === 'Left' ? 'Right' : 'Bottom';
return parseFloat(styles['border' + sideA + 'Width']) + parseFloat(styles['border' + sideB + 'Width']);
}
function getSize(axis, body, html, computedStyle) {
return Math.max(body['offset' + axis], body['scroll' + axis], html['client' + axis], html['offset' + axis], html['scroll' + axis], isIE(10) ? parseInt(html['offset' + axis]) + parseInt(computedStyle['margin' + (axis === 'Height' ? 'Top' : 'Left')]) + parseInt(computedStyle['margin' + (axis === 'Height' ? 'Bottom' : 'Right')]) : 0);
}
function getWindowSizes(document) {
var body = document.body;
var html = document.documentElement;
var computedStyle = isIE(10) && getComputedStyle(html);
return {
height: getSize('Height', body, html, computedStyle),
width: getSize('Width', body, html, computedStyle)
};
}
var classCallCheck = function (instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
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 defineProperty$3 = function (obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
};
var _extends$1 = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
/**
* Given element offsets, generate an output similar to getBoundingClientRect
* @method
* @memberof Popper.Utils
* @argument {Object} offsets
* @returns {Object} ClientRect like output
*/
function getClientRect(offsets) {
return _extends$1({}, offsets, {
right: offsets.left + offsets.width,
bottom: offsets.top + offsets.height
});
}
/**
* Get bounding client rect of given element
* @method
* @memberof Popper.Utils
* @param {HTMLElement} element
* @return {Object} client rect
*/
function getBoundingClientRect(element) {
var rect = {};
// IE10 10 FIX: Please, don't ask, the element isn't
// considered in DOM in some circumstances...
// This isn't reproducible in IE10 compatibility mode of IE11
try {
if (isIE(10)) {
rect = element.getBoundingClientRect();
var scrollTop = getScroll(element, 'top');
var scrollLeft = getScroll(element, 'left');
rect.top += scrollTop;
rect.left += scrollLeft;
rect.bottom += scrollTop;
rect.right += scrollLeft;
} else {
rect = element.getBoundingClientRect();
}
} catch (e) {}
var result = {
left: rect.left,
top: rect.top,
width: rect.right - rect.left,
height: rect.bottom - rect.top
};
// subtract scrollbar size from sizes
var sizes = element.nodeName === 'HTML' ? getWindowSizes(element.ownerDocument) : {};
var width = sizes.width || element.clientWidth || result.width;
var height = sizes.height || element.clientHeight || result.height;
var horizScrollbar = element.offsetWidth - width;
var vertScrollbar = element.offsetHeight - height;
// if an hypothetical scrollbar is detected, we must be sure it's not a `border`
// we make this check conditional for performance reasons
if (horizScrollbar || vertScrollbar) {
var styles = getStyleComputedProperty(element);
horizScrollbar -= getBordersSize(styles, 'x');
vertScrollbar -= getBordersSize(styles, 'y');
result.width -= horizScrollbar;
result.height -= vertScrollbar;
}
return getClientRect(result);
}
function getOffsetRectRelativeToArbitraryNode(children, parent) {
var fixedPosition = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
var isIE10 = isIE(10);
var isHTML = parent.nodeName === 'HTML';
var childrenRect = getBoundingClientRect(children);
var parentRect = getBoundingClientRect(parent);
var scrollParent = getScrollParent(children);
var styles = getStyleComputedProperty(parent);
var borderTopWidth = parseFloat(styles.borderTopWidth);
var borderLeftWidth = parseFloat(styles.borderLeftWidth);
// In cases where the parent is fixed, we must ignore negative scroll in offset calc
if (fixedPosition && isHTML) {
parentRect.top = Math.max(parentRect.top, 0);
parentRect.left = Math.max(parentRect.left, 0);
}
var offsets = getClientRect({
top: childrenRect.top - parentRect.top - borderTopWidth,
left: childrenRect.left - parentRect.left - borderLeftWidth,
width: childrenRect.width,
height: childrenRect.height
});
offsets.marginTop = 0;
offsets.marginLeft = 0;
// Subtract margins of documentElement in case it's being used as parent
// we do this only on HTML because it's the only element that behaves
// differently when margins are applied to it. The margins are included in
// the box of the documentElement, in the other cases not.
if (!isIE10 && isHTML) {
var marginTop = parseFloat(styles.marginTop);
var marginLeft = parseFloat(styles.marginLeft);
offsets.top -= borderTopWidth - marginTop;
offsets.bottom -= borderTopWidth - marginTop;
offsets.left -= borderLeftWidth - marginLeft;
offsets.right -= borderLeftWidth - marginLeft;
// Attach marginTop and marginLeft because in some circumstances we may need them
offsets.marginTop = marginTop;
offsets.marginLeft = marginLeft;
}
if (isIE10 && !fixedPosition ? parent.contains(scrollParent) : parent === scrollParent && scrollParent.nodeName !== 'BODY') {
offsets = includeScroll(offsets, parent);
}
return offsets;
}
function getViewportOffsetRectRelativeToArtbitraryNode(element) {
var excludeScroll = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
var html = element.ownerDocument.documentElement;
var relativeOffset = getOffsetRectRelativeToArbitraryNode(element, html);
var width = Math.max(html.clientWidth, window.innerWidth || 0);
var height = Math.max(html.clientHeight, window.innerHeight || 0);
var scrollTop = !excludeScroll ? getScroll(html) : 0;
var scrollLeft = !excludeScroll ? getScroll(html, 'left') : 0;
var offset = {
top: scrollTop - relativeOffset.top + relativeOffset.marginTop,
left: scrollLeft - relativeOffset.left + relativeOffset.marginLeft,
width: width,
height: height
};
return getClientRect(offset);
}
/**
* Check if the given element is fixed or is inside a fixed parent
* @method
* @memberof Popper.Utils
* @argument {Element} element
* @argument {Element} customContainer
* @returns {Boolean} answer to "isFixed?"
*/
function isFixed(element) {
var nodeName = element.nodeName;
if (nodeName === 'BODY' || nodeName === 'HTML') {
return false;
}
if (getStyleComputedProperty(element, 'position') === 'fixed') {
return true;
}
var parentNode = getParentNode(element);
if (!parentNode) {
return false;
}
return isFixed(parentNode);
}
/**
* Finds the first parent of an element that has a transformed property defined
* @method
* @memberof Popper.Utils
* @argument {Element} element
* @returns {Element} first transformed parent or documentElement
*/
function getFixedPositionOffsetParent(element) {
// This check is needed to avoid errors in case one of the elements isn't defined for any reason
if (!element || !element.parentElement || isIE()) {
return document.documentElement;
}
var el = element.parentElement;
while (el && getStyleComputedProperty(el, 'transform') === 'none') {
el = el.parentElement;
}
return el || document.documentElement;
}
/**
* Computed the boundaries limits and return them
* @method
* @memberof Popper.Utils
* @param {HTMLElement} popper
* @param {HTMLElement} reference
* @param {number} padding
* @param {HTMLElement} boundariesElement - Element used to define the boundaries
* @param {Boolean} fixedPosition - Is in fixed position mode
* @returns {Object} Coordinates of the boundaries
*/
function getBoundaries(popper, reference, padding, boundariesElement) {
var fixedPosition = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false;
// NOTE: 1 DOM access here
var boundaries = { top: 0, left: 0 };
var offsetParent = fixedPosition ? getFixedPositionOffsetParent(popper) : findCommonOffsetParent(popper, getReferenceNode(reference));
// Handle viewport case
if (boundariesElement === 'viewport') {
boundaries = getViewportOffsetRectRelativeToArtbitraryNode(offsetParent, fixedPosition);
} else {
// Handle other cases based on DOM element used as boundaries
var boundariesNode = void 0;
if (boundariesElement === 'scrollParent') {
boundariesNode = getScrollParent(getParentNode(reference));
if (boundariesNode.nodeName === 'BODY') {
boundariesNode = popper.ownerDocument.documentElement;
}
} else if (boundariesElement === 'window') {
boundariesNode = popper.ownerDocument.documentElement;
} else {
boundariesNode = boundariesElement;
}
var offsets = getOffsetRectRelativeToArbitraryNode(boundariesNode, offsetParent, fixedPosition);
// In case of HTML, we need a different computation
if (boundariesNode.nodeName === 'HTML' && !isFixed(offsetParent)) {
var _getWindowSizes = getWindowSizes(popper.ownerDocument),
height = _getWindowSizes.height,
width = _getWindowSizes.width;
boundaries.top += offsets.top - offsets.marginTop;
boundaries.bottom = height + offsets.top;
boundaries.left += offsets.left - offsets.marginLeft;
boundaries.right = width + offsets.left;
} else {
// for all the other DOM elements, this one is good
boundaries = offsets;
}
}
// Add paddings
padding = padding || 0;
var isPaddingNumber = typeof padding === 'number';
boundaries.left += isPaddingNumber ? padding : padding.left || 0;
boundaries.top += isPaddingNumber ? padding : padding.top || 0;
boundaries.right -= isPaddingNumber ? padding : padding.right || 0;
boundaries.bottom -= isPaddingNumber ? padding : padding.bottom || 0;
return boundaries;
}
function getArea(_ref) {
var width = _ref.width,
height = _ref.height;
return width * height;
}
/**
* Utility used to transform the `auto` placement to the placement with more
* available space.
* @method
* @memberof Popper.Utils
* @argument {Object} data - The data object generated by update method
* @argument {Object} options - Modifiers configuration and options
* @returns {Object} The data object, properly modified
*/
function computeAutoPlacement(placement, refRect, popper, reference, boundariesElement) {
var padding = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 0;
if (placement.indexOf('auto') === -1) {
return placement;
}
var boundaries = getBoundaries(popper, reference, padding, boundariesElement);
var rects = {
top: {
width: boundaries.width,
height: refRect.top - boundaries.top
},
right: {
width: boundaries.right - refRect.right,
height: boundaries.height
},
bottom: {
width: boundaries.width,
height: boundaries.bottom - refRect.bottom
},
left: {
width: refRect.left - boundaries.left,
height: boundaries.height
}
};
var sortedAreas = Object.keys(rects).map(function (key) {
return _extends$1({
key: key
}, rects[key], {
area: getArea(rects[key])
});
}).sort(function (a, b) {
return b.area - a.area;
});
var filteredAreas = sortedAreas.filter(function (_ref2) {
var width = _ref2.width,
height = _ref2.height;
return width >= popper.clientWidth && height >= popper.clientHeight;
});
var computedPlacement = filteredAreas.length > 0 ? filteredAreas[0].key : sortedAreas[0].key;
var variation = placement.split('-')[1];
return computedPlacement + (variation ? '-' + variation : '');
}
/**
* Get offsets to the reference element
* @method
* @memberof Popper.Utils
* @param {Object} state
* @param {Element} popper - the popper element
* @param {Element} reference - the reference element (the popper will be relative to this)
* @param {Element} fixedPosition - is in fixed position mode
* @returns {Object} An object containing the offsets which will be applied to the popper
*/
function getReferenceOffsets(state, popper, reference) {
var fixedPosition = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
var commonOffsetParent = fixedPosition ? getFixedPositionOffsetParent(popper) : findCommonOffsetParent(popper, getReferenceNode(reference));
return getOffsetRectRelativeToArbitraryNode(reference, commonOffsetParent, fixedPosition);
}
/**
* Get the outer sizes of the given element (offset size + margins)
* @method
* @memberof Popper.Utils
* @argument {Element} element
* @returns {Object} object containing width and height properties
*/
function getOuterSizes(element) {
var window = element.ownerDocument.defaultView;
var styles = window.getComputedStyle(element);
var x = parseFloat(styles.marginTop || 0) + parseFloat(styles.marginBottom || 0);
var y = parseFloat(styles.marginLeft || 0) + parseFloat(styles.marginRight || 0);
var result = {
width: element.offsetWidth + y,
height: element.offsetHeight + x
};
return result;
}
/**
* Get the opposite placement of the given one
* @method
* @memberof Popper.Utils
* @argument {String} placement
* @returns {String} flipped placement
*/
function getOppositePlacement(placement) {
var hash = { left: 'right', right: 'left', bottom: 'top', top: 'bottom' };
return placement.replace(/left|right|bottom|top/g, function (matched) {
return hash[matched];
});
}
/**
* Get offsets to the popper
* @method
* @memberof Popper.Utils
* @param {Object} position - CSS position the Popper will get applied
* @param {HTMLElement} popper - the popper element
* @param {Object} referenceOffsets - the reference offsets (the popper will be relative to this)
* @param {String} placement - one of the valid placement options
* @returns {Object} popperOffsets - An object containing the offsets which will be applied to the popper
*/
function getPopperOffsets(popper, referenceOffsets, placement) {
placement = placement.split('-')[0];
// Get popper node sizes
var popperRect = getOuterSizes(popper);
// Add position, width and height to our offsets object
var popperOffsets = {
width: popperRect.width,
height: popperRect.height
};
// depending by the popper placement we have to compute its offsets slightly differently
var isHoriz = ['right', 'left'].indexOf(placement) !== -1;
var mainSide = isHoriz ? 'top' : 'left';
var secondarySide = isHoriz ? 'left' : 'top';
var measurement = isHoriz ? 'height' : 'width';
var secondaryMeasurement = !isHoriz ? 'height' : 'width';
popperOffsets[mainSide] = referenceOffsets[mainSide] + referenceOffsets[measurement] / 2 - popperRect[measurement] / 2;
if (placement === secondarySide) {
popperOffsets[secondarySide] = referenceOffsets[secondarySide] - popperRect[secondaryMeasurement];
} else {
popperOffsets[secondarySide] = referenceOffsets[getOppositePlacement(secondarySide)];
}
return popperOffsets;
}
/**
* Mimics the `find` method of Array
* @method
* @memberof Popper.Utils
* @argument {Array} arr
* @argument prop
* @argument value
* @returns index or -1
*/
function find(arr, check) {
// use native find if supported
if (Array.prototype.find) {
return arr.find(check);
}
// use `filter` to obtain the same behavior of `find`
return arr.filter(check)[0];
}
/**
* Return the index of the matching object
* @method
* @memberof Popper.Utils
* @argument {Array} arr
* @argument prop
* @argument value
* @returns index or -1
*/
function findIndex(arr, prop, value) {
// use native findIndex if supported
if (Array.prototype.findIndex) {
return arr.findIndex(function (cur) {
return cur[prop] === value;
});
}
// use `find` + `indexOf` if `findIndex` isn't supported
var match = find(arr, function (obj) {
return obj[prop] === value;
});
return arr.indexOf(match);
}
/**
* Loop trough the list of modifiers and run them in order,
* each of them will then edit the data object.
* @method
* @memberof Popper.Utils
* @param {dataObject} data
* @param {Array} modifiers
* @param {String} ends - Optional modifier name used as stopper
* @returns {dataObject}
*/
function runModifiers(modifiers, data, ends) {
var modifiersToRun = ends === undefined ? modifiers : modifiers.slice(0, findIndex(modifiers, 'name', ends));
modifiersToRun.forEach(function (modifier) {
if (modifier['function']) {
// eslint-disable-line dot-notation
console.warn('`modifier.function` is deprecated, use `modifier.fn`!');
}
var fn = modifier['function'] || modifier.fn; // eslint-disable-line dot-notation
if (modifier.enabled && isFunction$2(fn)) {
// Add properties to offsets to make them a complete clientRect object
// we do this before each modifier to make sure the previous one doesn't
// mess with these values
data.offsets.popper = getClientRect(data.offsets.popper);
data.offsets.reference = getClientRect(data.offsets.reference);
data = fn(data, modifier);
}
});
return data;
}
/**
* Updates the position of the popper, computing the new offsets and applying
* the new style.<br />
* Prefer `scheduleUpdate` over `update` because of performance reasons.
* @method
* @memberof Popper
*/
function update() {
// if popper is destroyed, don't perform any further update
if (this.state.isDestroyed) {
return;
}
var data = {
instance: this,
styles: {},
arrowStyles: {},
attributes: {},
flipped: false,
offsets: {}
};
// compute reference element offsets
data.offsets.reference = getReferenceOffsets(this.state, this.popper, this.reference, this.options.positionFixed);
// compute auto placement, store placement inside the data object,
// modifiers will be able to edit `placement` if needed
// and refer to originalPlacement to know the original value
data.placement = computeAutoPlacement(this.options.placement, data.offsets.reference, this.popper, this.reference, this.options.modifiers.flip.boundariesElement, this.options.modifiers.flip.padding);
// store the computed placement inside `originalPlacement`
data.originalPlacement = data.placement;
data.positionFixed = this.options.positionFixed;
// compute the popper offsets
data.offsets.popper = getPopperOffsets(this.popper, data.offsets.reference, data.placement);
data.offsets.popper.position = this.options.positionFixed ? 'fixed' : 'absolute';
// run the modifiers
data = runModifiers(this.modifiers, data);
// the first `update` will call `onCreate` callback
// the other ones will call `onUpdate` callback
if (!this.state.isCreated) {
this.state.isCreated = true;
this.options.onCreate(data);
} else {
this.options.onUpdate(data);
}
}
/**
* Helper used to know if the given modifier is enabled.
* @method
* @memberof Popper.Utils
* @returns {Boolean}
*/
function isModifierEnabled(modifiers, modifierName) {
return modifiers.some(function (_ref) {
var name = _ref.name,
enabled = _ref.enabled;
return enabled && name === modifierName;
});
}
/**
* Get the prefixed supported property name
* @method
* @memberof Popper.Utils
* @argument {String} property (camelCase)
* @returns {String} prefixed property (camelCase or PascalCase, depending on the vendor prefix)
*/
function getSupportedPropertyName(property) {
var prefixes = [false, 'ms', 'Webkit', 'Moz', 'O'];
var upperProp = property.charAt(0).toUpperCase() + property.slice(1);
for (var i = 0; i < prefixes.length; i++) {
var prefix = prefixes[i];
var toCheck = prefix ? '' + prefix + upperProp : property;
if (typeof document.body.style[toCheck] !== 'undefined') {
return toCheck;
}
}
return null;
}
/**
* Destroys the popper.
* @method
* @memberof Popper
*/
function destroy() {
this.state.isDestroyed = true;
// touch DOM only if `applyStyle` modifier is enabled
if (isModifierEnabled(this.modifiers, 'applyStyle')) {
this.popper.removeAttribute('x-placement');
this.popper.style.position = '';
this.popper.style.top = '';
this.popper.style.left = '';
this.popper.style.right = '';
this.popper.style.bottom = '';
this.popper.style.willChange = '';
this.popper.style[getSupportedPropertyName('transform')] = '';
}
this.disableEventListeners();
// remove the popper if user explicitly asked for the deletion on destroy
// do not use `remove` because IE11 doesn't support it
if (this.options.removeOnDestroy) {
this.popper.parentNode.removeChild(this.popper);
}
return this;
}
/**
* Get the window associated with the element
* @argument {Element} element
* @returns {Window}
*/
function getWindow(element) {
var ownerDocument = element.ownerDocument;
return ownerDocument ? ownerDocument.defaultView : window;
}
function attachToScrollParents(scrollParent, event, callback, scrollParents) {
var isBody = scrollParent.nodeName === 'BODY';
var target = isBody ? scrollParent.ownerDocument.defaultView : scrollParent;
target.addEventListener(event, callback, { passive: true });
if (!isBody) {
attachToScrollParents(getScrollParent(target.parentNode), event, callback, scrollParents);
}
scrollParents.push(target);
}
/**
* Setup needed event listeners used to update the popper position
* @method
* @memberof Popper.Utils
* @private
*/
function setupEventListeners(reference, options, state, updateBound) {
// Resize event listener on window
state.updateBound = updateBound;
getWindow(reference).addEventListener('resize', state.updateBound, { passive: true });
// Scroll event listener on scroll parents
var scrollElement = getScrollParent(reference);
attachToScrollParents(scrollElement, 'scroll', state.updateBound, state.scrollParents);
state.scrollElement = scrollElement;
state.eventsEnabled = true;
return state;
}
/**
* It will add resize/scroll events and start recalculating
* position of the popper element when they are triggered.
* @method
* @memberof Popper
*/
function enableEventListeners() {
if (!this.state.eventsEnabled) {
this.state = setupEventListeners(this.reference, this.options, this.state, this.scheduleUpdate);
}
}
/**
* Remove event listeners used to update the popper position
* @method
* @memberof Popper.Utils
* @private
*/
function removeEventListeners(reference, state) {
// Remove resize event listener on window
getWindow(reference).removeEventListener('resize', state.updateBound);
// Remove scroll event listener on scroll parents
state.scrollParents.forEach(function (target) {
target.removeEventListener('scroll', state.updateBound);
});
// Reset state
state.updateBound = null;
state.scrollParents = [];
state.scrollElement = null;
state.eventsEnabled = false;
return state;
}
/**
* It will remove resize/scroll events and won't recalculate popper position
* when they are triggered. It also won't trigger `onUpdate` callback anymore,
* unless you call `update` method manually.
* @method
* @memberof Popper
*/
function disableEventListeners() {
if (this.state.eventsEnabled) {
cancelAnimationFrame(this.scheduleUpdate);
this.state = removeEventListeners(this.reference, this.state);
}
}
/**
* Tells if a given input is a number
* @method
* @memberof Popper.Utils
* @param {*} input to check
* @return {Boolean}
*/
function isNumeric(n) {
return n !== '' && !isNaN(parseFloat(n)) && isFinite(n);
}
/**
* Set the style to the given popper
* @method
* @memberof Popper.Utils
* @argument {Element} element - Element to apply the style to
* @argument {Object} styles
* Object with a list of properties and values which will be applied to the element
*/
function setStyles(element, styles) {
Object.keys(styles).forEach(function (prop) {
var unit = '';
// add unit if the value is numeric and is one of the following
if (['width', 'height', 'top', 'right', 'bottom', 'left'].indexOf(prop) !== -1 && isNumeric(styles[prop])) {
unit = 'px';
}
element.style[prop] = styles[prop] + unit;
});
}
/**
* Set the attributes to the given popper
* @method
* @memberof Popper.Utils
* @argument {Element} element - Element to apply the attributes to
* @argument {Object} styles
* Object with a list of properties and values which will be applied to the element
*/
function setAttributes(element, attributes) {
Object.keys(attributes).forEach(function (prop) {
var value = attributes[prop];
if (value !== false) {
element.setAttribute(prop, attributes[prop]);
} else {
element.removeAttribute(prop);
}
});
}
/**
* @function
* @memberof Modifiers
* @argument {Object} data - The data object generated by `update` method
* @argument {Object} data.styles - List of style properties - values to apply to popper element
* @argument {Object} data.attributes - List of attribute properties - values to apply to popper element
* @argument {Object} options - Modifiers configuration and options
* @returns {Object} The same data object
*/
function applyStyle(data) {
// any property present in `data.styles` will be applied to the popper,
// in this way we can make the 3rd party modifiers add custom styles to it
// Be aware, modifiers could override the properties defined in the previous
// lines of this modifier!
setStyles(data.instance.popper, data.styles);
// any property present in `data.attributes` will be applied to the popper,
// they will be set as HTML attributes of the element
setAttributes(data.instance.popper, data.attributes);
// if arrowElement is defined and arrowStyles has some properties
if (data.arrowElement && Object.keys(data.arrowStyles).length) {
setStyles(data.arrowElement, data.arrowStyles);
}
return data;
}
/**
* Set the x-placement attribute before everything else because it could be used
* to add margins to the popper margins needs to be calculated to get the
* correct popper offsets.
* @method
* @memberof Popper.modifiers
* @param {HTMLElement} reference - The reference element used to position the popper
* @param {HTMLElement} popper - The HTML element used as popper
* @param {Object} options - Popper.js options
*/
function applyStyleOnLoad(reference, popper, options, modifierOptions, state) {
// compute reference element offsets
var referenceOffsets = getReferenceOffsets(state, popper, reference, options.positionFixed);
// compute auto placement, store placement inside the data object,
// modifiers will be able to edit `placement` if needed
// and refer to originalPlacement to know the original value
var placement = computeAutoPlacement(options.placement, referenceOffsets, popper, reference, options.modifiers.flip.boundariesElement, options.modifiers.flip.padding);
popper.setAttribute('x-placement', placement);
// Apply `position` to popper before anything else because
// without the position applied we can't guarantee correct computations
setStyles(popper, { position: options.positionFixed ? 'fixed' : 'absolute' });
return options;
}
/**
* @function
* @memberof Popper.Utils
* @argument {Object} data - The data object generated by `update` method
* @argument {Boolean} shouldRound - If the offsets should be rounded at all
* @returns {Object} The popper's position offsets rounded
*
* The tale of pixel-perfect positioning. It's still not 100% perfect, but as
* good as it can be within reason.
* Discussion here: https://github.com/FezVrasta/popper.js/pull/715
*
* Low DPI screens cause a popper to be blurry if not using full pixels (Safari
* as well on High DPI screens).
*
* Firefox prefers no rounding for positioning and does not have blurriness on
* high DPI screens.
*
* Only horizontal placement and left/right values need to be considered.
*/
function getRoundedOffsets(data, shouldRound) {
var _data$offsets = data.offsets,
popper = _data$offsets.popper,
reference = _data$offsets.reference;
var round = Math.round,
floor = Math.floor;
var noRound = function noRound(v) {
return v;
};
var referenceWidth = round(reference.width);
var popperWidth = round(popper.width);
var isVertical = ['left', 'right'].indexOf(data.placement) !== -1;
var isVariation = data.placement.indexOf('-') !== -1;
var sameWidthParity = referenceWidth % 2 === popperWidth % 2;
var bothOddWidth = referenceWidth % 2 === 1 && popperWidth % 2 === 1;
var horizontalToInteger = !shouldRound ? noRound : isVertical || isVariation || sameWidthParity ? round : floor;
var verticalToInteger = !shouldRound ? noRound : round;
return {
left: horizontalToInteger(bothOddWidth && !isVariation && shouldRound ? popper.left - 1 : popper.left),
top: verticalToInteger(popper.top),
bottom: verticalToInteger(popper.bottom),
right: horizontalToInteger(popper.right)
};
}
var isFirefox = isBrowser && /Firefox/i.test(navigator.userAgent);
/**
* @function
* @memberof Modifiers
* @argument {Object} data - The data object generated by `update` method
* @argument {Object} options - Modifiers configuration and options
* @returns {Object} The data object, properly modified
*/
function computeStyle(data, options) {
var x = options.x,
y = options.y;
var popper = data.offsets.popper;
// Remove this legacy support in Popper.js v2
var legacyGpuAccelerationOption = find(data.instance.modifiers, function (modifier) {
return modifier.name === 'applyStyle';
}).gpuAcceleration;
if (legacyGpuAccelerationOption !== undefined) {
console.warn('WARNING: `gpuAcceleration` option moved to `computeStyle` modifier and will not be supported in future versions of Popper.js!');
}
var gpuAcceleration = legacyGpuAccelerationOption !== undefined ? legacyGpuAccelerationOption : options.gpuAcceleration;
var offsetParent = getOffsetParent(data.instance.popper);
var offsetParentRect = getBoundingClientRect(offsetParent);
// Styles
var styles = {
position: popper.position
};
var offsets = getRoundedOffsets(data, window.devicePixelRatio < 2 || !isFirefox);
var sideA = x === 'bottom' ? 'top' : 'bottom';
var sideB = y === 'right' ? 'left' : 'right';
// if gpuAcceleration is set to `true` and transform is supported,
// we use `translate3d` to apply the position to the popper we
// automatically use the supported prefixed version if needed
var prefixedProperty = getSupportedPropertyName('transform');
// now, let's make a step back and look at this code closely (wtf?)
// If the content of the popper grows once it's been positioned, it
// may happen that the popper gets misplaced because of the new content
// overflowing its reference element
// To avoid this problem, we provide two options (x and y), which allow
// the consumer to define the offset origin.
// If we position a popper on top of a reference element, we can set
// `x` to `top` to make the popper grow towards its top instead of
// its bottom.
var left = void 0,
top = void 0;
if (sideA === 'bottom') {
// when offsetParent is <html> the positioning is relative to the bottom of the screen (excluding the scrollbar)
// and not the bottom of the html element
if (offsetParent.nodeName === 'HTML') {
top = -offsetParent.clientHeight + offsets.bottom;
} else {
top = -offsetParentRect.height + offsets.bottom;
}
} else {
top = offsets.top;
}
if (sideB === 'right') {
if (offsetParent.nodeName === 'HTML') {
left = -offsetParent.clientWidth + offsets.right;
} else {
left = -offsetParentRect.width + offsets.right;
}
} else {
left = offsets.left;
}
if (gpuAcceleration && prefixedProperty) {
styles[prefixedProperty] = 'translate3d(' + left + 'px, ' + top + 'px, 0)';
styles[sideA] = 0;
styles[sideB] = 0;
styles.willChange = 'transform';
} else {
// othwerise, we use the standard `top`, `left`, `bottom` and `right` properties
var invertTop = sideA === 'bottom' ? -1 : 1;
var invertLeft = sideB === 'right' ? -1 : 1;
styles[sideA] = top * invertTop;
styles[sideB] = left * invertLeft;
styles.willChange = sideA + ', ' + sideB;
}
// Attributes
var attributes = {
'x-placement': data.placement
};
// Update `data` attributes, styles and arrowStyles
data.attributes = _extends$1({}, attributes, data.attributes);
data.styles = _extends$1({}, styles, data.styles);
data.arrowStyles = _extends$1({}, data.offsets.arrow, data.arrowStyles);
return data;
}
/**
* Helper used to know if the given modifier depends from another one.<br />
* It checks if the needed modifier is listed and enabled.
* @method
* @memberof Popper.Utils
* @param {Array} modifiers - list of modifiers
* @param {String} requestingName - name of requesting modifier
* @param {String} requestedName - name of requested modifier
* @returns {Boolean}
*/
function isModifierRequired(modifiers, requestingName, requestedName) {
var requesting = find(modifiers, function (_ref) {
var name = _ref.name;
return name === requestingName;
});
var isRequired = !!requesting && modifiers.some(function (modifier) {
return modifier.name === requestedName && modifier.enabled && modifier.order < requesting.order;
});
if (!isRequired) {
var _requesting = '`' + requestingName + '`';
var requested = '`' + requestedName + '`';
console.warn(requested + ' modifier is required by ' + _requesting + ' modifier in order to work, be sure to include it before ' + _requesting + '!');
}
return isRequired;
}
/**
* @function
* @memberof Modifiers
* @argument {Object} data - The data object generated by update method
* @argument {Object} options - Modifiers configuration and options
* @returns {Object} The data object, properly modified
*/
function arrow(data, options) {
var _data$offsets$arrow;
// arrow depends on keepTogether in order to work
if (!isModifierRequired(data.instance.modifiers, 'arrow', 'keepTogether')) {
return data;
}
var arrowElement = options.element;
// if arrowElement is a string, suppose it's a CSS selector
if (typeof arrowElement === 'string') {
arrowElement = data.instance.popper.querySelector(arrowElement);
// if arrowElement is not found, don't run the modifier
if (!arrowElement) {
return data;
}
} else {
// if the arrowElement isn't a query selector we must check that the
// provided DOM node is child of its popper node
if (!data.instance.popper.contains(arrowElement)) {
console.warn('WARNING: `arrow.element` must be child of its popper element!');
return data;
}
}
var placement = data.placement.split('-')[0];
var _data$offsets = data.offsets,
popper = _data$offsets.popper,
reference = _data$offsets.reference;
var isVertical = ['left', 'right'].indexOf(placement) !== -1;
var len = isVertical ? 'height' : 'width';
var sideCapitalized = isVertical ? 'Top' : 'Left';
var side = sideCapitalized.toLowerCase();
var altSide = isVertical ? 'left' : 'top';
var opSide = isVertical ? 'bottom' : 'right';
var arrowElementSize = getOuterSizes(arrowElement)[len];
//
// extends keepTogether behavior making sure the popper and its
// reference have enough pixels in conjunction
//
// top/left side
if (reference[opSide] - arrowElementSize < popper[side]) {
data.offsets.popper[side] -= popper[side] - (reference[opSide] - arrowElementSize);
}
// bottom/right side
if (reference[side] + arrowElementSize > popper[opSide]) {
data.offsets.popper[side] += reference[side] + arrowElementSize - popper[opSide];
}
data.offsets.popper = getClientRect(data.offsets.popper);
// compute center of the popper
var center = reference[side] + reference[len] / 2 - arrowElementSize / 2;
// Compute the sideValue using the updated popper offsets
// take popper margin in account because we don't have this info available
var css = getStyleComputedProperty(data.instance.popper);
var popperMarginSide = parseFloat(css['margin' + sideCapitalized]);
var popperBorderSide = parseFloat(css['border' + sideCapitalized + 'Width']);
var sideValue = center - data.offsets.popper[side] - popperMarginSide - popperBorderSide;
// prevent arrowElement from being placed not contiguously to its popper
sideValue = Math.max(Math.min(popper[len] - arrowElementSize, sideValue), 0);
data.arrowElement = arrowElement;
data.offsets.arrow = (_data$offsets$arrow = {}, defineProperty$3(_data$offsets$arrow, side, Math.round(sideValue)), defineProperty$3(_data$offsets$arrow, altSide, ''), _data$offsets$arrow);
return data;
}
/**
* Get the opposite placement variation of the given one
* @method
* @memberof Popper.Utils
* @argument {String} placement variation
* @returns {String} flipped placement variation
*/
function getOppositeVariation(variation) {
if (variation === 'end') {
return 'start';
} else if (variation === 'start') {
return 'end';
}
return variation;
}
/**
* List of accepted placements to use as values of the `placement` option.<br />
* Valid placements are:
* - `auto`
* - `top`
* - `right`
* - `bottom`
* - `left`
*
* Each placement can have a variation from this list:
* - `-start`
* - `-end`
*
* Variations are interpreted easily if you think of them as the left to right
* written languages. Horizontally (`top` and `bottom`), `start` is left and `end`
* is right.<br />
* Vertically (`left` and `right`), `start` is top and `end` is bottom.
*
* Some valid examples are:
* - `top-end` (on top of reference, right aligned)
* - `right-start` (on right of reference, top aligned)
* - `bottom` (on bottom, centered)
* - `auto-end` (on the side with more space available, alignment depends by placement)
*
* @static
* @type {Array}
* @enum {String}
* @readonly
* @method placements
* @memberof Popper
*/
var placements = ['auto-start', 'auto', 'auto-end', 'top-start', 'top', 'top-end', 'right-start', 'right', 'right-end', 'bottom-end', 'bottom', 'bottom-start', 'left-end', 'left', 'left-start'];
// Get rid of `auto` `auto-start` and `auto-end`
var validPlacements = placements.slice(3);
/**
* Given an initial placement, returns all the subsequent placements
* clockwise (or counter-clockwise).
*
* @method
* @memberof Popper.Utils
* @argument {String} placement - A valid placement (it accepts variations)
* @argument {Boolean} counter - Set to true to walk the placements counterclockwise
* @returns {Array} placements including their variations
*/
function clockwise(placement) {
var counter = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
var index = validPlacements.indexOf(placement);
var arr = validPlacements.slice(index + 1).concat(validPlacements.slice(0, index));
return counter ? arr.reverse() : arr;
}
var BEHAVIORS = {
FLIP: 'flip',
CLOCKWISE: 'clockwise',
COUNTERCLOCKWISE: 'counterclockwise'
};
/**
* @function
* @memberof Modifiers
* @argument {Object} data - The data object generated by update method
* @argument {Object} options - Modifiers configuration and options
* @returns {Object} The data object, properly modified
*/
function flip(data, options) {
// if `inner` modifier is enabled, we can't use the `flip` modifier
if (isModifierEnabled(data.instance.modifiers, 'inner')) {
return data;
}
if (data.flipped && data.placement === data.originalPlacement) {
// seems like flip is trying to loop, probably there's not enough space on any of the flippable sides
return data;
}
var boundaries = getBoundaries(data.instance.popper, data.instance.reference, options.padding, options.boundariesElement, data.positionFixed);
var placement = data.placement.split('-')[0];
var placementOpposite = getOppositePlacement(placement);
var variation = data.placement.split('-')[1] || '';
var flipOrder = [];
switch (options.behavior) {
case BEHAVIORS.FLIP:
flipOrder = [placement, placementOpposite];
break;
case BEHAVIORS.CLOCKWISE:
flipOrder = clockwise(placement);
break;
case BEHAVIORS.COUNTERCLOCKWISE:
flipOrder = clockwise(placement, true);
break;
default:
flipOrder = options.behavior;
}
flipOrder.forEach(function (step, index) {
if (placement !== step || flipOrder.length === index + 1) {
return data;
}
placement = data.placement.split('-')[0];
placementOpposite = getOppositePlacement(placement);
var popperOffsets = data.offsets.popper;
var refOffsets = data.offsets.reference;
// using floor because the reference offsets may contain decimals we are not going to consider here
var floor = Math.floor;
var overlapsRef = placement === 'left' && floor(popperOffsets.right) > floor(refOffsets.left) || placement === 'right' && floor(popperOffsets.left) < floor(refOffsets.right) || placement === 'top' && floor(popperOffsets.bottom) > floor(refOffsets.top) || placement === 'bottom' && floor(popperOffsets.top) < floor(refOffsets.bottom);
var overflowsLeft = floor(popperOffsets.left) < floor(boundaries.left);
var overflowsRight = floor(popperOffsets.right) > floor(boundaries.right);
var overflowsTop = floor(popperOffsets.top) < floor(boundaries.top);
var overflowsBottom = floor(popperOffsets.bottom) > floor(boundaries.bottom);
var overflowsBoundaries = placement === 'left' && overflowsLeft || placement === 'right' && overflowsRight || placement === 'top' && overflowsTop || placement === 'bottom' && overflowsBottom;
// flip the variation if required
var isVertical = ['top', 'bottom'].indexOf(placement) !== -1;
// flips variation if reference element overflows boundaries
var flippedVariationByRef = !!options.flipVariations && (isVertical && variation === 'start' && overflowsLeft || isVertical && variation === 'end' && overflowsRight || !isVertical && variation === 'start' && overflowsTop || !isVertical && variation === 'end' && overflowsBottom);
// flips variation if popper content overflows boundaries
var flippedVariationByContent = !!options.flipVariationsByContent && (isVertical && variation === 'start' && overflowsRight || isVertical && variation === 'end' && overflowsLeft || !isVertical && variation === 'start' && overflowsBottom || !isVertical && variation === 'end' && overflowsTop);
var flippedVariation = flippedVariationByRef || flippedVariationByContent;
if (overlapsRef || overflowsBoundaries || flippedVariation) {
// this boolean to detect any flip loop
data.flipped = true;
if (overlapsRef || overflowsBoundaries) {
placement = flipOrder[index + 1];
}
if (flippedVariation) {
variation = getOppositeVariation(variation);
}
data.placement = placement + (variation ? '-' + variation : '');
// this object contains `position`, we want to preserve it along with
// any additional property we may add in the future
data.offsets.popper = _extends$1({}, data.offsets.popper, getPopperOffsets(data.instance.popper, data.offsets.reference, data.placement));
data = runModifiers(data.instance.modifiers, data, 'flip');
}
});
return data;
}
/**
* @function
* @memberof Modifiers
* @argument {Object} data - The data object generated by update method
* @argument {Object} options - Modifiers configuration and options
* @returns {Object} The data object, properly modified
*/
function keepTogether(data) {
var _data$offsets = data.offsets,
popper = _data$offsets.popper,
reference = _data$offsets.reference;
var placement = data.placement.split('-')[0];
var floor = Math.floor;
var isVertical = ['top', 'bottom'].indexOf(placement) !== -1;
var side = isVertical ? 'right' : 'bottom';
var opSide = isVertical ? 'left' : 'top';
var measurement = isVertical ? 'width' : 'height';
if (popper[side] < floor(reference[opSide])) {
data.offsets.popper[opSide] = floor(reference[opSide]) - popper[measurement];
}
if (popper[opSide] > floor(reference[side])) {
data.offsets.popper[opSide] = floor(reference[side]);
}
return data;
}
/**
* Converts a string containing value + unit into a px value number
* @function
* @memberof {modifiers~offset}
* @private
* @argument {String} str - Value + unit string
* @argument {String} measurement - `height` or `width`
* @argument {Object} popperOffsets
* @argument {Object} referenceOffsets
* @returns {Number|String}
* Value in pixels, or original string if no values were extracted
*/
function toValue(str, measurement, popperOffsets, referenceOffsets) {
// separate value from unit
var split = str.match(/((?:\-|\+)?\d*\.?\d*)(.*)/);
var value = +split[1];
var unit = split[2];
// If it's not a number it's an operator, I guess
if (!value) {
return str;
}
if (unit.indexOf('%') === 0) {
var element = void 0;
switch (unit) {
case '%p':
element = popperOffsets;
break;
case '%':
case '%r':
default:
element = referenceOffsets;
}
var rect = getClientRect(element);
return rect[measurement] / 100 * value;
} else if (unit === 'vh' || unit === 'vw') {
// if is a vh or vw, we calculate the size based on the viewport
var size = void 0;
if (unit === 'vh') {
size = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
} else {
size = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
}
return size / 100 * value;
} else {
// if is an explicit pixel unit, we get rid of the unit and keep the value
// if is an implicit unit, it's px, and we return just the value
return value;
}
}
/**
* Parse an `offset` string to extrapolate `x` and `y` numeric offsets.
* @function
* @memberof {modifiers~offset}
* @private
* @argument {String} offset
* @argument {Object} popperOffsets
* @argument {Object} referenceOffsets
* @argument {String} basePlacement
* @returns {Array} a two cells array with x and y offsets in numbers
*/
function parseOffset(offset, popperOffsets, referenceOffsets, basePlacement) {
var offsets = [0, 0];
// Use height if placement is left or right and index is 0 otherwise use width
// in this way the first offset will use an axis and the second one
// will use the other one
var useHeight = ['right', 'left'].indexOf(basePlacement) !== -1;
// Split the offset string to obtain a list of values and operands
// The regex addresses values with the plus or minus sign in front (+10, -20, etc)
var fragments = offset.split(/(\+|\-)/).map(function (frag) {
return frag.trim();
});
// Detect if the offset string contains a pair of values or a single one
// they could be separated by comma or space
var divider = fragments.indexOf(find(fragments, function (frag) {
return frag.search(/,|\s/) !== -1;
}));
if (fragments[divider] && fragments[divider].indexOf(',') === -1) {
console.warn('Offsets separated by white space(s) are deprecated, use a comma (,) instead.');
}
// If divider is found, we divide the list of values and operands to divide
// them by ofset X and Y.
var splitRegex = /\s*,\s*|\s+/;
var ops = divider !== -1 ? [fragments.slice(0, divider).concat([fragments[divider].split(splitRegex)[0]]), [fragments[divider].split(splitRegex)[1]].concat(fragments.slice(divider + 1))] : [fragments];
// Convert the values with units to absolute pixels to allow our computations
ops = ops.map(function (op, index) {
// Most of the units rely on the orientation of the popper
var measurement = (index === 1 ? !useHeight : useHeight) ? 'height' : 'width';
var mergeWithPrevious = false;
return op
// This aggregates any `+` or `-` sign that aren't considered operators
// e.g.: 10 + +5 => [10, +, +5]
.reduce(function (a, b) {
if (a[a.length - 1] === '' && ['+', '-'].indexOf(b) !== -1) {
a[a.length - 1] = b;
mergeWithPrevious = true;
return a;
} else if (mergeWithPrevious) {
a[a.length - 1] += b;
mergeWithPrevious = false;
return a;
} else {
return a.concat(b);
}
}, [])
// Here we convert the string values into number values (in px)
.map(function (str) {
return toValue(str, measurement, popperOffsets, referenceOffsets);
});
});
// Loop trough the offsets arrays and execute the operations
ops.forEach(function (op, index) {
op.forEach(function (frag, index2) {
if (isNumeric(frag)) {
offsets[index] += frag * (op[index2 - 1] === '-' ? -1 : 1);
}
});
});
return offsets;
}
/**
* @function
* @memberof Modifiers
* @argument {Object} data - The data object generated by update method
* @argument {Object} options - Modifiers configuration and options
* @argument {Number|String} options.offset=0
* The offset value as described in the modifier description
* @returns {Object} The data object, properly modified
*/
function offset(data, _ref) {
var offset = _ref.offset;
var placement = data.placement,
_data$offsets = data.offsets,
popper = _data$offsets.popper,
reference = _data$offsets.reference;
var basePlacement = placement.split('-')[0];
var offsets = void 0;
if (isNumeric(+offset)) {
offsets = [+offset, 0];
} else {
offsets = parseOffset(offset, popper, reference, basePlacement);
}
if (basePlacement === 'left') {
popper.top += offsets[0];
popper.left -= offsets[1];
} else if (basePlacement === 'right') {
popper.top += offsets[0];
popper.left += offsets[1];
} else if (basePlacement === 'top') {
popper.left += offsets[0];
popper.top -= offsets[1];
} else if (basePlacement === 'bottom') {
popper.left += offsets[0];
popper.top += offsets[1];
}
data.popper = popper;
return data;
}
/**
* @function
* @memberof Modifiers
* @argument {Object} data - The data object generated by `update` method
* @argument {Object} options - Modifiers configuration and options
* @returns {Object} The data object, properly modified
*/
function preventOverflow(data, options) {
var boundariesElement = options.boundariesElement || getOffsetParent(data.instance.popper);
// If offsetParent is the reference element, we really want to
// go one step up and use the next offsetParent as reference to
// avoid to make this modifier completely useless and look like broken
if (data.instance.reference === boundariesElement) {
boundariesElement = getOffsetParent(boundariesElement);
}
// NOTE: DOM access here
// resets the popper's position so that the document size can be calculated excluding
// the size of the popper element itself
var transformProp = getSupportedPropertyName('transform');
var popperStyles = data.instance.popper.style; // assignment to help minification
var top = popperStyles.top,
left = popperStyles.left,
transform = popperStyles[transformProp];
popperStyles.top = '';
popperStyles.left = '';
popperStyles[transformProp] = '';
var boundaries = getBoundaries(data.instance.popper, data.instance.reference, options.padding, boundariesElement, data.positionFixed);
// NOTE: DOM access here
// restores the original style properties after the offsets have been computed
popperStyles.top = top;
popperStyles.left = left;
popperStyles[transformProp] = transform;
options.boundaries = boundaries;
var order = options.priority;
var popper = data.offsets.popper;
var check = {
primary: function primary(placement) {
var value = popper[placement];
if (popper[placement] < boundaries[placement] && !options.escapeWithReference) {
value = Math.max(popper[placement], boundaries[placement]);
}
return defineProperty$3({}, placement, value);
},
secondary: function secondary(placement) {
var mainSide = placement === 'right' ? 'left' : 'top';
var value = popper[mainSide];
if (popper[placement] > boundaries[placement] && !options.escapeWithReference) {
value = Math.min(popper[mainSide], boundaries[placement] - (placement === 'right' ? popper.width : popper.height));
}
return defineProperty$3({}, mainSide, value);
}
};
order.forEach(function (placement) {
var side = ['left', 'top'].indexOf(placement) !== -1 ? 'primary' : 'secondary';
popper = _extends$1({}, popper, check[side](placement));
});
data.offsets.popper = popper;
return data;
}
/**
* @function
* @memberof Modifiers
* @argument {Object} data - The data object generated by `update` method
* @argument {Object} options - Modifiers configuration and options
* @returns {Object} The data object, properly modified
*/
function shift(data) {
var placement = data.placement;
var basePlacement = placement.split('-')[0];
var shiftvariation = placement.split('-')[1];
// if shift shiftvariation is specified, run the modifier
if (shiftvariation) {
var _data$offsets = data.offsets,
reference = _data$offsets.reference,
popper = _data$offsets.popper;
var isVertical = ['bottom', 'top'].indexOf(basePlacement) !== -1;
var side = isVertical ? 'left' : 'top';
var measurement = isVertical ? 'width' : 'height';
var shiftOffsets = {
start: defineProperty$3({}, side, reference[side]),
end: defineProperty$3({}, side, reference[side] + reference[measurement] - popper[measurement])
};
data.offsets.popper = _extends$1({}, popper, shiftOffsets[shiftvariation]);
}
return data;
}
/**
* @function
* @memberof Modifiers
* @argument {Object} data - The data object generated by update method
* @argument {Object} options - Modifiers configuration and options
* @returns {Object} The data object, properly modified
*/
function hide(data) {
if (!isModifierRequired(data.instance.modifiers, 'hide', 'preventOverflow')) {
return data;
}
var refRect = data.offsets.reference;
var bound = find(data.instance.modifiers, function (modifier) {
return modifier.name === 'preventOverflow';
}).boundaries;
if (refRect.bottom < bound.top || refRect.left > bound.right || refRect.top > bound.bottom || refRect.right < bound.left) {
// Avoid unnecessary DOM access if visibility hasn't changed
if (data.hide === true) {
return data;
}
data.hide = true;
data.attributes['x-out-of-boundaries'] = '';
} else {
// Avoid unnecessary DOM access if visibility hasn't changed
if (data.hide === false) {
return data;
}
data.hide = false;
data.attributes['x-out-of-boundaries'] = false;
}
return data;
}
/**
* @function
* @memberof Modifiers
* @argument {Object} data - The data object generated by `update` method
* @argument {Object} options - Modifiers configuration and options
* @returns {Object} The data object, properly modified
*/
function inner(data) {
var placement = data.placement;
var basePlacement = placement.split('-')[0];
var _data$offsets = data.offsets,
popper = _data$offsets.popper,
reference = _data$offsets.reference;
var isHoriz = ['left', 'right'].indexOf(basePlacement) !== -1;
var subtractLength = ['top', 'left'].indexOf(basePlacement) === -1;
popper[isHoriz ? 'left' : 'top'] = reference[basePlacement] - (subtractLength ? popper[isHoriz ? 'width' : 'height'] : 0);
data.placement = getOppositePlacement(placement);
data.offsets.popper = getClientRect(popper);
return data;
}
/**
* Modifier function, each modifier can have a function of this type assigned
* to its `fn` property.<br />
* These functions will be called on each update, this means that you must
* make sure they are performant enough to avoid performance bottlenecks.
*
* @function ModifierFn
* @argument {dataObject} data - The data object generated by `update` method
* @argument {Object} options - Modifiers configuration and options
* @returns {dataObject} The data object, properly modified
*/
/**
* Modifiers are plugins used to alter the behavior of your poppers.<br />
* Popper.js uses a set of 9 modifiers to provide all the basic functionalities
* needed by the library.
*
* Usually you don't want to override the `order`, `fn` and `onLoad` props.
* All the other properties are configurations that could be tweaked.
* @namespace modifiers
*/
var modifiers = {
/**
* Modifier used to shift the popper on the start or end of its reference
* element.<br />
* It will read the variation of the `placement` property.<br />
* It can be one either `-end` or `-start`.
* @memberof modifiers
* @inner
*/
shift: {
/** @prop {number} order=100 - Index used to define the order of execution */
order: 100,
/** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
enabled: true,
/** @prop {ModifierFn} */
fn: shift
},
/**
* The `offset` modifier can shift your popper on both its axis.
*
* It accepts the following units:
* - `px` or unit-less, interpreted as pixels
* - `%` or `%r`, percentage relative to the length of the reference element
* - `%p`, percentage relative to the length of the popper element
* - `vw`, CSS viewport width unit
* - `vh`, CSS viewport height unit
*
* For length is intended the main axis relative to the placement of the popper.<br />
* This means that if the placement is `top` or `bottom`, the length will be the
* `width`. In case of `left` or `right`, it will be the `height`.
*
* You can provide a single value (as `Number` or `String`), or a pair of values
* as `String` divided by a comma or one (or more) white spaces.<br />
* The latter is a deprecated method because it leads to confusion and will be
* removed in v2.<br />
* Additionally, it accepts additions and subtractions between different units.
* Note that multiplications and divisions aren't supported.
*
* Valid examples are:
* ```
* 10
* '10%'
* '10, 10'
* '10%, 10'
* '10 + 10%'
* '10 - 5vh + 3%'
* '-10px + 5vh, 5px - 6%'
* ```
* > **NB**: If you desire to apply offsets to your poppers in a way that may make them overlap
* > with their reference element, unfortunately, you will have to disable the `flip` modifier.
* > You can read more on this at this [issue](https://github.com/FezVrasta/popper.js/issues/373).
*
* @memberof modifiers
* @inner
*/
offset: {
/** @prop {number} order=200 - Index used to define the order of execution */
order: 200,
/** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
enabled: true,
/** @prop {ModifierFn} */
fn: offset,
/** @prop {Number|String} offset=0
* The offset value as described in the modifier description
*/
offset: 0
},
/**
* Modifier used to prevent the popper from being positioned outside the boundary.
*
* A scenario exists where the reference itself is not within the boundaries.<br />
* We can say it has "escaped the boundaries" — or just "escaped".<br />
* In this case we need to decide whether the popper should either:
*
* - detach from the reference and remain "trapped" in the boundaries, or
* - if it should ignore the boundary and "escape with its reference"
*
* When `escapeWithReference` is set to`true` and reference is completely
* outside its boundaries, the popper will overflow (or completely leave)
* the boundaries in order to remain attached to the edge of the reference.
*
* @memberof modifiers
* @inner
*/
preventOverflow: {
/** @prop {number} order=300 - Index used to define the order of execution */
order: 300,
/** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
enabled: true,
/** @prop {ModifierFn} */
fn: preventOverflow,
/**
* @prop {Array} [priority=['left','right','top','bottom']]
* Popper will try to prevent overflow following these priorities by default,
* then, it could overflow on the left and on top of the `boundariesElement`
*/
priority: ['left', 'right', 'top', 'bottom'],
/**
* @prop {number} padding=5
* Amount of pixel used to define a minimum distance between the boundaries
* and the popper. This makes sure the popper always has a little padding
* between the edges of its container
*/
padding: 5,
/**
* @prop {String|HTMLElement} boundariesElement='scrollParent'
* Boundaries used by the modifier. Can be `scrollParent`, `window`,
* `viewport` or any DOM element.
*/
boundariesElement: 'scrollParent'
},
/**
* Modifier used to make sure the reference and its popper stay near each other
* without leaving any gap between the two. Especially useful when the arrow is
* enabled and you want to ensure that it points to its reference element.
* It cares only about the first axis. You can still have poppers with margin
* between the popper and its reference element.
* @memberof modifiers
* @inner
*/
keepTogether: {
/** @prop {number} order=400 - Index used to define the order of execution */
order: 400,
/** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
enabled: true,
/** @prop {ModifierFn} */
fn: keepTogether
},
/**
* This modifier is used to move the `arrowElement` of the popper to make
* sure it is positioned between the reference element and its popper element.
* It will read the outer size of the `arrowElement` node to detect how many
* pixels of conjunction are needed.
*
* It has no effect if no `arrowElement` is provided.
* @memberof modifiers
* @inner
*/
arrow: {
/** @prop {number} order=500 - Index used to define the order of execution */
order: 500,
/** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
enabled: true,
/** @prop {ModifierFn} */
fn: arrow,
/** @prop {String|HTMLElement} element='[x-arrow]' - Selector or node used as arrow */
element: '[x-arrow]'
},
/**
* Modifier used to flip the popper's placement when it starts to overlap its
* reference element.
*
* Requires the `preventOverflow` modifier before it in order to work.
*
* **NOTE:** this modifier will interrupt the current update cycle and will
* restart it if it detects the need to flip the placement.
* @memberof modifiers
* @inner
*/
flip: {
/** @prop {number} order=600 - Index used to define the order of execution */
order: 600,
/** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
enabled: true,
/** @prop {ModifierFn} */
fn: flip,
/**
* @prop {String|Array} behavior='flip'
* The behavior used to change the popper's placement. It can be one of
* `flip`, `clockwise`, `counterclockwise` or an array with a list of valid
* placements (with optional variations)
*/
behavior: 'flip',
/**
* @prop {number} padding=5
* The popper will flip if it hits the edges of the `boundariesElement`
*/
padding: 5,
/**
* @prop {String|HTMLElement} boundariesElement='viewport'
* The element which will define the boundaries of the popper position.
* The popper will never be placed outside of the defined boundaries
* (except if `keepTogether` is enabled)
*/
boundariesElement: 'viewport',
/**
* @prop {Boolean} flipVariations=false
* The popper will switch placement variation between `-start` and `-end` when
* the reference element overlaps its boundaries.
*
* The original placement should have a set variation.
*/
flipVariations: false,
/**
* @prop {Boolean} flipVariationsByContent=false
* The popper will switch placement variation between `-start` and `-end` when
* the popper element overlaps its reference boundaries.
*
* The original placement should have a set variation.
*/
flipVariationsByContent: false
},
/**
* Modifier used to make the popper flow toward the inner of the reference element.
* By default, when this modifier is disabled, the popper will be placed outside
* the reference element.
* @memberof modifiers
* @inner
*/
inner: {
/** @prop {number} order=700 - Index used to define the order of execution */
order: 700,
/** @prop {Boolean} enabled=false - Whether the modifier is enabled or not */
enabled: false,
/** @prop {ModifierFn} */
fn: inner
},
/**
* Modifier used to hide the popper when its reference element is outside of the
* popper boundaries. It will set a `x-out-of-boundaries` attribute which can
* be used to hide with a CSS selector the popper when its reference is
* out of boundaries.
*
* Requires the `preventOverflow` modifier before it in order to work.
* @memberof modifiers
* @inner
*/
hide: {
/** @prop {number} order=800 - Index used to define the order of execution */
order: 800,
/** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
enabled: true,
/** @prop {ModifierFn} */
fn: hide
},
/**
* Computes the style that will be applied to the popper element to gets
* properly positioned.
*
* Note that this modifier will not touch the DOM, it just prepares the styles
* so that `applyStyle` modifier can apply it. This separation is useful
* in case you need to replace `applyStyle` with a custom implementation.
*
* This modifier has `850` as `order` value to maintain backward compatibility
* with previous versions of Popper.js. Expect the modifiers ordering method
* to change in future major versions of the library.
*
* @memberof modifiers
* @inner
*/
computeStyle: {
/** @prop {number} order=850 - Index used to define the order of execution */
order: 850,
/** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
enabled: true,
/** @prop {ModifierFn} */
fn: computeStyle,
/**
* @prop {Boolean} gpuAcceleration=true
* If true, it uses the CSS 3D transformation to position the popper.
* Otherwise, it will use the `top` and `left` properties
*/
gpuAcceleration: true,
/**
* @prop {string} [x='bottom']
* Where to anchor the X axis (`bottom` or `top`). AKA X offset origin.
* Change this if your popper should grow in a direction different from `bottom`
*/
x: 'bottom',
/**
* @prop {string} [x='left']
* Where to anchor the Y axis (`left` or `right`). AKA Y offset origin.
* Change this if your popper should grow in a direction different from `right`
*/
y: 'right'
},
/**
* Applies the computed styles to the popper element.
*
* All the DOM manipulations are limited to this modifier. This is useful in case
* you want to integrate Popper.js inside a framework or view library and you
* want to delegate all the DOM manipulations to it.
*
* Note that if you disable this modifier, you must make sure the popper element
* has its position set to `absolute` before Popper.js can do its work!
*
* Just disable this modifier and define your own to achieve the desired effect.
*
* @memberof modifiers
* @inner
*/
applyStyle: {
/** @prop {number} order=900 - Index used to define the order of execution */
order: 900,
/** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
enabled: true,
/** @prop {ModifierFn} */
fn: applyStyle,
/** @prop {Function} */
onLoad: applyStyleOnLoad,
/**
* @deprecated since version 1.10.0, the property moved to `computeStyle` modifier
* @prop {Boolean} gpuAcceleration=true
* If true, it uses the CSS 3D transformation to position the popper.
* Otherwise, it will use the `top` and `left` properties
*/
gpuAcceleration: undefined
}
};
/**
* The `dataObject` is an object containing all the information used by Popper.js.
* This object is passed to modifiers and to the `onCreate` and `onUpdate` callbacks.
* @name dataObject
* @property {Object} data.instance The Popper.js instance
* @property {String} data.placement Placement applied to popper
* @property {String} data.originalPlacement Placement originally defined on init
* @property {Boolean} data.flipped True if popper has been flipped by flip modifier
* @property {Boolean} data.hide True if the reference element is out of boundaries, useful to know when to hide the popper
* @property {HTMLElement} data.arrowElement Node used as arrow by arrow modifier
* @property {Object} data.styles Any CSS property defined here will be applied to the popper. It expects the JavaScript nomenclature (eg. `marginBottom`)
* @property {Object} data.arrowStyles Any CSS property defined here will be applied to the popper arrow. It expects the JavaScript nomenclature (eg. `marginBottom`)
* @property {Object} data.boundaries Offsets of the popper boundaries
* @property {Object} data.offsets The measurements of popper, reference and arrow elements
* @property {Object} data.offsets.popper `top`, `left`, `width`, `height` values
* @property {Object} data.offsets.reference `top`, `left`, `width`, `height` values
* @property {Object} data.offsets.arrow] `top` and `left` offsets, only one of them will be different from 0
*/
/**
* Default options provided to Popper.js constructor.<br />
* These can be overridden using the `options` argument of Popper.js.<br />
* To override an option, simply pass an object with the same
* structure of the `options` object, as the 3rd argument. For example:
* ```
* new Popper(ref, pop, {
* modifiers: {
* preventOverflow: { enabled: false }
* }
* })
* ```
* @type {Object}
* @static
* @memberof Popper
*/
var Defaults = {
/**
* Popper's placement.
* @prop {Popper.placements} placement='bottom'
*/
placement: 'bottom',
/**
* Set this to true if you want popper to position it self in 'fixed' mode
* @prop {Boolean} positionFixed=false
*/
positionFixed: false,
/**
* Whether events (resize, scroll) are initially enabled.
* @prop {Boolean} eventsEnabled=true
*/
eventsEnabled: true,
/**
* Set to true if you want to automatically remove the popper when
* you call the `destroy` method.
* @prop {Boolean} removeOnDestroy=false
*/
removeOnDestroy: false,
/**
* Callback called when the popper is created.<br />
* By default, it is set to no-op.<br />
* Access Popper.js instance with `data.instance`.
* @prop {onCreate}
*/
onCreate: function onCreate() {},
/**
* Callback called when the popper is updated. This callback is not called
* on the initialization/creation of the popper, but only on subsequent
* updates.<br />
* By default, it is set to no-op.<br />
* Access Popper.js instance with `data.instance`.
* @prop {onUpdate}
*/
onUpdate: function onUpdate() {},
/**
* List of modifiers used to modify the offsets before they are applied to the popper.
* They provide most of the functionalities of Popper.js.
* @prop {modifiers}
*/
modifiers: modifiers
};
/**
* @callback onCreate
* @param {dataObject} data
*/
/**
* @callback onUpdate
* @param {dataObject} data
*/
// Utils
// Methods
var Popper = function () {
/**
* Creates a new Popper.js instance.
* @class Popper
* @param {Element|referenceObject} reference - The reference element used to position the popper
* @param {Element} popper - The HTML / XML element used as the popper
* @param {Object} options - Your custom options to override the ones defined in [Defaults](#defaults)
* @return {Object} instance - The generated Popper.js instance
*/
function Popper(reference, popper) {
var _this = this;
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
classCallCheck(this, Popper);
this.scheduleUpdate = function () {
return requestAnimationFrame(_this.update);
};
// make update() debounced, so that it only runs at most once-per-tick
this.update = debounce$1(this.update.bind(this));
// with {} we create a new object with the options inside it
this.options = _extends$1({}, Popper.Defaults, options);
// init state
this.state = {
isDestroyed: false,
isCreated: false,
scrollParents: []
};
// get reference and popper elements (allow jQuery wrappers)
this.reference = reference && reference.jquery ? reference[0] : reference;
this.popper = popper && popper.jquery ? popper[0] : popper;
// Deep merge modifiers options
this.options.modifiers = {};
Object.keys(_extends$1({}, Popper.Defaults.modifiers, options.modifiers)).forEach(function (name) {
_this.options.modifiers[name] = _extends$1({}, Popper.Defaults.modifiers[name] || {}, options.modifiers ? options.modifiers[name] : {});
});
// Refactoring modifiers' list (Object => Array)
this.modifiers = Object.keys(this.options.modifiers).map(function (name) {
return _extends$1({
name: name
}, _this.options.modifiers[name]);
})
// sort the modifiers by order
.sort(function (a, b) {
return a.order - b.order;
});
// modifiers have the ability to execute arbitrary code when Popper.js get inited
// such code is executed in the same order of its modifier
// they could add new properties to their options configuration
// BE AWARE: don't add options to `options.modifiers.name` but to `modifierOptions`!
this.modifiers.forEach(function (modifierOptions) {
if (modifierOptions.enabled && isFunction$2(modifierOptions.onLoad)) {
modifierOptions.onLoad(_this.reference, _this.popper, _this.options, modifierOptions, _this.state);
}
});
// fire the first update to position the popper in the right place
this.update();
var eventsEnabled = this.options.eventsEnabled;
if (eventsEnabled) {
// setup event listeners, they will take care of update the position in specific situations
this.enableEventListeners();
}
this.state.eventsEnabled = eventsEnabled;
}
// We can't use class properties because they don't get listed in the
// class prototype and break stuff like Sinon stubs
createClass(Popper, [{
key: 'update',
value: function update$$1() {
return update.call(this);
}
}, {
key: 'destroy',
value: function destroy$$1() {
return destroy.call(this);
}
}, {
key: 'enableEventListeners',
value: function enableEventListeners$$1() {
return enableEventListeners.call(this);
}
}, {
key: 'disableEventListeners',
value: function disableEventListeners$$1() {
return disableEventListeners.call(this);
}
/**
* Schedules an update. It will run on the next UI update available.
* @method scheduleUpdate
* @memberof Popper
*/
/**
* Collection of utilities useful when writing custom modifiers.
* Starting from version 1.7, this method is available only if you
* include `popper-utils.js` before `popper.js`.
*
* **DEPRECATION**: This way to access PopperUtils is deprecated
* and will be removed in v2! Use the PopperUtils module directly instead.
* Due to the high instability of the methods contained in Utils, we can't
* guarantee them to follow semver. Use them at your own risk!
* @static
* @private
* @type {Object}
* @deprecated since version 1.8
* @member Utils
* @memberof Popper
*/
}]);
return Popper;
}();
/**
* The `referenceObject` is an object that provides an interface compatible with Popper.js
* and lets you use it as replacement of a real DOM node.<br />
* You can use this method to position a popper relatively to a set of coordinates
* in case you don't have a DOM node to use as reference.
*
* ```
* new Popper(referenceObject, popperNode);
* ```
*
* NB: This feature isn't supported in Internet Explorer 10.
* @name referenceObject
* @property {Function} data.getBoundingClientRect
* A function that returns a set of coordinates compatible with the native `getBoundingClientRect` method.
* @property {number} data.clientWidth
* An ES6 getter that will return the width of the virtual reference element.
* @property {number} data.clientHeight
* An ES6 getter that will return the height of the virtual reference element.
*/
Popper.Utils = (typeof window !== 'undefined' ? window : global).PopperUtils;
Popper.placements = placements;
Popper.Defaults = Defaults;
var key = '__global_unique_id__';
var gud = function() {
return commonjsGlobal[key] = (commonjsGlobal[key] || 0) + 1;
};
var implementation$3 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
var _react2 = _interopRequireDefault(React__default);
var _propTypes2 = _interopRequireDefault(propTypes);
var _gud2 = _interopRequireDefault(gud);
var _warning2 = _interopRequireDefault(warning_1);
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; }
var MAX_SIGNED_31_BIT_INT = 1073741823;
// Inlined Object.is polyfill.
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
function objectIs(x, y) {
if (x === y) {
return x !== 0 || 1 / x === 1 / y;
} else {
return x !== x && y !== y;
}
}
function createEventEmitter(value) {
var handlers = [];
return {
on: function on(handler) {
handlers.push(handler);
},
off: function off(handler) {
handlers = handlers.filter(function (h) {
return h !== handler;
});
},
get: function get() {
return value;
},
set: function set(newValue, changedBits) {
value = newValue;
handlers.forEach(function (handler) {
return handler(value, changedBits);
});
}
};
}
function onlyChild(children) {
return Array.isArray(children) ? children[0] : children;
}
function createReactContext(defaultValue, calculateChangedBits) {
var _Provider$childContex, _Consumer$contextType;
var contextProp = '__create-react-context-' + (0, _gud2.default)() + '__';
var Provider = function (_Component) {
_inherits(Provider, _Component);
function Provider() {
var _temp, _this, _ret;
_classCallCheck(this, Provider);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, _Component.call.apply(_Component, [this].concat(args))), _this), _this.emitter = createEventEmitter(_this.props.value), _temp), _possibleConstructorReturn(_this, _ret);
}
Provider.prototype.getChildContext = function getChildContext() {
var _ref;
return _ref = {}, _ref[contextProp] = this.emitter, _ref;
};
Provider.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
if (this.props.value !== nextProps.value) {
var oldValue = this.props.value;
var newValue = nextProps.value;
var changedBits = void 0;
if (objectIs(oldValue, newValue)) {
changedBits = 0; // No change
} else {
changedBits = typeof calculateChangedBits === 'function' ? calculateChangedBits(oldValue, newValue) : MAX_SIGNED_31_BIT_INT;
{
(0, _warning2.default)((changedBits & MAX_SIGNED_31_BIT_INT) === changedBits, 'calculateChangedBits: Expected the return value to be a ' + '31-bit integer. Instead received: %s', changedBits);
}
changedBits |= 0;
if (changedBits !== 0) {
this.emitter.set(nextProps.value, changedBits);
}
}
}
};
Provider.prototype.render = function render() {
return this.props.children;
};
return Provider;
}(React__default.Component);
Provider.childContextTypes = (_Provider$childContex = {}, _Provider$childContex[contextProp] = _propTypes2.default.object.isRequired, _Provider$childContex);
var Consumer = function (_Component2) {
_inherits(Consumer, _Component2);
function Consumer() {
var _temp2, _this2, _ret2;
_classCallCheck(this, Consumer);
for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
return _ret2 = (_temp2 = (_this2 = _possibleConstructorReturn(this, _Component2.call.apply(_Component2, [this].concat(args))), _this2), _this2.state = {
value: _this2.getValue()
}, _this2.onUpdate = function (newValue, changedBits) {
var observedBits = _this2.observedBits | 0;
if ((observedBits & changedBits) !== 0) {
_this2.setState({ value: _this2.getValue() });
}
}, _temp2), _possibleConstructorReturn(_this2, _ret2);
}
Consumer.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
var observedBits = nextProps.observedBits;
this.observedBits = observedBits === undefined || observedBits === null ? MAX_SIGNED_31_BIT_INT // Subscribe to all changes by default
: observedBits;
};
Consumer.prototype.componentDidMount = function componentDidMount() {
if (this.context[contextProp]) {
this.context[contextProp].on(this.onUpdate);
}
var observedBits = this.props.observedBits;
this.observedBits = observedBits === undefined || observedBits === null ? MAX_SIGNED_31_BIT_INT // Subscribe to all changes by default
: observedBits;
};
Consumer.prototype.componentWillUnmount = function componentWillUnmount() {
if (this.context[contextProp]) {
this.context[contextProp].off(this.onUpdate);
}
};
Consumer.prototype.getValue = function getValue() {
if (this.context[contextProp]) {
return this.context[contextProp].get();
} else {
return defaultValue;
}
};
Consumer.prototype.render = function render() {
return onlyChild(this.props.children)(this.state.value);
};
return Consumer;
}(React__default.Component);
Consumer.contextTypes = (_Consumer$contextType = {}, _Consumer$contextType[contextProp] = _propTypes2.default.object, _Consumer$contextType);
return {
Provider: Provider,
Consumer: Consumer
};
}
exports.default = createReactContext;
module.exports = exports['default'];
});
unwrapExports(implementation$3);
var lib = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
var _react2 = _interopRequireDefault(React__default);
var _implementation2 = _interopRequireDefault(implementation$3);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = _react2.default.createContext || _implementation2.default;
module.exports = exports['default'];
});
var createContext = unwrapExports(lib);
var ManagerReferenceNodeContext = createContext();
var ManagerReferenceNodeSetterContext = createContext();
/**
* Takes an argument and if it's an array, returns the first item in the array,
* otherwise returns the argument. Used for Preact compatibility.
*/
var unwrapArray = function unwrapArray(arg) {
return Array.isArray(arg) ? arg[0] : arg;
};
/**
* Takes a maybe-undefined function and arbitrary args and invokes the function
* only if it is defined.
*/
var safeInvoke = function safeInvoke(fn) {
if (typeof fn === "function") {
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
return fn.apply(void 0, args);
}
};
/**
* Does a shallow equality check of two objects by comparing the reference
* equality of each value.
*/
var shallowEqual = function shallowEqual(objA, objB) {
var aKeys = Object.keys(objA);
var bKeys = Object.keys(objB);
if (bKeys.length !== aKeys.length) {
return false;
}
for (var i = 0; i < bKeys.length; i++) {
var key = aKeys[i];
if (objA[key] !== objB[key]) {
return false;
}
}
return true;
};
/**
* Sets a ref using either a ref callback or a ref object
*/
var setRef = function setRef(ref, node) {
// if its a function call it
if (typeof ref === "function") {
return safeInvoke(ref, node);
} // otherwise we should treat it as a ref object
else if (ref != null) {
ref.current = node;
}
};
var initialStyle = {
position: 'absolute',
top: 0,
left: 0,
opacity: 0,
pointerEvents: 'none'
};
var initialArrowStyle = {};
var InnerPopper =
/*#__PURE__*/
function (_React$Component) {
inheritsLoose(InnerPopper, _React$Component);
function InnerPopper() {
var _this;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;
defineProperty(assertThisInitialized(_this), "state", {
data: undefined,
placement: undefined
});
defineProperty(assertThisInitialized(_this), "popperInstance", void 0);
defineProperty(assertThisInitialized(_this), "popperNode", null);
defineProperty(assertThisInitialized(_this), "arrowNode", null);
defineProperty(assertThisInitialized(_this), "setPopperNode", function (popperNode) {
if (!popperNode || _this.popperNode === popperNode) return;
setRef(_this.props.innerRef, popperNode);
_this.popperNode = popperNode;
_this.updatePopperInstance();
});
defineProperty(assertThisInitialized(_this), "setArrowNode", function (arrowNode) {
_this.arrowNode = arrowNode;
});
defineProperty(assertThisInitialized(_this), "updateStateModifier", {
enabled: true,
order: 900,
fn: function fn(data) {
var placement = data.placement;
_this.setState({
data: data,
placement: placement
});
return data;
}
});
defineProperty(assertThisInitialized(_this), "getOptions", function () {
return {
placement: _this.props.placement,
eventsEnabled: _this.props.eventsEnabled,
positionFixed: _this.props.positionFixed,
modifiers: _extends_1({}, _this.props.modifiers, {
arrow: _extends_1({}, _this.props.modifiers && _this.props.modifiers.arrow, {
enabled: !!_this.arrowNode,
element: _this.arrowNode
}),
applyStyle: {
enabled: false
},
updateStateModifier: _this.updateStateModifier
})
};
});
defineProperty(assertThisInitialized(_this), "getPopperStyle", function () {
return !_this.popperNode || !_this.state.data ? initialStyle : _extends_1({
position: _this.state.data.offsets.popper.position
}, _this.state.data.styles);
});
defineProperty(assertThisInitialized(_this), "getPopperPlacement", function () {
return !_this.state.data ? undefined : _this.state.placement;
});
defineProperty(assertThisInitialized(_this), "getArrowStyle", function () {
return !_this.arrowNode || !_this.state.data ? initialArrowStyle : _this.state.data.arrowStyles;
});
defineProperty(assertThisInitialized(_this), "getOutOfBoundariesState", function () {
return _this.state.data ? _this.state.data.hide : undefined;
});
defineProperty(assertThisInitialized(_this), "destroyPopperInstance", function () {
if (!_this.popperInstance) return;
_this.popperInstance.destroy();
_this.popperInstance = null;
});
defineProperty(assertThisInitialized(_this), "updatePopperInstance", function () {
_this.destroyPopperInstance();
var _assertThisInitialize = assertThisInitialized(_this),
popperNode = _assertThisInitialize.popperNode;
var referenceElement = _this.props.referenceElement;
if (!referenceElement || !popperNode) return;
_this.popperInstance = new Popper(referenceElement, popperNode, _this.getOptions());
});
defineProperty(assertThisInitialized(_this), "scheduleUpdate", function () {
if (_this.popperInstance) {
_this.popperInstance.scheduleUpdate();
}
});
return _this;
}
var _proto = InnerPopper.prototype;
_proto.componentDidUpdate = function componentDidUpdate(prevProps, prevState) {
// If the Popper.js options have changed, update the instance (destroy + create)
if (this.props.placement !== prevProps.placement || this.props.referenceElement !== prevProps.referenceElement || this.props.positionFixed !== prevProps.positionFixed || !deepEqual_1(this.props.modifiers, prevProps.modifiers, {
strict: true
})) {
// develop only check that modifiers isn't being updated needlessly
{
if (this.props.modifiers !== prevProps.modifiers && this.props.modifiers != null && prevProps.modifiers != null && shallowEqual(this.props.modifiers, prevProps.modifiers)) {
console.warn("'modifiers' prop reference updated even though all values appear the same.\nConsider memoizing the 'modifiers' object to avoid needless rendering.");
}
}
this.updatePopperInstance();
} else if (this.props.eventsEnabled !== prevProps.eventsEnabled && this.popperInstance) {
this.props.eventsEnabled ? this.popperInstance.enableEventListeners() : this.popperInstance.disableEventListeners();
} // A placement difference in state means popper determined a new placement
// apart from the props value. By the time the popper element is rendered with
// the new position Popper has already measured it, if the place change triggers
// a size change it will result in a misaligned popper. So we schedule an update to be sure.
if (prevState.placement !== this.state.placement) {
this.scheduleUpdate();
}
};
_proto.componentWillUnmount = function componentWillUnmount() {
setRef(this.props.innerRef, null);
this.destroyPopperInstance();
};
_proto.render = function render() {
return unwrapArray(this.props.children)({
ref: this.setPopperNode,
style: this.getPopperStyle(),
placement: this.getPopperPlacement(),
outOfBoundaries: this.getOutOfBoundariesState(),
scheduleUpdate: this.scheduleUpdate,
arrowProps: {
ref: this.setArrowNode,
style: this.getArrowStyle()
}
});
};
return InnerPopper;
}(React.Component);
defineProperty(InnerPopper, "defaultProps", {
placement: 'bottom',
eventsEnabled: true,
referenceElement: undefined,
positionFixed: false
});
function Popper$1(_ref) {
var referenceElement = _ref.referenceElement,
props = objectWithoutPropertiesLoose(_ref, ["referenceElement"]);
return React.createElement(ManagerReferenceNodeContext.Consumer, null, function (referenceNode) {
return React.createElement(InnerPopper, _extends_1({
referenceElement: referenceElement !== undefined ? referenceElement : referenceNode
}, props));
});
}
// `Element` is not defined during server-side rendering, so shim it here.
/* istanbul ignore next */
var SafeElement = typeof Element === 'undefined' ? function () {} : Element;
var propTypes$2 = {
/**
* Specify menu alignment. The default value is `justify`, which makes the
* menu as wide as the input and truncates long values. Specifying `left`
* or `right` will align the menu to that side and the width will be
* determined by the length of menu item values.
*/
align: propTypes.oneOf(values(ALIGN)),
children: propTypes.func.isRequired,
/**
* Specify whether the menu should appear above the input.
*/
dropup: propTypes.bool,
/**
* Whether or not to automatically adjust the position of the menu when it
* reaches the viewport boundaries.
*/
flip: propTypes.bool,
isMenuShown: propTypes.bool,
positionFixed: propTypes.bool,
referenceElement: propTypes.instanceOf(SafeElement)
};
var defaultProps$1 = {
align: ALIGN.JUSTIFY,
dropup: false,
flip: false,
isMenuShown: false,
positionFixed: false
};
function getModifiers(_ref) {
var align = _ref.align,
flip = _ref.flip;
return {
computeStyles: {
enabled: true,
fn: function fn(_ref2) {
var styles = _ref2.styles,
data = _objectWithoutPropertiesLoose(_ref2, ["styles"]);
return _extends({}, data, {
styles: _extends({}, styles, {
// Use the following condition instead of `align === 'justify'`
// since it allows the component to fall back to justifying the
// menu width if `align` is undefined.
width: align !== ALIGN.RIGHT && align !== ALIGN.LEFT ? // Set the popper width to match the target width.
data.offsets.reference.width : styles.width
})
});
}
},
flip: {
enabled: flip
},
preventOverflow: {
escapeWithReference: true
}
};
} // Flow expects a string literal value for `placement`.
var PLACEMENT = {
bottom: {
end: 'bottom-end',
start: 'bottom-start'
},
top: {
end: 'top-end',
start: 'top-start'
}
};
function getPlacement(_ref3) {
var align = _ref3.align,
dropup = _ref3.dropup;
var x = align === ALIGN.RIGHT ? 'end' : 'start';
var y = dropup ? 'top' : 'bottom';
return PLACEMENT[y][x];
}
var Overlay = function Overlay(props) {
var children = props.children,
isMenuShown = props.isMenuShown,
positionFixed = props.positionFixed,
referenceElement = props.referenceElement;
if (!isMenuShown) {
return null;
}
return React.createElement(Popper$1, {
modifiers: getModifiers(props),
placement: getPlacement(props),
positionFixed: positionFixed,
referenceElement: referenceElement
}, function (_ref4) {
var ref = _ref4.ref,
popperProps = _objectWithoutPropertiesLoose(_ref4, ["ref"]);
return children(_extends({}, popperProps, {
innerRef: ref,
inputHeight: referenceElement ? referenceElement.offsetHeight : 0
}));
});
};
Overlay.propTypes = propTypes$2;
Overlay.defaultProps = defaultProps$1;
var TypeaheadContext = React.createContext({
activeIndex: -1,
hintText: '',
id: '',
initialItem: null,
inputNode: null,
isOnlyResult: false,
items: [],
onActiveItemChange: noop,
onAdd: noop,
onInitialItemChange: noop,
onMenuItemClick: noop,
selectHintOnEnter: false,
value: ''
});
var useTypeaheadContext = function useTypeaheadContext() {
return React.useContext(TypeaheadContext);
};
var inputPropKeys = ['activeIndex', 'disabled', 'id', 'inputRef', 'isFocused', 'isMenuShown', 'multiple', 'onBlur', 'onChange', 'onFocus', 'onKeyDown', 'placeholder'];
var propKeys = ['activeIndex', 'isMenuShown', 'labelKey', 'onClear', 'onHide', 'onRemove', 'results', 'selected', 'text'];
var contextKeys = ['activeIndex', 'id', 'initialItem', 'inputNode', 'items', 'onActiveItemChange', 'onAdd', 'onInitialItemChange', 'onMenuItemClick', 'selectHintOnEnter'];
function usePrevious(value) {
var ref = React.useRef(null);
React.useEffect(function () {
ref.current = value;
});
return ref.current;
}
var TypeaheadManager = function TypeaheadManager(props) {
var allowNew = props.allowNew,
children = props.children,
initialItem = props.initialItem,
isMenuShown = props.isMenuShown,
onAdd = props.onAdd,
onInitialItemChange = props.onInitialItemChange,
onKeyDown = props.onKeyDown,
onMenuToggle = props.onMenuToggle,
results = props.results;
var prevProps = usePrevious(props);
React.useEffect(function () {
// Clear the initial item when there are no results.
if (!(allowNew || results.length)) {
onInitialItemChange(null);
}
});
React.useEffect(function () {
if (prevProps && prevProps.isMenuShown !== isMenuShown) {
onMenuToggle(isMenuShown);
}
});
var handleKeyDown = React.useCallback(function (e) {
switch (e.keyCode) {
case RETURN:
if (initialItem && getIsOnlyResult(props)) {
onAdd(initialItem);
}
break;
}
onKeyDown(e);
});
var value = getInputText(props);
var childProps = _extends({}, pick(props, propKeys), {
getInputProps: getInputProps(_extends({}, pick(props, inputPropKeys), {
onKeyDown: handleKeyDown,
value: value
}))
});
var contextValue = _extends({}, pick(props, contextKeys), {
hintText: getHintText(props),
isOnlyResult: getIsOnlyResult(props),
value: value
});
return React__default.createElement(TypeaheadContext.Provider, {
value: contextValue
}, children(childProps));
};
var propTypes$3 = {
/**
* Allows the creation of new selections on the fly. Note that any new items
* will be added to the list of selections, but not the list of original
* options unless handled as such by `Typeahead`'s parent.
*
* If a function is specified, it will be used to determine whether a custom
* option should be included. The return value should be true or false.
*/
allowNew: propTypes.oneOfType([propTypes.bool, propTypes.func]),
/**
* Autofocus the input when the component initially mounts.
*/
autoFocus: propTypes.bool,
/**
* Whether or not filtering should be case-sensitive.
*/
caseSensitive: checkPropType(propTypes.bool, caseSensitiveType),
/**
* The initial value displayed in the text input.
*/
defaultInputValue: checkPropType(propTypes.string, defaultInputValueType),
/**
* Whether or not the menu is displayed upon initial render.
*/
defaultOpen: propTypes.bool,
/**
* Specify any pre-selected options. Use only if you want the component to
* be uncontrolled.
*/
defaultSelected: checkPropType(propTypes.arrayOf(optionType), defaultSelectedType),
/**
* Either an array of fields in `option` to search, or a custom filtering
* callback.
*/
filterBy: propTypes.oneOfType([propTypes.arrayOf(propTypes.string.isRequired), propTypes.func]),
/**
* Highlights the menu item if there is only one result and allows selecting
* that item by hitting enter. Does not work with `allowNew`.
*/
highlightOnlyResult: checkPropType(propTypes.bool, highlightOnlyResultType),
/**
* An html id attribute, required for assistive technologies such as screen
* readers.
*/
id: checkPropType(propTypes.oneOfType([propTypes.number, propTypes.string]), isRequiredForA11y),
/**
* Whether the filter should ignore accents and other diacritical marks.
*/
ignoreDiacritics: checkPropType(propTypes.bool, ignoreDiacriticsType),
/**
* Specify the option key to use for display or a function returning the
* display string. By default, the selector will use the `label` key.
*/
labelKey: checkPropType(propTypes.oneOfType([propTypes.string, propTypes.func]), labelKeyType),
/**
* Maximum number of results to display by default. Mostly done for
* performance reasons so as not to render too many DOM nodes in the case of
* large data sets.
*/
maxResults: propTypes.number,
/**
* Number of input characters that must be entered before showing results.
*/
minLength: propTypes.number,
/**
* Whether or not multiple selections are allowed.
*/
multiple: propTypes.bool,
/**
* Invoked when the input is blurred. Receives an event.
*/
onBlur: propTypes.func,
/**
* Invoked whenever items are added or removed. Receives an array of the
* selected options.
*/
onChange: propTypes.func,
/**
* Invoked when the input is focused. Receives an event.
*/
onFocus: propTypes.func,
/**
* Invoked when the input value changes. Receives the string value of the
* input.
*/
onInputChange: propTypes.func,
/**
* Invoked when a key is pressed. Receives an event.
*/
onKeyDown: propTypes.func,
/**
* Invoked when menu visibility changes.
*/
onMenuToggle: propTypes.func,
/**
* Invoked when the pagination menu item is clicked. Receives an event.
*/
onPaginate: propTypes.func,
/**
* Whether or not the menu should be displayed. `undefined` allows the
* component to control visibility, while `true` and `false` show and hide
* the menu, respectively.
*/
open: propTypes.bool,
/**
* Full set of options, including pre-selected options. Must either be an
* array of objects (recommended) or strings.
*/
options: propTypes.arrayOf(optionType).isRequired,
/**
* Give user the ability to display additional results if the number of
* results exceeds `maxResults`.
*/
paginate: propTypes.bool,
/**
* The selected option(s) displayed in the input. Use this prop if you want
* to control the component via its parent.
*/
selected: checkPropType(propTypes.arrayOf(optionType), selectedType),
/**
* Allows selecting the hinted result by pressing enter.
*/
selectHintOnEnter: propTypes.bool
};
var defaultProps$2 = {
allowNew: false,
autoFocus: false,
caseSensitive: false,
defaultInputValue: '',
defaultOpen: false,
defaultSelected: [],
filterBy: [],
highlightOnlyResult: false,
ignoreDiacritics: true,
labelKey: DEFAULT_LABELKEY,
maxResults: 100,
minLength: 0,
multiple: false,
onBlur: noop,
onFocus: noop,
onInputChange: noop,
onKeyDown: noop,
onMenuToggle: noop,
onPaginate: noop,
paginate: true,
selectHintOnEnter: false
};
function getInitialState(props) {
var defaultInputValue = props.defaultInputValue,
defaultOpen = props.defaultOpen,
defaultSelected = props.defaultSelected,
maxResults = props.maxResults,
multiple = props.multiple;
var selected = props.selected ? props.selected.slice() : defaultSelected.slice();
var text = defaultInputValue;
if (!multiple && selected.length) {
// Set the text if an initial selection is passed in.
text = getOptionLabel(head(selected), props.labelKey);
if (selected.length > 1) {
// Limit to 1 selection in single-select mode.
selected = selected.slice(0, 1);
}
}
return {
activeIndex: -1,
activeItem: null,
initialItem: null,
isFocused: false,
selected: selected,
showMenu: defaultOpen,
shownResults: maxResults,
text: text
};
}
function clearTypeahead(state, props) {
return _extends({}, getInitialState(props), {
isFocused: state.isFocused,
selected: [],
text: ''
});
}
function hideMenu(state, props) {
var _getInitialState = getInitialState(props),
activeIndex = _getInitialState.activeIndex,
activeItem = _getInitialState.activeItem,
initialItem = _getInitialState.initialItem,
shownResults = _getInitialState.shownResults;
return {
activeIndex: activeIndex,
activeItem: activeItem,
initialItem: initialItem,
showMenu: false,
shownResults: shownResults
};
}
var Typeahead = /*#__PURE__*/function (_React$Component) {
_inheritsLoose(Typeahead, _React$Component);
function Typeahead() {
var _this;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;
_defineProperty(_assertThisInitialized(_this), "state", getInitialState(_this.props));
_defineProperty(_assertThisInitialized(_this), "inputNode", void 0);
_defineProperty(_assertThisInitialized(_this), "isMenuShown", false);
_defineProperty(_assertThisInitialized(_this), "items", []);
_defineProperty(_assertThisInitialized(_this), "blur", function () {
_this.inputNode && _this.inputNode.blur();
_this._hideMenu();
});
_defineProperty(_assertThisInitialized(_this), "clear", function () {
_this.setState(clearTypeahead);
});
_defineProperty(_assertThisInitialized(_this), "focus", function () {
_this.inputNode && _this.inputNode.focus();
});
_defineProperty(_assertThisInitialized(_this), "getInput", function () {
return _this.inputNode;
});
_defineProperty(_assertThisInitialized(_this), "inputRef", function (inputNode) {
_this.inputNode = inputNode;
});
_defineProperty(_assertThisInitialized(_this), "_handleActiveIndexChange", function (activeIndex) {
_this.setState(function (state) {
return {
activeIndex: activeIndex,
activeItem: activeIndex === -1 ? null : state.activeItem
};
});
});
_defineProperty(_assertThisInitialized(_this), "_handleActiveItemChange", function (activeItem) {
// Don't update the active item if it hasn't changed.
if (!fastDeepEqual(activeItem, _this.state.activeItem)) {
_this.setState({
activeItem: activeItem
});
}
});
_defineProperty(_assertThisInitialized(_this), "_handleBlur", function (e) {
e.persist();
_this.setState({
isFocused: false
}, function () {
return _this.props.onBlur(e);
});
});
_defineProperty(_assertThisInitialized(_this), "_handleChange", function (selected) {
_this.props.onChange && _this.props.onChange(selected);
});
_defineProperty(_assertThisInitialized(_this), "_handleClear", function () {
_this.setState(clearTypeahead, function () {
return _this._handleChange([]);
});
});
_defineProperty(_assertThisInitialized(_this), "_handleFocus", function (e) {
e.persist();
_this.setState({
isFocused: true,
showMenu: true
}, function () {
return _this.props.onFocus(e);
});
});
_defineProperty(_assertThisInitialized(_this), "_handleInitialItemChange", function (initialItem) {
// Don't update the initial item if it hasn't changed.
if (!fastDeepEqual(initialItem, _this.state.initialItem)) {
_this.setState({
initialItem: initialItem
});
}
});
_defineProperty(_assertThisInitialized(_this), "_handleInputChange", function (e) {
e.persist();
var text = e.currentTarget.value;
var _this$props = _this.props,
multiple = _this$props.multiple,
onInputChange = _this$props.onInputChange; // Clear selections when the input value changes in single-select mode.
var shouldClearSelections = _this.state.selected.length && !multiple;
_this.setState(function (state, props) {
var _getInitialState2 = getInitialState(props),
activeIndex = _getInitialState2.activeIndex,
activeItem = _getInitialState2.activeItem,
shownResults = _getInitialState2.shownResults;
return {
activeIndex: activeIndex,
activeItem: activeItem,
selected: shouldClearSelections ? [] : state.selected,
showMenu: true,
shownResults: shownResults,
text: text
};
}, function () {
onInputChange(text, e);
shouldClearSelections && _this._handleChange([]);
});
});
_defineProperty(_assertThisInitialized(_this), "_handleKeyDown", function (e) {
var activeItem = _this.state.activeItem; // Skip most actions when the menu is hidden.
if (!_this.isMenuShown) {
if (e.keyCode === UP || e.keyCode === DOWN) {
_this.setState({
showMenu: true
});
}
_this.props.onKeyDown(e);
return;
}
switch (e.keyCode) {
case UP:
case DOWN:
// Prevent input cursor from going to the beginning when pressing up.
e.preventDefault();
_this._handleActiveIndexChange(getUpdatedActiveIndex(_this.state.activeIndex, e.keyCode, _this.items));
break;
case RETURN:
// Prevent form submission while menu is open.
e.preventDefault();
activeItem && _this._handleMenuItemSelect(activeItem, e);
break;
case ESC:
case TAB:
// ESC simply hides the menu. TAB will blur the input and move focus to
// the next item; hide the menu so it doesn't gain focus.
_this._hideMenu();
break;
}
_this.props.onKeyDown(e);
});
_defineProperty(_assertThisInitialized(_this), "_handleMenuItemSelect", function (option, e) {
if (option.paginationOption) {
_this._handlePaginate(e);
} else {
_this._handleSelectionAdd(option);
}
});
_defineProperty(_assertThisInitialized(_this), "_handlePaginate", function (e) {
e.persist();
_this.setState(function (state, props) {
return {
shownResults: state.shownResults + props.maxResults
};
}, function () {
return _this.props.onPaginate(e, _this.state.shownResults);
});
});
_defineProperty(_assertThisInitialized(_this), "_handleSelectionAdd", function (option) {
var _this$props2 = _this.props,
multiple = _this$props2.multiple,
labelKey = _this$props2.labelKey;
var selected;
var selection = option;
var text; // Add a unique id to the custom selection. Avoid doing this in `render` so
// the id doesn't increment every time.
if (!isString(selection) && selection.customOption) {
selection = _extends({}, selection, {
id: uniqueId('new-id-')
});
}
if (multiple) {
// If multiple selections are allowed, add the new selection to the
// existing selections.
selected = _this.state.selected.concat(selection);
text = '';
} else {
// If only a single selection is allowed, replace the existing selection
// with the new one.
selected = [selection];
text = getOptionLabel(selection, labelKey);
}
_this.setState(function (state, props) {
return _extends({}, hideMenu(state, props), {
initialItem: selection,
selected: selected,
text: text
});
}, function () {
return _this._handleChange(selected);
});
});
_defineProperty(_assertThisInitialized(_this), "_handleSelectionRemove", function (selection) {
var selected = _this.state.selected.filter(function (option) {
return !fastDeepEqual(option, selection);
}); // Make sure the input stays focused after the item is removed.
_this.focus();
_this.setState(function (state, props) {
return _extends({}, hideMenu(state, props), {
selected: selected
});
}, function () {
return _this._handleChange(selected);
});
});
_defineProperty(_assertThisInitialized(_this), "_hideMenu", function () {
_this.setState(hideMenu);
});
return _this;
}
var _proto = Typeahead.prototype;
_proto.componentDidMount = function componentDidMount() {
this.props.autoFocus && this.focus();
};
_proto.componentDidUpdate = function componentDidUpdate(prevProps, prevState) {
var _this$props3 = this.props,
labelKey = _this$props3.labelKey,
multiple = _this$props3.multiple,
selected = _this$props3.selected;
validateSelectedPropChange(selected, prevProps.selected); // Sync selections in state with those in props.
if (selected && !fastDeepEqual(selected, prevState.selected)) {
this.setState({
selected: selected
});
if (!multiple) {
this.setState({
text: selected.length ? getOptionLabel(head(selected), labelKey) : ''
});
}
}
};
_proto.render = function render() {
// Omit `onChange` so Flow doesn't complain.
var _this$props4 = this.props,
onChange = _this$props4.onChange,
otherProps = _objectWithoutPropertiesLoose(_this$props4, ["onChange"]);
var mergedPropsAndState = _extends({}, otherProps, {}, this.state);
var filterBy = mergedPropsAndState.filterBy,
labelKey = mergedPropsAndState.labelKey,
options = mergedPropsAndState.options,
paginate = mergedPropsAndState.paginate,
shownResults = mergedPropsAndState.shownResults,
text = mergedPropsAndState.text;
this.isMenuShown = isShown(mergedPropsAndState);
this.items = []; // Reset items on re-render.
var results = [];
if (this.isMenuShown) {
var cb = typeof filterBy === 'function' ? filterBy : defaultFilterBy;
results = options.filter(function (option) {
return cb(option, mergedPropsAndState);
}); // This must come before results are truncated.
var shouldPaginate = paginate && results.length > shownResults; // Truncate results if necessary.
results = getTruncatedOptions(results, shownResults); // Add the custom option if necessary.
if (addCustomOption(results, mergedPropsAndState)) {
var _results$push;
results.push((_results$push = {
customOption: true
}, _results$push[getStringLabelKey(labelKey)] = text, _results$push));
} // Add the pagination item if necessary.
if (shouldPaginate) {
var _results$push2;
results.push((_results$push2 = {}, _results$push2[getStringLabelKey(labelKey)] = '', _results$push2.paginationOption = true, _results$push2));
}
}
return React__default.createElement(TypeaheadManager, _extends({}, mergedPropsAndState, {
inputNode: this.inputNode,
inputRef: this.inputRef,
isMenuShown: this.isMenuShown,
items: this.items,
onActiveItemChange: this._handleActiveItemChange,
onAdd: this._handleSelectionAdd,
onBlur: this._handleBlur,
onChange: this._handleInputChange,
onClear: this._handleClear,
onFocus: this._handleFocus,
onHide: this._hideMenu,
onInitialItemChange: this._handleInitialItemChange,
onKeyDown: this._handleKeyDown,
onMenuItemClick: this._handleMenuItemSelect,
onRemove: this._handleSelectionRemove,
results: results
}));
};
return Typeahead;
}(React__default.Component);
_defineProperty(Typeahead, "propTypes", propTypes$3);
_defineProperty(Typeahead, "defaultProps", defaultProps$2);
var propTypes$4 = {
label: propTypes.string,
onClick: propTypes.func,
size: sizeType
};
var defaultProps$3 = {
label: 'Clear',
onClick: noop
};
/**
* ClearButton
*
* http://getbootstrap.com/css/#helper-classes-close
*/
var ClearButton = function ClearButton(_ref) {
var className = _ref.className,
label = _ref.label,
_onClick = _ref.onClick,
size = _ref.size,
props = _objectWithoutPropertiesLoose(_ref, ["className", "label", "onClick", "size"]);
return React__default.createElement("button", _extends({}, props, {
"aria-label": label,
className: classnames('close', 'rbt-close', {
'rbt-close-lg': isSizeLarge(size)
}, className),
onClick: function onClick(e) {
e.stopPropagation();
_onClick(e);
},
type: "button"
}), React__default.createElement("span", {
"aria-hidden": "true"
}, "\xD7"), React__default.createElement("span", {
className: "sr-only"
}, label));
};
ClearButton.propTypes = propTypes$4;
ClearButton.defaultProps = defaultProps$3;
var propTypes$5 = {
label: propTypes.string
};
var defaultProps$4 = {
label: 'Loading...'
};
var Loader = function Loader(_ref) {
var label = _ref.label;
return React__default.createElement("div", {
className: "rbt-loader spinner-border spinner-border-sm",
role: "status"
}, React__default.createElement("span", {
className: "sr-only"
}, label));
};
Loader.propTypes = propTypes$5;
Loader.defaultProps = defaultProps$4;
/* eslint-disable no-bitwise, no-cond-assign */
// HTML DOM and SVG DOM may have different support levels,
// so we need to check on context instead of a document root element.
function contains(context, node) {
if (context.contains) return context.contains(node);
if (context.compareDocumentPosition) return context === node || !!(context.compareDocumentPosition(node) & 16);
}
var canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement);
/* eslint-disable no-return-assign */
var optionsSupported = false;
var onceSupported = false;
try {
var options = {
get passive() {
return optionsSupported = true;
},
get once() {
// eslint-disable-next-line no-multi-assign
return onceSupported = optionsSupported = true;
}
};
if (canUseDOM) {
window.addEventListener('test', options, options);
window.removeEventListener('test', options, true);
}
} catch (e) {
/* */
}
/**
* An `addEventListener` ponyfill, supports the `once` option
*/
function addEventListener(node, eventName, handler, options) {
if (options && typeof options !== 'boolean' && !onceSupported) {
var once = options.once,
capture = options.capture;
var wrappedHandler = handler;
if (!onceSupported && once) {
wrappedHandler = handler.__once || function onceHandler(event) {
this.removeEventListener(eventName, onceHandler, capture);
handler.call(this, event);
};
handler.__once = wrappedHandler;
}
node.addEventListener(eventName, wrappedHandler, optionsSupported ? options : capture);
}
node.addEventListener(eventName, handler, options);
}
function removeEventListener(node, eventName, handler, options) {
var capture = options && typeof options !== 'boolean' ? options.capture : options;
node.removeEventListener(eventName, handler, capture);
if (handler.__once) {
node.removeEventListener(eventName, handler.__once, capture);
}
}
function listen(node, eventName, handler, options) {
addEventListener(node, eventName, handler, options);
return function () {
removeEventListener(node, eventName, handler, options);
};
}
/**
* Creates a `Ref` whose value is updated in an effect, ensuring the most recent
* value is the one rendered with. Generally only required for Concurrent mode usage
* where previous work in `render()` may be discarded befor being used.
*
* This is safe to access in an event handler.
*
* @param value The `Ref` value
*/
function useCommittedRef(value) {
var ref = React.useRef(value);
React.useEffect(function () {
ref.current = value;
}, [value]);
return ref;
}
function useEventCallback(fn) {
var ref = useCommittedRef(fn);
return React.useCallback(function () {
return ref.current && ref.current.apply(ref, arguments);
}, [ref]);
}
function ownerDocument(node) {
return node && node.ownerDocument || document;
}
function ownerDocument$1 (componentOrElement) {
return ownerDocument(ReactDOM.findDOMNode(componentOrElement));
}
var escapeKeyCode = 27;
var noop$1 = function noop() {};
function isLeftClickEvent(event) {
return event.button === 0;
}
function isModifiedEvent(event) {
return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
}
/**
* The `useRootClose` hook registers your callback on the document
* when rendered. Powers the `<Overlay/>` component. This is used achieve modal
* style behavior where your callback is triggered when the user tries to
* interact with the rest of the document or hits the `esc` key.
*
* @param {Ref<HTMLElement>|HTMLElement} ref The element boundary
* @param {function} onRootClose
* @param {object} options
* @param {boolean} options.disabled
* @param {string} options.clickTrigger The DOM event name (click, mousedown, etc) to attach listeners on
*/
function useRootClose(ref, onRootClose, _temp) {
var _ref = _temp === void 0 ? {} : _temp,
disabled = _ref.disabled,
_ref$clickTrigger = _ref.clickTrigger,
clickTrigger = _ref$clickTrigger === void 0 ? 'click' : _ref$clickTrigger;
var preventMouseRootCloseRef = React.useRef(false);
var onClose = onRootClose || noop$1;
var handleMouseCapture = React.useCallback(function (e) {
var currentTarget = ref && ('current' in ref ? ref.current : ref);
warning_1(!!currentTarget, 'RootClose captured a close event but does not have a ref to compare it to. ' + 'useRootClose(), should be passed a ref that resolves to a DOM node');
preventMouseRootCloseRef.current = !currentTarget || isModifiedEvent(e) || !isLeftClickEvent(e) || contains(currentTarget, e.target);
}, [ref]);
var handleMouse = useEventCallback(function (e) {
if (!preventMouseRootCloseRef.current) {
onClose(e);
}
});
var handleKeyUp = useEventCallback(function (e) {
if (e.keyCode === escapeKeyCode) {
onClose(e);
}
});
React.useEffect(function () {
if (disabled || ref == null) return undefined;
var doc = ownerDocument$1(ref.current); // Use capture for this listener so it fires before React's listener, to
// avoid false positives in the contains() check below if the target DOM
// element is removed in the React mouse callback.
var removeMouseCaptureListener = listen(doc, clickTrigger, handleMouseCapture, true);
var removeMouseListener = listen(doc, clickTrigger, handleMouse);
var removeKeyupListener = listen(doc, 'keyup', handleKeyUp);
var mobileSafariHackListeners = [];
if ('ontouchstart' in doc.documentElement) {
mobileSafariHackListeners = [].slice.call(doc.body.children).map(function (el) {
return listen(el, 'mousemove', noop$1);
});
}
return function () {
removeMouseCaptureListener();
removeMouseListener();
removeKeyupListener();
mobileSafariHackListeners.forEach(function (remove) {
return remove();
});
};
}, [ref, disabled, clickTrigger, handleMouseCapture, handleMouse, handleKeyUp]);
}
var RootClose = function RootClose(_ref) {
var children = _ref.children,
onRootClose = _ref.onRootClose,
props = _objectWithoutPropertiesLoose(_ref, ["children", "onRootClose"]);
var _useState = React.useState(null),
rootElement = _useState[0],
attachRef = _useState[1];
useRootClose(rootElement, onRootClose, props);
return children(attachRef);
};
var propTypes$6 = {
onBlur: propTypes.func,
onClick: propTypes.func,
onFocus: propTypes.func,
onRemove: propTypes.func,
option: optionType.isRequired
};
var defaultProps$5 = {
onBlur: noop,
onClick: noop,
onFocus: noop
};
/**
* Higher-order component to encapsulate Token behaviors.
*/
var tokenContainer = function tokenContainer(Component) {
var WrappedComponent = /*#__PURE__*/function (_React$Component) {
_inheritsLoose(WrappedComponent, _React$Component);
function WrappedComponent() {
var _this;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;
_defineProperty(_assertThisInitialized(_this), "state", {
active: false
});
_defineProperty(_assertThisInitialized(_this), "_handleActiveChange", function (e, active, callback) {
// e.persist() isn't always present.
e.persist && e.persist();
e.stopPropagation();
_this.setState({
active: active
}, function () {
return callback(e);
});
});
_defineProperty(_assertThisInitialized(_this), "_handleBlur", function (e) {
_this._handleActiveChange(e, false, _this.props.onBlur);
});
_defineProperty(_assertThisInitialized(_this), "_handleClick", function (e) {
_this._handleActiveChange(e, true, _this.props.onClick);
});
_defineProperty(_assertThisInitialized(_this), "_handleFocus", function (e) {
_this._handleActiveChange(e, true, _this.props.onFocus);
});
_defineProperty(_assertThisInitialized(_this), "_handleKeyDown", function (e) {
switch (e.keyCode) {
case BACKSPACE:
if (_this.state.active) {
// Prevent backspace keypress from triggering the browser "back"
// action.
e.preventDefault();
_this._handleRemove();
}
break;
}
});
_defineProperty(_assertThisInitialized(_this), "_handleRemove", function () {
var _this$props = _this.props,
onRemove = _this$props.onRemove,
option = _this$props.option; // Flow having trouble with `isFunction` here for some reason...
if (typeof onRemove === 'function') {
onRemove(option);
}
});
return _this;
}
var _proto = WrappedComponent.prototype;
_proto.render = function render() {
var _this2 = this;
var onRemove = this.props.onRemove;
var active = this.state.active;
return React__default.createElement(RootClose, {
disabled: !active,
onRootClose: this._handleBlur
}, function (ref) {
return React__default.createElement(Component, _extends({}, _this2.props, {
active: active,
onBlur: _this2._handleBlur,
onClick: _this2._handleClick,
onFocus: _this2._handleFocus,
onKeyDown: _this2._handleKeyDown,
onRemove: isFunction(onRemove) ? _this2._handleRemove : undefined,
ref: ref
}));
});
};
return WrappedComponent;
}(React__default.Component);
_defineProperty(WrappedComponent, "displayName", "tokenContainer(" + getDisplayName(Component) + ")");
_defineProperty(WrappedComponent, "propTypes", propTypes$6);
_defineProperty(WrappedComponent, "defaultProps", defaultProps$5);
return WrappedComponent;
};
var InteractiveToken = React.forwardRef(function (_ref, ref) {
var active = _ref.active,
children = _ref.children,
className = _ref.className,
onRemove = _ref.onRemove,
tabIndex = _ref.tabIndex,
props = _objectWithoutPropertiesLoose(_ref, ["active", "children", "className", "onRemove", "tabIndex"]);
return React__default.createElement("div", _extends({}, props, {
className: classnames('rbt-token', 'rbt-token-removeable', {
'rbt-token-active': !!active
}, className),
ref: ref,
tabIndex: tabIndex || 0
}), children, React__default.createElement(ClearButton, {
className: "rbt-token-remove-button",
label: "Remove",
onClick: onRemove,
tabIndex: -1
}));
});
var StaticToken = function StaticToken(_ref2) {
var children = _ref2.children,
className = _ref2.className,
disabled = _ref2.disabled,
href = _ref2.href;
var classnames$1 = classnames('rbt-token', {
'rbt-token-disabled': disabled
}, className);
if (href && !disabled) {
return React__default.createElement("a", {
className: classnames$1,
href: href
}, children);
}
return React__default.createElement("div", {
className: classnames$1
}, children);
};
/**
* Token
*
* Individual token component, generally displayed within the TokenizerInput
* component, but can also be rendered on its own.
*/
var Token = React.forwardRef(function (props, ref) {
var disabled = props.disabled,
onRemove = props.onRemove,
readOnly = props.readOnly;
return !disabled && !readOnly && isFunction(onRemove) ? React__default.createElement(InteractiveToken, _extends({}, props, {
ref: ref
})) : React__default.createElement(StaticToken, props);
});
var Token$1 = tokenContainer(Token);
// 'borderStyle', etc.), so generate these from the individual values.
function interpolateStyle(styles, attr, subattr) {
if (subattr === void 0) {
subattr = '';
}
// Title-case the sub-attribute.
if (subattr) {
/* eslint-disable-next-line no-param-reassign */
subattr = subattr.replace(subattr[0], subattr[0].toUpperCase());
}
return ['Top', 'Right', 'Bottom', 'Left'].map(function (dir) {
return styles[attr + dir + subattr];
}).join(' ');
}
function copyStyles(inputNode, hintNode) {
if (!inputNode || !hintNode) {
return;
}
var inputStyle = window.getComputedStyle(inputNode);
/* eslint-disable no-param-reassign */
hintNode.style.borderStyle = interpolateStyle(inputStyle, 'border', 'style');
hintNode.style.borderWidth = interpolateStyle(inputStyle, 'border', 'width');
hintNode.style.fontSize = inputStyle.fontSize;
hintNode.style.height = inputStyle.height;
hintNode.style.lineHeight = inputStyle.lineHeight;
hintNode.style.margin = interpolateStyle(inputStyle, 'margin');
hintNode.style.padding = interpolateStyle(inputStyle, 'padding');
/* eslint-enable no-param-reassign */
}
var Hint = function Hint(_ref) {
var children = _ref.children,
className = _ref.className;
var context = useTypeaheadContext();
var hintText = context.hintText,
initialItem = context.initialItem,
inputNode = context.inputNode,
onAdd = context.onAdd;
var hintRef = React.useRef(null);
!(React__default.Children.count(children) === 1) ? invariant_1(false, 'The `Hint` component expects one child.') : void 0;
var onKeyDown = React.useCallback(function (e) {
if (shouldSelectHint(e, context)) {
e.preventDefault(); // Prevent input from blurring on TAB.
initialItem && onAdd(initialItem);
}
children.props.onKeyDown(e);
});
React.useEffect(function () {
copyStyles(inputNode, hintRef.current);
});
return React__default.createElement("div", {
className: className,
style: {
display: 'flex',
flex: 1,
height: '100%',
position: 'relative'
}
}, React.cloneElement(children, _extends({}, children.props, {
onKeyDown: onKeyDown
})), React__default.createElement("input", {
"aria-hidden": true,
className: "rbt-input-hint",
ref: hintRef,
readOnly: true,
style: {
backgroundColor: 'transparent',
borderColor: 'transparent',
boxShadow: 'none',
color: 'rgba(0, 0, 0, 0.35)',
left: 0,
pointerEvents: 'none',
position: 'absolute',
top: 0,
width: '100%'
},
tabIndex: -1,
value: hintText
}));
};
var Input = React__default.forwardRef(function (props, ref) {
return React__default.createElement("input", _extends({}, props, {
className: classnames('rbt-input-main', props.className),
ref: ref
}));
});
function withClassNames(Component) {
// Use a class instead of function component to support refs.
/* eslint-disable-next-line react/prefer-stateless-function */
var WrappedComponent = /*#__PURE__*/function (_React$Component) {
_inheritsLoose(WrappedComponent, _React$Component);
function WrappedComponent() {
return _React$Component.apply(this, arguments) || this;
}
var _proto = WrappedComponent.prototype;
_proto.render = function render() {
var _this$props = this.props,
className = _this$props.className,
isInvalid = _this$props.isInvalid,
isValid = _this$props.isValid,
size = _this$props.size,
props = _objectWithoutPropertiesLoose(_this$props, ["className", "isInvalid", "isValid", "size"]);
return React__default.createElement(Component, _extends({}, props, {
className: classnames('form-control', 'rbt-input', {
'form-control-lg': isSizeLarge(size),
'form-control-sm': isSizeSmall(size),
'is-invalid': isInvalid,
'is-valid': isValid
}, className)
}));
};
return WrappedComponent;
}(React__default.Component);
_defineProperty(WrappedComponent, "displayName", "withClassNames(" + getDisplayName(Component) + ")");
return WrappedComponent;
}
var TypeaheadInputMulti = /*#__PURE__*/function (_React$Component) {
_inheritsLoose(TypeaheadInputMulti, _React$Component);
function TypeaheadInputMulti() {
var _this;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;
_defineProperty(_assertThisInitialized(_this), "wrapperRef", React__default.createRef());
_defineProperty(_assertThisInitialized(_this), "_input", void 0);
_defineProperty(_assertThisInitialized(_this), "getInputRef", function (input) {
_this._input = input;
_this.props.inputRef(input);
});
_defineProperty(_assertThisInitialized(_this), "_handleContainerClickOrFocus", function (e) {
// Don't focus the input if it's disabled.
if (_this.props.disabled) {
e.currentTarget.blur();
return;
} // Move cursor to the end if the user clicks outside the actual input.
var inputNode = _this._input;
if (!inputNode) {
return;
}
if (e.currentTarget !== inputNode && isSelectable(inputNode)) {
inputNode.selectionStart = inputNode.value.length;
}
inputNode.focus();
});
_defineProperty(_assertThisInitialized(_this), "_handleKeyDown", function (e) {
var _this$props = _this.props,
onKeyDown = _this$props.onKeyDown,
selected = _this$props.selected,
value = _this$props.value;
switch (e.keyCode) {
case BACKSPACE:
if (e.currentTarget === _this._input && selected.length && !value) {
// Prevent browser from going back.
e.preventDefault(); // If the input is selected and there is no text, focus the last
// token when the user hits backspace.
if (_this.wrapperRef.current) {
var children = _this.wrapperRef.current.children;
var lastToken = children[children.length - 2];
lastToken && lastToken.focus();
}
}
break;
}
onKeyDown(e);
});
return _this;
}
var _proto = TypeaheadInputMulti.prototype;
_proto.render = function render() {
var _this$props2 = this.props,
children = _this$props2.children,
className = _this$props2.className,
inputClassName = _this$props2.inputClassName,
inputRef = _this$props2.inputRef,
placeholder = _this$props2.placeholder,
referenceElementRef = _this$props2.referenceElementRef,
selected = _this$props2.selected,
props = _objectWithoutPropertiesLoose(_this$props2, ["children", "className", "inputClassName", "inputRef", "placeholder", "referenceElementRef", "selected"]);
return React__default.createElement("div", {
className: classnames('rbt-input-multi', className),
disabled: props.disabled,
onClick: this._handleContainerClickOrFocus,
onFocus: this._handleContainerClickOrFocus,
ref: referenceElementRef,
tabIndex: -1
}, React__default.createElement("div", {
className: "rbt-input-wrapper",
ref: this.wrapperRef
}, children, React__default.createElement(Hint, null, React__default.createElement(Input, _extends({}, props, {
className: inputClassName,
onKeyDown: this._handleKeyDown,
placeholder: selected.length ? '' : placeholder,
ref: this.getInputRef,
style: {
backgroundColor: 'transparent',
border: 0,
boxShadow: 'none',
cursor: 'inherit',
outline: 'none',
padding: 0,
width: '100%',
zIndex: 1
}
})))));
};
return TypeaheadInputMulti;
}(React__default.Component);
var TypeaheadInputMulti$1 = withClassNames(TypeaheadInputMulti);
var TypeaheadInputSingle = withClassNames(function (_ref) {
var inputRef = _ref.inputRef,
referenceElementRef = _ref.referenceElementRef,
props = _objectWithoutPropertiesLoose(_ref, ["inputRef", "referenceElementRef"]);
return React__default.createElement(Hint, null, React__default.createElement(Input, _extends({}, props, {
ref: function ref(node) {
inputRef(node);
referenceElementRef(node);
}
})));
});
var propTypes$7 = {
children: propTypes.string.isRequired,
highlightClassName: propTypes.string,
search: propTypes.string.isRequired
};
var defaultProps$6 = {
highlightClassName: 'rbt-highlight-text'
};
/**
* Stripped-down version of https://github.com/helior/react-highlighter
*
* Results are already filtered by the time the component is used internally so
* we can safely ignore case and diacritical marks for the purposes of matching.
*/
var Highlighter = /*#__PURE__*/function (_React$PureComponent) {
_inheritsLoose(Highlighter, _React$PureComponent);
function Highlighter() {
return _React$PureComponent.apply(this, arguments) || this;
}
var _proto = Highlighter.prototype;
_proto.render = function render() {
var _this$props = this.props,
children = _this$props.children,
highlightClassName = _this$props.highlightClassName,
search = _this$props.search;
if (!search || !children) {
return children;
}
var matchCount = 0;
var remaining = children;
var highlighterChildren = [];
while (remaining) {
var bounds = getMatchBounds(remaining, search); // No match anywhere in the remaining string, stop.
if (!bounds) {
highlighterChildren.push(remaining);
break;
} // Capture the string that leads up to a match.
var nonMatch = remaining.slice(0, bounds.start);
if (nonMatch) {
highlighterChildren.push(nonMatch);
} // Capture the matching string.
var match = remaining.slice(bounds.start, bounds.end);
highlighterChildren.push(React__default.createElement("mark", {
className: highlightClassName,
key: matchCount
}, match));
matchCount += 1; // And if there's anything left over, continue the loop.
remaining = remaining.slice(bounds.end);
}
return highlighterChildren;
};
return Highlighter;
}(React__default.PureComponent);
_defineProperty(Highlighter, "propTypes", propTypes$7);
_defineProperty(Highlighter, "defaultProps", defaultProps$6);
function isElement(el) {
return el != null && typeof el === 'object' && el.nodeType === 1;
}
function canOverflow(overflow, skipOverflowHiddenElements) {
if (skipOverflowHiddenElements && overflow === 'hidden') {
return false;
}
return overflow !== 'visible' && overflow !== 'clip';
}
function getFrameElement(el) {
if (!el.ownerDocument || !el.ownerDocument.defaultView) {
return null;
}
return el.ownerDocument.defaultView.frameElement;
}
function isHiddenByFrame(el) {
var frame = getFrameElement(el);
if (!frame) {
return false;
}
return frame.clientHeight < el.scrollHeight || frame.clientWidth < el.scrollWidth;
}
function isScrollable(el, skipOverflowHiddenElements) {
if (el.clientHeight < el.scrollHeight || el.clientWidth < el.scrollWidth) {
var style = getComputedStyle(el, null);
return canOverflow(style.overflowY, skipOverflowHiddenElements) || canOverflow(style.overflowX, skipOverflowHiddenElements) || isHiddenByFrame(el);
}
return false;
}
function alignNearest(scrollingEdgeStart, scrollingEdgeEnd, scrollingSize, scrollingBorderStart, scrollingBorderEnd, elementEdgeStart, elementEdgeEnd, elementSize) {
if (elementEdgeStart < scrollingEdgeStart && elementEdgeEnd > scrollingEdgeEnd || elementEdgeStart > scrollingEdgeStart && elementEdgeEnd < scrollingEdgeEnd) {
return 0;
}
if (elementEdgeStart <= scrollingEdgeStart && elementSize <= scrollingSize || elementEdgeEnd >= scrollingEdgeEnd && elementSize >= scrollingSize) {
return elementEdgeStart - scrollingEdgeStart - scrollingBorderStart;
}
if (elementEdgeEnd > scrollingEdgeEnd && elementSize < scrollingSize || elementEdgeStart < scrollingEdgeStart && elementSize > scrollingSize) {
return elementEdgeEnd - scrollingEdgeEnd + scrollingBorderEnd;
}
return 0;
}
var compute = (function (target, options) {
var scrollMode = options.scrollMode,
block = options.block,
inline = options.inline,
boundary = options.boundary,
skipOverflowHiddenElements = options.skipOverflowHiddenElements;
var checkBoundary = typeof boundary === 'function' ? boundary : function (node) {
return node !== boundary;
};
if (!isElement(target)) {
throw new TypeError('Invalid target');
}
var scrollingElement = document.scrollingElement || document.documentElement;
var frames = [];
var cursor = target;
while (isElement(cursor) && checkBoundary(cursor)) {
cursor = cursor.parentNode;
if (cursor === scrollingElement) {
frames.push(cursor);
break;
}
if (cursor === document.body && isScrollable(cursor) && !isScrollable(document.documentElement)) {
continue;
}
if (isScrollable(cursor, skipOverflowHiddenElements)) {
frames.push(cursor);
}
}
var viewportWidth = window.visualViewport ? visualViewport.width : innerWidth;
var viewportHeight = window.visualViewport ? visualViewport.height : innerHeight;
var viewportX = window.scrollX || pageXOffset;
var viewportY = window.scrollY || pageYOffset;
var _target$getBoundingCl = target.getBoundingClientRect(),
targetHeight = _target$getBoundingCl.height,
targetWidth = _target$getBoundingCl.width,
targetTop = _target$getBoundingCl.top,
targetRight = _target$getBoundingCl.right,
targetBottom = _target$getBoundingCl.bottom,
targetLeft = _target$getBoundingCl.left;
var targetBlock = block === 'start' || block === 'nearest' ? targetTop : block === 'end' ? targetBottom : targetTop + targetHeight / 2;
var targetInline = inline === 'center' ? targetLeft + targetWidth / 2 : inline === 'end' ? targetRight : targetLeft;
var computations = [];
for (var index = 0; index < frames.length; index++) {
var frame = frames[index];
var _frame$getBoundingCli = frame.getBoundingClientRect(),
height = _frame$getBoundingCli.height,
width = _frame$getBoundingCli.width,
top = _frame$getBoundingCli.top,
right = _frame$getBoundingCli.right,
bottom = _frame$getBoundingCli.bottom,
left = _frame$getBoundingCli.left;
if (scrollMode === 'if-needed' && targetTop >= 0 && targetLeft >= 0 && targetBottom <= viewportHeight && targetRight <= viewportWidth && targetTop >= top && targetBottom <= bottom && targetLeft >= left && targetRight <= right) {
return computations;
}
var frameStyle = getComputedStyle(frame);
var borderLeft = parseInt(frameStyle.borderLeftWidth, 10);
var borderTop = parseInt(frameStyle.borderTopWidth, 10);
var borderRight = parseInt(frameStyle.borderRightWidth, 10);
var borderBottom = parseInt(frameStyle.borderBottomWidth, 10);
var blockScroll = 0;
var inlineScroll = 0;
var scrollbarWidth = 'offsetWidth' in frame ? frame.offsetWidth - frame.clientWidth - borderLeft - borderRight : 0;
var scrollbarHeight = 'offsetHeight' in frame ? frame.offsetHeight - frame.clientHeight - borderTop - borderBottom : 0;
if (scrollingElement === frame) {
if (block === 'start') {
blockScroll = targetBlock;
} else if (block === 'end') {
blockScroll = targetBlock - viewportHeight;
} else if (block === 'nearest') {
blockScroll = alignNearest(viewportY, viewportY + viewportHeight, viewportHeight, borderTop, borderBottom, viewportY + targetBlock, viewportY + targetBlock + targetHeight, targetHeight);
} else {
blockScroll = targetBlock - viewportHeight / 2;
}
if (inline === 'start') {
inlineScroll = targetInline;
} else if (inline === 'center') {
inlineScroll = targetInline - viewportWidth / 2;
} else if (inline === 'end') {
inlineScroll = targetInline - viewportWidth;
} else {
inlineScroll = alignNearest(viewportX, viewportX + viewportWidth, viewportWidth, borderLeft, borderRight, viewportX + targetInline, viewportX + targetInline + targetWidth, targetWidth);
}
blockScroll = Math.max(0, blockScroll + viewportY);
inlineScroll = Math.max(0, inlineScroll + viewportX);
} else {
if (block === 'start') {
blockScroll = targetBlock - top - borderTop;
} else if (block === 'end') {
blockScroll = targetBlock - bottom + borderBottom + scrollbarHeight;
} else if (block === 'nearest') {
blockScroll = alignNearest(top, bottom, height, borderTop, borderBottom + scrollbarHeight, targetBlock, targetBlock + targetHeight, targetHeight);
} else {
blockScroll = targetBlock - (top + height / 2) + scrollbarHeight / 2;
}
if (inline === 'start') {
inlineScroll = targetInline - left - borderLeft;
} else if (inline === 'center') {
inlineScroll = targetInline - (left + width / 2) + scrollbarWidth / 2;
} else if (inline === 'end') {
inlineScroll = targetInline - right + borderRight + scrollbarWidth;
} else {
inlineScroll = alignNearest(left, right, width, borderLeft, borderRight + scrollbarWidth, targetInline, targetInline + targetWidth, targetWidth);
}
var scrollLeft = frame.scrollLeft,
scrollTop = frame.scrollTop;
blockScroll = Math.max(0, Math.min(scrollTop + blockScroll, frame.scrollHeight - height + scrollbarHeight));
inlineScroll = Math.max(0, Math.min(scrollLeft + inlineScroll, frame.scrollWidth - width + scrollbarWidth));
targetBlock += scrollTop - blockScroll;
targetInline += scrollLeft - inlineScroll;
}
computations.push({
el: frame,
top: blockScroll,
left: inlineScroll
});
}
return computations;
});
function isOptionsObject(options) {
return options === Object(options) && Object.keys(options).length !== 0;
}
function defaultBehavior(actions, behavior) {
if (behavior === void 0) {
behavior = 'auto';
}
var canSmoothScroll = 'scrollBehavior' in document.body.style;
actions.forEach(function (_ref) {
var el = _ref.el,
top = _ref.top,
left = _ref.left;
if (el.scroll && canSmoothScroll) {
el.scroll({
top: top,
left: left,
behavior: behavior
});
} else {
el.scrollTop = top;
el.scrollLeft = left;
}
});
}
function getOptions(options) {
if (options === false) {
return {
block: 'end',
inline: 'nearest'
};
}
if (isOptionsObject(options)) {
return options;
}
return {
block: 'start',
inline: 'nearest'
};
}
function scrollIntoView(target, options) {
var targetIsDetached = !target.ownerDocument.documentElement.contains(target);
if (isOptionsObject(options) && typeof options.behavior === 'function') {
return options.behavior(targetIsDetached ? [] : compute(target, options));
}
if (targetIsDetached) {
return;
}
var computeOptions = getOptions(options);
return defaultBehavior(compute(target, computeOptions), computeOptions.behavior);
}
var propTypes$8 = {
option: optionType.isRequired,
position: propTypes.number
};
var menuItemContainer = function menuItemContainer(Component) {
var displayName = "menuItemContainer(" + getDisplayName(Component) + ")";
var WrappedMenuItem = function WrappedMenuItem(_ref) {
var label = _ref.label,
option = _ref.option,
position = _ref.position,
props = _objectWithoutPropertiesLoose(_ref, ["label", "option", "position"]);
var _useTypeaheadContext = useTypeaheadContext(),
activeIndex = _useTypeaheadContext.activeIndex,
id = _useTypeaheadContext.id,
isOnlyResult = _useTypeaheadContext.isOnlyResult,
items = _useTypeaheadContext.items,
onActiveItemChange = _useTypeaheadContext.onActiveItemChange,
onInitialItemChange = _useTypeaheadContext.onInitialItemChange,
onMenuItemClick = _useTypeaheadContext.onMenuItemClick;
var itemRef = React.useRef(null);
React.useEffect(function () {
if (position === 0) {
onInitialItemChange(option);
}
}, [position]);
React.useEffect(function () {
if (position === activeIndex) {
onActiveItemChange(option); // Automatically scroll the menu as the user keys through it.
var node = itemRef.current;
node && scrollIntoView(node, {
block: 'nearest',
boundary: node.parentNode,
inline: 'nearest',
scrollMode: 'if-needed'
});
}
}, [activeIndex, position]);
var active = isOnlyResult || activeIndex === position; // Update the item's position in the item stack on each render.
items[position] = option;
var handleClick = React.useCallback(function (e) {
onMenuItemClick(option, e);
props.onClick && props.onClick(e);
});
return React__default.createElement(Component, _extends({}, props, {
active: active,
"aria-label": label,
"aria-selected": active,
id: getMenuItemId(id, position),
onClick: handleClick,
onMouseDown: preventInputBlur,
ref: itemRef,
role: "option"
}));
};
WrappedMenuItem.displayName = displayName;
WrappedMenuItem.propTypes = propTypes$8;
return WrappedMenuItem;
};
var BaseMenuItem = React__default.forwardRef(function (_ref, ref) {
var active = _ref.active,
children = _ref.children,
className = _ref.className,
disabled = _ref.disabled,
_onClick = _ref.onClick,
onMouseDown = _ref.onMouseDown,
props = _objectWithoutPropertiesLoose(_ref, ["active", "children", "className", "disabled", "onClick", "onMouseDown"]);
return (
/* eslint-disable jsx-a11y/anchor-is-valid */
React__default.createElement("a", _extends({}, props, {
className: classnames('dropdown-item', {
active: active,
disabled: disabled
}, className),
href: "#",
onClick: function onClick(e) {
e.preventDefault();
!disabled && _onClick && _onClick(e);
},
onMouseDown: onMouseDown,
ref: ref
}), children)
/* eslint-enable jsx-a11y/anchor-is-valid */
);
});
var MenuItem = menuItemContainer(BaseMenuItem);
var MenuDivider = function MenuDivider(props) {
return React__default.createElement("div", {
className: "dropdown-divider",
role: "separator"
});
};
var MenuHeader = function MenuHeader(props) {
return React__default.createElement("div", _extends({}, props, {
className: "dropdown-header",
role: "heading"
}));
};
var propTypes$9 = {
'aria-label': propTypes.string,
/**
* Message to display in the menu if there are no valid results.
*/
emptyLabel: propTypes.node,
/**
* Needed for accessibility.
*/
id: checkPropType(propTypes.oneOfType([propTypes.number, propTypes.string]), isRequiredForA11y),
/**
* Maximum height of the dropdown menu.
*/
maxHeight: propTypes.string
};
var defaultProps$7 = {
'aria-label': 'menu-options',
emptyLabel: 'No matches found.',
maxHeight: '300px'
};
/**
* Menu component that handles empty state when passed a set of results.
*/
var Menu = /*#__PURE__*/function (_React$Component) {
_inheritsLoose(Menu, _React$Component);
function Menu() {
return _React$Component.apply(this, arguments) || this;
}
var _proto = Menu.prototype;
_proto.componentDidUpdate = function componentDidUpdate(prevProps) {
var _this$props = this.props,
inputHeight = _this$props.inputHeight,
scheduleUpdate = _this$props.scheduleUpdate; // Update the menu position if the height of the input changes.
if (inputHeight !== prevProps.inputHeight) {
scheduleUpdate();
}
};
_proto.render = function render() {
var _this$props2 = this.props,
children = _this$props2.children,
className = _this$props2.className,
emptyLabel = _this$props2.emptyLabel,
id = _this$props2.id,
innerRef = _this$props2.innerRef,
maxHeight = _this$props2.maxHeight,
style = _this$props2.style,
text = _this$props2.text;
var contents = React.Children.count(children) === 0 ? React__default.createElement(BaseMenuItem, {
disabled: true,
role: "option"
}, emptyLabel) : children;
return React__default.createElement("div", {
"aria-label": this.props['aria-label'],
className: classnames('rbt-menu', 'dropdown-menu', 'show', className),
id: id,
key: // Force a re-render if the text changes to ensure that menu
// positioning updates correctly.
text,
ref: innerRef,
role: "listbox",
style: _extends({}, style, {
display: 'block',
maxHeight: maxHeight,
overflow: 'auto'
})
}, contents);
};
return Menu;
}(React__default.Component);
_defineProperty(Menu, "propTypes", propTypes$9);
_defineProperty(Menu, "defaultProps", defaultProps$7);
_defineProperty(Menu, "Divider", MenuDivider);
_defineProperty(Menu, "Header", MenuHeader);
var propTypes$a = {
/**
* Provides the ability to specify a prefix before the user-entered text to
* indicate that the selection will be new. No-op unless `allowNew={true}`.
*/
newSelectionPrefix: propTypes.string,
/**
* Prompt displayed when large data sets are paginated.
*/
paginationText: propTypes.string,
/**
* Provides a hook for customized rendering of menu item contents.
*/
renderMenuItemChildren: propTypes.func
};
var defaultProps$8 = {
newSelectionPrefix: 'New selection: ',
paginationText: 'Display additional results...',
renderMenuItemChildren: function renderMenuItemChildren(option, props, idx) {
return React__default.createElement(Highlighter, {
search: props.text
}, getOptionLabel(option, props.labelKey));
}
};
var TypeaheadMenu = function TypeaheadMenu(props) {
var labelKey = props.labelKey,
newSelectionPrefix = props.newSelectionPrefix,
options = props.options,
paginationText = props.paginationText,
renderMenuItemChildren = props.renderMenuItemChildren,
text = props.text,
menuProps = _objectWithoutPropertiesLoose(props, ["labelKey", "newSelectionPrefix", "options", "paginationText", "renderMenuItemChildren", "text"]);
var renderMenuItem = React.useCallback(function (option, position) {
var label = getOptionLabel(option, labelKey);
var menuItemProps = {
disabled: getOptionProperty(option, 'disabled'),
label: label,
option: option,
position: position
};
if (option.customOption) {
return React__default.createElement(MenuItem, _extends({}, menuItemProps, {
className: "rbt-menu-custom-option",
key: position,
label: newSelectionPrefix + label
}), newSelectionPrefix, React__default.createElement(Highlighter, {
search: text
}, label));
}
if (option.paginationOption) {
return React__default.createElement(React.Fragment, {
key: "pagination-item"
}, React__default.createElement(Menu.Divider, null), React__default.createElement(MenuItem, _extends({}, menuItemProps, {
className: "rbt-menu-pagination-option",
label: paginationText
}), paginationText));
}
return React__default.createElement(MenuItem, _extends({}, menuItemProps, {
key: position
}), renderMenuItemChildren(option, props, position));
});
return (// Explictly pass `text` so Flow doesn't complain...
React__default.createElement(Menu, _extends({}, menuProps, {
text: text
}), options.map(renderMenuItem))
);
};
TypeaheadMenu.propTypes = propTypes$a;
TypeaheadMenu.defaultProps = defaultProps$8;
var propTypes$b = {
/**
* Displays a button to clear the input when there are selections.
*/
clearButton: propTypes.bool,
/**
* Props to be applied directly to the input. `onBlur`, `onChange`,
* `onFocus`, and `onKeyDown` are ignored.
*/
inputProps: checkPropType(propTypes.object, inputPropsType),
/**
* Bootstrap 4 only. Adds the `is-invalid` classname to the `form-control`.
*/
isInvalid: propTypes.bool,
/**
* Indicate whether an asynchronous data fetch is happening.
*/
isLoading: propTypes.bool,
/**
* Bootstrap 4 only. Adds the `is-valid` classname to the `form-control`.
*/
isValid: propTypes.bool,
/**
* Callback for custom input rendering.
*/
renderInput: propTypes.func,
/**
* Callback for custom menu rendering.
*/
renderMenu: propTypes.func,
/**
* Callback for custom menu rendering.
*/
renderToken: propTypes.func,
/**
* Specifies the size of the input.
*/
size: sizeType
};
var defaultProps$9 = {
clearButton: false,
inputProps: {},
isInvalid: false,
isLoading: false,
isValid: false,
renderMenu: function renderMenu(results, menuProps, props) {
return React.createElement(TypeaheadMenu, _extends({}, menuProps, {
labelKey: props.labelKey,
options: results,
text: props.text
}));
},
renderToken: function renderToken(option, props, idx) {
return React.createElement(Token$1, {
disabled: props.disabled,
key: idx,
onRemove: props.onRemove,
option: option,
tabIndex: props.tabIndex
}, getOptionLabel(option, props.labelKey));
}
};
function getOverlayProps(props) {
return pick(props, ['align', 'dropup', 'flip', 'positionFixed']);
}
var TypeaheadComponent = /*#__PURE__*/function (_React$Component) {
_inheritsLoose(TypeaheadComponent, _React$Component);
function TypeaheadComponent() {
var _this;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;
_defineProperty(_assertThisInitialized(_this), "_instance", void 0);
_defineProperty(_assertThisInitialized(_this), "_referenceElement", void 0);
_defineProperty(_assertThisInitialized(_this), "getInstance", function () {
return _this._instance;
});
_defineProperty(_assertThisInitialized(_this), "referenceElementRef", function (referenceElement) {
_this._referenceElement = referenceElement;
});
_defineProperty(_assertThisInitialized(_this), "_renderInput", function (inputProps, props) {
var _this$props = _this.props,
isInvalid = _this$props.isInvalid,
isValid = _this$props.isValid,
multiple = _this$props.multiple,
renderInput = _this$props.renderInput,
renderToken = _this$props.renderToken,
size = _this$props.size;
if (isFunction(renderInput)) {
return renderInput(inputProps, props);
}
var commonProps = _extends({}, inputProps, {
isInvalid: isInvalid,
isValid: isValid,
size: size
});
if (!multiple) {
return React.createElement(TypeaheadInputSingle, commonProps);
}
var labelKey = props.labelKey,
onRemove = props.onRemove,
selected = props.selected;
return React.createElement(TypeaheadInputMulti$1, _extends({}, commonProps, {
selected: selected
}), selected.map(function (option, idx) {
return renderToken(option, _extends({}, commonProps, {
labelKey: labelKey,
onRemove: onRemove
}), idx);
}));
});
_defineProperty(_assertThisInitialized(_this), "_renderMenu", function (results, menuProps, props) {
var _this$props2 = _this.props,
emptyLabel = _this$props2.emptyLabel,
id = _this$props2.id,
maxHeight = _this$props2.maxHeight,
newSelectionPrefix = _this$props2.newSelectionPrefix,
paginationText = _this$props2.paginationText,
renderMenu = _this$props2.renderMenu,
renderMenuItemChildren = _this$props2.renderMenuItemChildren;
return renderMenu(results, _extends({}, menuProps, {
emptyLabel: emptyLabel,
id: id,
maxHeight: maxHeight,
newSelectionPrefix: newSelectionPrefix,
paginationText: paginationText,
renderMenuItemChildren: renderMenuItemChildren
}), props);
});
_defineProperty(_assertThisInitialized(_this), "_renderAux", function (_ref) {
var onClear = _ref.onClear,
selected = _ref.selected;
var _this$props3 = _this.props,
clearButton = _this$props3.clearButton,
disabled = _this$props3.disabled,
isLoading = _this$props3.isLoading,
size = _this$props3.size;
var content;
if (isLoading) {
content = React.createElement(Loader, null);
} else if (clearButton && !disabled && selected.length) {
content = React.createElement(ClearButton, {
onClick: onClear,
onFocus: function onFocus(e) {
// Prevent the main input from auto-focusing again.
e.stopPropagation();
},
onMouseDown: preventInputBlur,
size: size
});
}
return content ? React.createElement("div", {
className: classnames('rbt-aux', {
'rbt-aux-lg': isSizeLarge(size)
})
}, content) : null;
});
return _this;
}
var _proto = TypeaheadComponent.prototype;
_proto.render = function render() {
var _this2 = this;
// Explicitly pass `options` so Flow doesn't complain...
var _this$props4 = this.props,
children = _this$props4.children,
className = _this$props4.className,
open = _this$props4.open,
options = _this$props4.options,
style = _this$props4.style;
return React.createElement(Typeahead, _extends({}, this.props, {
options: options,
ref: function ref(instance) {
return _this2._instance = instance;
}
}), function (_ref2) {
var getInputProps = _ref2.getInputProps,
props = _objectWithoutPropertiesLoose(_ref2, ["getInputProps"]);
var isMenuShown = props.isMenuShown,
onHide = props.onHide,
results = props.results;
var auxContent = _this2._renderAux(props);
return React.createElement(RootClose, {
disabled: open || !isMenuShown,
onRootClose: onHide
}, function (ref) {
return React.createElement("div", {
className: classnames('rbt', {
'has-aux': !!auxContent
}, className),
ref: ref,
style: _extends({}, style, {
outline: 'none',
position: 'relative'
}),
tabIndex: -1
}, _this2._renderInput(_extends({}, getInputProps(_this2.props.inputProps), {
referenceElementRef: _this2.referenceElementRef
}), props), React.createElement(Overlay, _extends({}, getOverlayProps(_this2.props), {
isMenuShown: isMenuShown,
referenceElement: _this2._referenceElement
}), function (menuProps) {
return _this2._renderMenu(results, menuProps, props);
}), auxContent, isFunction(children) ? children(props) : children);
});
});
};
return TypeaheadComponent;
}(React.Component);
_defineProperty(TypeaheadComponent, "propTypes", propTypes$b);
_defineProperty(TypeaheadComponent, "defaultProps", defaultProps$9);
var AsyncTypeahead_react = asyncContainer(TypeaheadComponent);
exports.AsyncTypeahead = AsyncTypeahead_react;
exports.ClearButton = ClearButton;
exports.Highlighter = Highlighter;
exports.Hint = Hint;
exports.Input = Input;
exports.Loader = Loader;
exports.Menu = Menu;
exports.MenuItem = MenuItem;
exports.Token = Token$1;
exports.Typeahead = TypeaheadComponent;
exports.TypeaheadInputMulti = TypeaheadInputMulti$1;
exports.TypeaheadInputSingle = TypeaheadInputSingle;
exports.TypeaheadMenu = TypeaheadMenu;
exports.asyncContainer = asyncContainer;
exports.menuItemContainer = menuItemContainer;
exports.tokenContainer = tokenContainer;
Object.defineProperty(exports, '__esModule', { value: true });
})));
|
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is JavaScript Engine testing utilities.
*
* The Initial Developer of the Original Code is
* Mozilla Foundation.
* Portions created by the Initial Developer are Copyright (C) 2005
* the Initial Developer. All Rights Reserved.
*
* Contributor(s): nanto_vi
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
//-----------------------------------------------------------------------------
var BUGNUMBER = 306591;
var summary = 'String static methods';
var actual = '';
var expect = '';
printBugNumber(BUGNUMBER);
printStatus (summary);
printStatus ('See https://bugzilla.mozilla.org/show_bug.cgi?id=304828');
expect = ['a', 'b', 'c'].toString();
actual = String.split(new String('abc'), '').toString();
reportCompare(expect, actual, summary +
" String.split(new String('abc'), '')");
expect = '2';
actual = String.substring(new Number(123), 1, 2);
reportCompare(expect, actual, summary +
" String.substring(new Number(123), 1, 2)");
expect = 'TRUE';
actual = String.toUpperCase(new Boolean(true));
reportCompare(expect, actual, summary +
" String.toUpperCase(new Boolean(true))");
// null means the global object is passed
expect = (typeof window == 'undefined') ? 9 : -1;
actual = String.indexOf(null, 'l');
reportCompare(expect, actual, summary +
" String.indexOf(null, 'l')");
expect = 2;
actual = String.indexOf(String(null), 'l');
reportCompare(expect, actual, summary +
" String.indexOf(String(null), 'l')");
expect = ['a', 'b', 'c'].toString();
actual = String.split('abc', '').toString();
reportCompare(expect, actual, summary +
" String.split('abc', '')");
expect = '2';
actual = String.substring(123, 1, 2);
reportCompare(expect, actual, summary +
" String.substring(123, 1, 2)");
expect = 'TRUE';
actual = String.toUpperCase(true);
reportCompare(expect, actual, summary +
" String.toUpperCase(true)");
// null means the global object is passed
expect = (typeof window == 'undefined') ? -1 : 11;
actual = String.indexOf(undefined, 'd');
reportCompare(expect, actual, summary +
" String.indexOf(undefined, 'd')");
expect = 2;
actual = String.indexOf(String(undefined), 'd');
reportCompare(expect, actual, summary +
" String.indexOf(String(undefined), 'd')");
|
import SliderAutoplay from './slider-autoplay';
import SliderDrag from './slider-drag';
import SliderNav from './slider-nav';
import {$, assign, clamp, fastdom, getIndex, hasClass, isNumber, isRtl, Promise, removeClass, toNodes, trigger} from 'uikit-util';
export default {
mixins: [SliderAutoplay, SliderDrag, SliderNav],
props: {
clsActivated: Boolean,
easing: String,
index: Number,
finite: Boolean,
velocity: Number
},
data: () => ({
easing: 'ease',
finite: false,
velocity: 1,
index: 0,
prevIndex: -1,
stack: [],
percent: 0,
clsActive: 'uk-active',
clsActivated: false,
Transitioner: false,
transitionOptions: {}
}),
connected() {
this.prevIndex = -1;
this.index = this.getValidIndex(this.index);
this.stack = [];
},
disconnected() {
removeClass(this.slides, this.clsActive);
},
computed: {
duration({velocity}, $el) {
return speedUp($el.offsetWidth / velocity);
},
list({selList}, $el) {
return $(selList, $el);
},
maxIndex() {
return this.length - 1;
},
selSlides({selList}) {
return `${selList} > *`;
},
slides: {
get() {
return toNodes(this.list.children);
},
watch() {
this.$reset();
}
},
length() {
return this.slides.length;
}
},
events: {
itemshown() {
this.$update(this.list);
}
},
methods: {
show(index, force = false) {
if (this.dragging || !this.length) {
return;
}
const {stack} = this;
const queueIndex = force ? 0 : stack.length;
const reset = () => {
stack.splice(queueIndex, 1);
if (stack.length) {
this.show(stack.shift(), true);
}
};
stack[force ? 'unshift' : 'push'](index);
if (!force && stack.length > 1) {
if (stack.length === 2) {
this._transitioner.forward(Math.min(this.duration, 200));
}
return;
}
const prevIndex = this.index;
const prev = hasClass(this.slides, this.clsActive) && this.slides[prevIndex];
const nextIndex = this.getIndex(index, this.index);
const next = this.slides[nextIndex];
if (prev === next) {
reset();
return;
}
this.dir = getDirection(index, prevIndex);
this.prevIndex = prevIndex;
this.index = nextIndex;
prev && trigger(prev, 'beforeitemhide', [this]);
if (!trigger(next, 'beforeitemshow', [this, prev])) {
this.index = this.prevIndex;
reset();
return;
}
const promise = this._show(prev, next, force).then(() => {
prev && trigger(prev, 'itemhidden', [this]);
trigger(next, 'itemshown', [this]);
return new Promise(resolve => {
fastdom.write(() => {
stack.shift();
if (stack.length) {
this.show(stack.shift(), true);
} else {
this._transitioner = null;
}
resolve();
});
});
});
prev && trigger(prev, 'itemhide', [this]);
trigger(next, 'itemshow', [this]);
return promise;
},
getIndex(index = this.index, prev = this.index) {
return clamp(getIndex(index, this.slides, prev, this.finite), 0, this.maxIndex);
},
getValidIndex(index = this.index, prevIndex = this.prevIndex) {
return this.getIndex(index, prevIndex);
},
_show(prev, next, force) {
this._transitioner = this._getTransitioner(
prev,
next,
this.dir,
assign({
easing: force
? next.offsetWidth < 600
? 'cubic-bezier(0.25, 0.46, 0.45, 0.94)' /* easeOutQuad */
: 'cubic-bezier(0.165, 0.84, 0.44, 1)' /* easeOutQuart */
: this.easing
}, this.transitionOptions)
);
if (!force && !prev) {
this._transitioner.translate(1);
return Promise.resolve();
}
const {length} = this.stack;
return this._transitioner[length > 1 ? 'forward' : 'show'](length > 1 ? Math.min(this.duration, 75 + 75 / (length - 1)) : this.duration, this.percent);
},
_getDistance(prev, next) {
return this._getTransitioner(prev, prev !== next && next).getDistance();
},
_translate(percent, prev = this.prevIndex, next = this.index) {
const transitioner = this._getTransitioner(prev !== next ? prev : false, next);
transitioner.translate(percent);
return transitioner;
},
_getTransitioner(prev = this.prevIndex, next = this.index, dir = this.dir || 1, options = this.transitionOptions) {
return new this.Transitioner(
isNumber(prev) ? this.slides[prev] : prev,
isNumber(next) ? this.slides[next] : next,
dir * (isRtl ? -1 : 1),
options
);
}
}
};
function getDirection(index, prevIndex) {
return index === 'next'
? 1
: index === 'previous'
? -1
: index < prevIndex
? -1
: 1;
}
export function speedUp(x) {
return .5 * x + 300; // parabola through (400,500; 600,600; 1800,1200)
}
|
module.exports={A:{A:{"2":"K C G E A B CB"},B:{"1":"D u Y I M H"},C:{"1":"0 2 3 4 5 6 7 j k l m n o p q r s t y z v","2":"1 VB F J K C G E A B D u Y I M H N O P Q R S T U V W X w Z a b c d e f L h i TB SB"},D:{"1":"0 2 3 4 5 6 7 k l m n o p q r s t y z v HB g DB XB EB FB","2":"F J K C G E A B D u Y I M H N O P Q R S T U V W X w Z a b c d e f L h i j"},E:{"1":"E A B LB MB NB","2":"F J K C G GB AB IB JB KB"},F:{"1":"X w Z a b c d e f L h i j k l m n o p q r s t","2":"8 9 E B D I M H N O P Q R S T U V W OB PB QB RB UB x"},G:{"1":"cB dB eB fB gB","2":"G AB WB BB YB ZB aB bB"},H:{"2":"hB"},I:{"1":"g","2":"1 F iB jB kB lB BB mB nB"},J:{"2":"C","16":"A"},K:{"1":"L","2":"8 9 A B D x"},L:{"1":"g"},M:{"1":"v"},N:{"2":"A B"},O:{"2":"oB"},P:{"1":"F J pB"},Q:{"2":"qB"},R:{"1":"rB"}},B:6,C:"String.prototype.includes"};
|
var shouldArr =
[100, 100, 100, 255,
100, 100, 100, 255,
100, 100, 100, 255,
100, 100, 100, 255];
var tempArr =
[50, 100, 150, 255,
50, 100, 150, 255,
50, 100, 150, 255,
50, 100, 150, 255];
describe('ColorChanger', function () {
describe('changeColor', function () {
it('should equal [100, 100, 100, 255]', function () {
var tempElem = getTempElem(tempArr);
var opt = {
from: {
r: 50,
g: 100,
b: 150
},
to: {
r: 100,
g: 100,
b: 100
}
};
var colorChanger = new ColorChanger(tempElem, opt);
colorChanger.changeColor();
expect(getData(tempElem).data).to.eql(shouldArr);
});
it('should equal [100, 100, 100, 255]', function () {
var tempElem = getTempElem(tempArr);
var opt = {
from: {
r: {great: 0},
g: {less: 150},
b: {great: 100, less: 200}
},
to: {
r: 100,
g: 100,
b: 100
}
};
var colorChanger = new ColorChanger(tempElem, opt);
colorChanger.changeColor();
expect(getData(tempElem).data).to.eql(shouldArr);
});
it('should equal [100, 100, 100, 255]', function () {
var tempElem = getTempElem(tempArr);
var opt = {
to: {
r: 100,
g: 100,
b: 100
}
};
var colorChanger = new ColorChanger(tempElem, opt);
colorChanger.changeColor();
expect(getData(tempElem).data).to.eql(shouldArr);
});
it('should equal [100, 100, 100, 255]', function () {
var tempElem = getTempElem(tempArr);
var opt = {
from: {
r: 50,
g: 100,
b: 150
},
to: {
r: {plus: 50},
g: {plus: 50, minus: 50},
b: {minus: 50}
}
};
var colorChanger = new ColorChanger(tempElem, opt);
colorChanger.changeColor();
expect(getData(tempElem).data).to.eql(shouldArr);
});
});
describe('changeOriginal', function () {
it('should equal [50, 100, 150, 255]', function () {
var tempElem = getTempElem(tempArr);
var opt = {
from: {
r: 50,
g: 100,
b: 150
},
to: {
r: 255,
g: 255,
b: 255
}
};
var colorChanger = new ColorChanger(tempElem, opt);
colorChanger.changeColor();
colorChanger.changeOriginal();
expect(getData(tempElem).data).to.eql(tempArr);
});
});
});
function getTempElem(tempArr) {
var canvas = document.createElement('canvas');
var tempElem = document.createElement('img');
tempElem.width = 2;
tempElem.height = 2;
var tempData = canvas.getContext('2d').createImageData(2, 2);
for (var i = 0; i < tempArr.length; i++) {
tempData.data[i] = tempArr[i];
}
setData(tempElem, tempData, 'png');
return tempElem;
}
function getData(elem) {
var data;
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
canvas.width = elem.width;
canvas.height = elem.height;
ctx.drawImage(elem, 0, 0, elem.naturalWidth, elem.naturalHeight, 0, 0, elem.width, elem.height);
data = ctx.getImageData(0, 0, elem.width, elem.height);
elem.onload = false;
return data;
}
function setData(elem, data, extname) {
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
canvas.width = elem.width;
canvas.height = elem.height;
ctx.putImageData(data, 0, 0);
elem.src = canvas.toDataURL('image/' + extname);
}
|
// nothing to see here
var chai = require('chai');
var should = chai.should();
var name = 'peter parker';
describe('BDD', function() {
describe('Check the type', function() {
it('Test for string', function() {
name.should.be.a('string');
});
});
});
describe('BDD', function() {
describe('Is the name correct?', function() {
it('Test for Peter Parker', function() {
name.should.equal('peter parker');
});
});
});
|
// Rule Test Cases
// -----------------------------
// Modules Dependencies:
// - Assert (http://nodejs.org/api/assert.html)
var assert = require('assert');
// Require basic config files and DB connection
require('../../../utils/dbconnect');
// Global Variables for the test case
var Rule, rule;
// Unit Tests
describe('Model Test Rule', function(){
before(function(){
// Before all tests
Rule = require("../../../models/rule.js");
});
describe('Rule', function(){
// It show create a new document in the database
it('add a rule', function(done){
rule = new Rule({ name: 'rule'+Math.floor((Math.random() * 10) + 1)});
rule.save(done);
});
});
});
|
//在about也页面上显示的幸运话
var fortuneCookies = [
"Conquer your fears or they will conquer you.",
"Rivers need springs.",
"Do not fear what you don't konow",
"You will have a pleasant surprise",
"wheneven possible, keep is simple"
];
exports.getFortune = function () {
var idx = Math.floor(Math.random() * fortuneCookies.length);
return fortuneCookies[idx];
} |
var expect = require('chai').expect;
var _ = require('lodash');
var getReadableStream = require('../../_utilities/getReadableStream.js');
var runBasicStreamTests = require('../../_utilities/runBasicStreamTests.js');
var waitObj = require('../../../').wait.obj;
describe('[v2-waitObj]', function () {
var data = ['item1', new Buffer('item2'), 'item3', 'item4'];
var expected = ['item1', 'item2', 'item3', 'item4'];
var objData = [true, 'item', 5, { obj: 'mode' }, [1, 2, 3]];
function runTest(stream, objectMode, done) {
var actual = [];
stream
.pipe(waitObj())
.on('data', function (chunk) {
actual.push(chunk);
})
.on('error', done)
.on('end', function () {
expect(actual).to.have.lengthOf(1);
if (objectMode) {
expect(actual[0]).to.deep.equal(objData);
} else {
expect(actual[0]).to.deep.equal(expected.map(function (item) {
return new Buffer(item);
}));
}
done();
});
}
runBasicStreamTests(data, objData, runTest);
it('optionally provides data to a callback', function (done) {
var stream = getReadableStream(objData, {
objectMode: true
});
var actual = {
callback: [],
event: []
};
var doneCount = 0;
function onDone() {
doneCount += 1;
if (doneCount >= 2) {
expect(actual.callback).to.have.lengthOf(1);
expect(actual.event).to.have.lengthOf(1);
// If they're both the same we have succeeded
expect(actual.callback).to.deep.equal(actual.event);
expect(actual.callback[0]).to.deep.equal(objData);
done();
}
}
stream
.pipe(waitObj(function (err, chunk) {
expect(err).to.equal(null);
actual.callback.push(chunk);
onDone();
}))
.on('data', function (chunk) {
actual.event.push(chunk);
})
.on('error', done)
.on('end', onDone);
});
it('reads the entire stream when given a callback', function (done) {
var testData = _.times(100);
var stream = getReadableStream(testData, {
objectMode: true
});
stream
.pipe(waitObj(function (err, chunk) {
expect(err).to.equal(null);
expect(chunk).to.deep.equal(testData);
done();
}));
});
});
|
/**
* @license Copyright (c) 2013, Viet Trinh All Rights Reserved.
* Available via MIT license.
*/
/**
* A server users users_view_server handler.
*/
define([ 'framework/request/base_request_handler',
'../users_view_server_request',
'framework/core/deferred/deferred',
'framework/core/utils/clazz' ],
function(BaseRequestHandler,
UsersViewServerRequest,
Deferred,
ClazzUtils)
{
var UsersViewServerHandler = BaseRequestHandler.create(UsersViewServerRequest, [ 'userRepository' ]);
// @override
UsersViewServerHandler.prototype.execute = function(requestContext, request, response)
{
return this._remotePromise(requestContext, this._userRepository.getById(request.getId())).then(function(user)
{
ClazzUtils.copyProperties(user, response);
return Deferred.resolvedPromise(requestContext);
});
};
return UsersViewServerHandler;
}); |
/*global moment: false*/
$(function () {
var sub = $('#sub').prop('checked');
$('#modify').click(function (e) {
if ($('#sub').prop('checked') === sub) {
$('#message').append('<div class="alert alert-info"><button class="close" data-dismiss="alert">x</button>The subscription state was not changed.</div>');
} else {
sub = $('#sub').prop('checked');
var request = $.ajax({
type: 'PUT',
async: true,
data: JSON.stringify({
subscribe: sub
}),
contentType: 'application/json',
processData: false,
dataType: 'json'
}).done(function (json) {
var timestamp = request.getResponseHeader('Date');
var dateObj = moment(timestamp);
$('#message').append('<div class="alert alert-info"><button class="close" data-dismiss="alert">x</button>The modification was saved at ' + dateObj.format('HH:mm:ss') + '.</div>');
}).fail(function (jqXHR, status, error) {
$('#message').append('<div class="alert alert-info"><button class="close" data-dismiss="alert">x</button>The modification request failed. You might need to try again or contact the admin.</div>');
});
}
e.preventDefault();
});
});
|
'use strict';
var string = /"([^"]+)?"/;
module.exports = [
{type: 'command', regex: /(?:click|close|find|get|include|quit|refresh|set|sleep|submit|type)(?=\s|$)/},
{type: 'in', regex: /(?:in)(?=\s)/},
{type: 'operator', regex: /(?:equal|or|and)(?=\s)/},
{type: 'string', regex: string},
{type: 'number', regex: /[0-9]+(?:\.[0-9]+)?/},
{type: 'variable', regex: /[a-zA-Z]{1,}(?:(?:\.[a-z0-9_A-Z]+)+|[a-z0-9_A-Z]+)?/},
{type: 'space', regex: /\s+/}
];
|
/*!
* jquery.fancytree.js
* Tree view control with support for lazy loading and much more.
* https://github.com/mar10/fancytree/
*
* Copyright (c) 2008-2020, Martin Wendt (https://wwWendt.de)
* Released under the MIT license
* https://github.com/mar10/fancytree/wiki/LicenseInfo
*
* @version 2.37.0
* @date 2020-09-11T18:58:08Z
*/
/** Core Fancytree module.
*/
// UMD wrapper for the Fancytree core module
(function(factory) {
if (typeof define === "function" && define.amd) {
// AMD. Register as an anonymous module.
define(["jquery", "./jquery.fancytree.ui-deps"], factory);
} else if (typeof module === "object" && module.exports) {
// Node/CommonJS
require("./jquery.fancytree.ui-deps");
module.exports = factory(require("jquery"));
} else {
// Browser globals
factory(jQuery);
}
})(function($) {
"use strict";
// prevent duplicate loading
if ($.ui && $.ui.fancytree) {
$.ui.fancytree.warn("Fancytree: ignored duplicate include");
return;
}
/******************************************************************************
* Private functions and variables
*/
var i,
attr,
FT = null, // initialized below
TEST_IMG = new RegExp(/\.|\//), // strings are considered image urls if they contain '.' or '/'
REX_HTML = /[&<>"'/]/g, // Escape those characters
REX_TOOLTIP = /[<>"'/]/g, // Don't escape `&` in tooltips
RECURSIVE_REQUEST_ERROR = "$recursive_request",
INVALID_REQUEST_TARGET_ERROR = "$request_target_invalid",
ENTITY_MAP = {
"&": "&",
"<": "<",
">": ">",
'"': """,
"'": "'",
"/": "/",
},
IGNORE_KEYCODES = { 16: true, 17: true, 18: true },
SPECIAL_KEYCODES = {
8: "backspace",
9: "tab",
10: "return",
13: "return",
// 16: null, 17: null, 18: null, // ignore shift, ctrl, alt
19: "pause",
20: "capslock",
27: "esc",
32: "space",
33: "pageup",
34: "pagedown",
35: "end",
36: "home",
37: "left",
38: "up",
39: "right",
40: "down",
45: "insert",
46: "del",
59: ";",
61: "=",
// 91: null, 93: null, // ignore left and right meta
96: "0",
97: "1",
98: "2",
99: "3",
100: "4",
101: "5",
102: "6",
103: "7",
104: "8",
105: "9",
106: "*",
107: "+",
109: "-",
110: ".",
111: "/",
112: "f1",
113: "f2",
114: "f3",
115: "f4",
116: "f5",
117: "f6",
118: "f7",
119: "f8",
120: "f9",
121: "f10",
122: "f11",
123: "f12",
144: "numlock",
145: "scroll",
173: "-",
186: ";",
187: "=",
188: ",",
189: "-",
190: ".",
191: "/",
192: "`",
219: "[",
220: "\\",
221: "]",
222: "'",
},
MODIFIERS = {
16: "shift",
17: "ctrl",
18: "alt",
91: "meta",
93: "meta",
},
MOUSE_BUTTONS = { 0: "", 1: "left", 2: "middle", 3: "right" },
// Boolean attributes that can be set with equivalent class names in the LI tags
// Note: v2.23: checkbox and hideCheckbox are *not* in this list
CLASS_ATTRS = "active expanded focus folder lazy radiogroup selected unselectable unselectableIgnore".split(
" "
),
CLASS_ATTR_MAP = {},
// Top-level Fancytree attributes, that can be set by dict
TREE_ATTRS = "columns types".split(" "),
// TREE_ATTR_MAP = {},
// Top-level FancytreeNode attributes, that can be set by dict
NODE_ATTRS = "checkbox expanded extraClasses folder icon iconTooltip key lazy partsel radiogroup refKey selected statusNodeType title tooltip type unselectable unselectableIgnore unselectableStatus".split(
" "
),
NODE_ATTR_MAP = {},
// Mapping of lowercase -> real name (because HTML5 data-... attribute only supports lowercase)
NODE_ATTR_LOWERCASE_MAP = {},
// Attribute names that should NOT be added to node.data
NONE_NODE_DATA_MAP = {
active: true,
children: true,
data: true,
focus: true,
};
for (i = 0; i < CLASS_ATTRS.length; i++) {
CLASS_ATTR_MAP[CLASS_ATTRS[i]] = true;
}
for (i = 0; i < NODE_ATTRS.length; i++) {
attr = NODE_ATTRS[i];
NODE_ATTR_MAP[attr] = true;
if (attr !== attr.toLowerCase()) {
NODE_ATTR_LOWERCASE_MAP[attr.toLowerCase()] = attr;
}
}
// for(i=0; i<TREE_ATTRS.length; i++) {
// TREE_ATTR_MAP[TREE_ATTRS[i]] = true;
// }
function _assert(cond, msg) {
// TODO: see qunit.js extractStacktrace()
if (!cond) {
msg = msg ? ": " + msg : "";
// consoleApply("assert", [!!cond, msg]);
$.error("Fancytree assertion failed" + msg);
}
}
_assert($.ui, "Fancytree requires jQuery UI (http://jqueryui.com)");
function consoleApply(method, args) {
var i,
s,
fn = window.console ? window.console[method] : null;
if (fn) {
try {
fn.apply(window.console, args);
} catch (e) {
// IE 8?
s = "";
for (i = 0; i < args.length; i++) {
s += args[i];
}
fn(s);
}
}
}
/* support: IE8 Polyfil for Date.now() */
if (!Date.now) {
Date.now = function now() {
return new Date().getTime();
};
}
/*Return true if x is a FancytreeNode.*/
function _isNode(x) {
return !!(x.tree && x.statusNodeType !== undefined);
}
/** Return true if dotted version string is equal or higher than requested version.
*
* See http://jsfiddle.net/mar10/FjSAN/
*/
function isVersionAtLeast(dottedVersion, major, minor, patch) {
var i,
v,
t,
verParts = $.map($.trim(dottedVersion).split("."), function(e) {
return parseInt(e, 10);
}),
testParts = $.map(
Array.prototype.slice.call(arguments, 1),
function(e) {
return parseInt(e, 10);
}
);
for (i = 0; i < testParts.length; i++) {
v = verParts[i] || 0;
t = testParts[i] || 0;
if (v !== t) {
return v > t;
}
}
return true;
}
/**
* Deep-merge a list of objects (but replace array-type options).
*
* jQuery's $.extend(true, ...) method does a deep merge, that also merges Arrays.
* This variant is used to merge extension defaults with user options, and should
* merge objects, but override arrays (for example the `triggerStart: [...]` option
* of ext-edit). Also `null` values are copied over and not skipped.
*
* See issue #876
*
* Example:
* _simpleDeepMerge({}, o1, o2);
*/
function _simpleDeepMerge() {
var options,
name,
src,
copy,
clone,
target = arguments[0] || {},
i = 1,
length = arguments.length;
// Handle case when target is a string or something (possible in deep copy)
if (typeof target !== "object" && !$.isFunction(target)) {
target = {};
}
if (i === length) {
throw Error("need at least two args");
}
for (; i < length; i++) {
// Only deal with non-null/undefined values
if ((options = arguments[i]) != null) {
// Extend the base object
for (name in options) {
if (options.hasOwnProperty(name)) {
src = target[name];
copy = options[name];
// Prevent never-ending loop
if (target === copy) {
continue;
}
// Recurse if we're merging plain objects
// (NOTE: unlike $.extend, we don't merge arrays, but replace them)
if (copy && $.isPlainObject(copy)) {
clone = src && $.isPlainObject(src) ? src : {};
// Never move original objects, clone them
target[name] = _simpleDeepMerge(clone, copy);
// Don't bring in undefined values
} else if (copy !== undefined) {
target[name] = copy;
}
}
}
}
}
// Return the modified object
return target;
}
/** Return a wrapper that calls sub.methodName() and exposes
* this : tree
* this._local : tree.ext.EXTNAME
* this._super : base.methodName.call()
* this._superApply : base.methodName.apply()
*/
function _makeVirtualFunction(methodName, tree, base, extension, extName) {
// $.ui.fancytree.debug("_makeVirtualFunction", methodName, tree, base, extension, extName);
// if(rexTestSuper && !rexTestSuper.test(func)){
// // extension.methodName() doesn't call _super(), so no wrapper required
// return func;
// }
// Use an immediate function as closure
var proxy = (function() {
var prevFunc = tree[methodName], // org. tree method or prev. proxy
baseFunc = extension[methodName], //
_local = tree.ext[extName],
_super = function() {
return prevFunc.apply(tree, arguments);
},
_superApply = function(args) {
return prevFunc.apply(tree, args);
};
// Return the wrapper function
return function() {
var prevLocal = tree._local,
prevSuper = tree._super,
prevSuperApply = tree._superApply;
try {
tree._local = _local;
tree._super = _super;
tree._superApply = _superApply;
return baseFunc.apply(tree, arguments);
} finally {
tree._local = prevLocal;
tree._super = prevSuper;
tree._superApply = prevSuperApply;
}
};
})(); // end of Immediate Function
return proxy;
}
/**
* Subclass `base` by creating proxy functions
*/
function _subclassObject(tree, base, extension, extName) {
// $.ui.fancytree.debug("_subclassObject", tree, base, extension, extName);
for (var attrName in extension) {
if (typeof extension[attrName] === "function") {
if (typeof tree[attrName] === "function") {
// override existing method
tree[attrName] = _makeVirtualFunction(
attrName,
tree,
base,
extension,
extName
);
} else if (attrName.charAt(0) === "_") {
// Create private methods in tree.ext.EXTENSION namespace
tree.ext[extName][attrName] = _makeVirtualFunction(
attrName,
tree,
base,
extension,
extName
);
} else {
$.error(
"Could not override tree." +
attrName +
". Use prefix '_' to create tree." +
extName +
"._" +
attrName
);
}
} else {
// Create member variables in tree.ext.EXTENSION namespace
if (attrName !== "options") {
tree.ext[extName][attrName] = extension[attrName];
}
}
}
}
function _getResolvedPromise(context, argArray) {
if (context === undefined) {
return $.Deferred(function() {
this.resolve();
}).promise();
}
return $.Deferred(function() {
this.resolveWith(context, argArray);
}).promise();
}
function _getRejectedPromise(context, argArray) {
if (context === undefined) {
return $.Deferred(function() {
this.reject();
}).promise();
}
return $.Deferred(function() {
this.rejectWith(context, argArray);
}).promise();
}
function _makeResolveFunc(deferred, context) {
return function() {
deferred.resolveWith(context);
};
}
function _getElementDataAsDict($el) {
// Evaluate 'data-NAME' attributes with special treatment for 'data-json'.
var d = $.extend({}, $el.data()),
json = d.json;
delete d.fancytree; // added to container by widget factory (old jQuery UI)
delete d.uiFancytree; // added to container by widget factory
if (json) {
delete d.json;
// <li data-json='...'> is already returned as object (http://api.jquery.com/data/#data-html5)
d = $.extend(d, json);
}
return d;
}
function _escapeTooltip(s) {
return ("" + s).replace(REX_TOOLTIP, function(s) {
return ENTITY_MAP[s];
});
}
// TODO: use currying
function _makeNodeTitleMatcher(s) {
s = s.toLowerCase();
return function(node) {
return node.title.toLowerCase().indexOf(s) >= 0;
};
}
function _makeNodeTitleStartMatcher(s) {
var reMatch = new RegExp("^" + s, "i");
return function(node) {
return reMatch.test(node.title);
};
}
/******************************************************************************
* FancytreeNode
*/
/**
* Creates a new FancytreeNode
*
* @class FancytreeNode
* @classdesc A FancytreeNode represents the hierarchical data model and operations.
*
* @param {FancytreeNode} parent
* @param {NodeData} obj
*
* @property {Fancytree} tree The tree instance
* @property {FancytreeNode} parent The parent node
* @property {string} key Node id (must be unique inside the tree)
* @property {string} title Display name (may contain HTML)
* @property {object} data Contains all extra data that was passed on node creation
* @property {FancytreeNode[] | null | undefined} children Array of child nodes.<br>
* For lazy nodes, null or undefined means 'not yet loaded'. Use an empty array
* to define a node that has no children.
* @property {boolean} expanded Use isExpanded(), setExpanded() to access this property.
* @property {string} extraClasses Additional CSS classes, added to the node's `<span>`.<br>
* Note: use `node.add/remove/toggleClass()` to modify.
* @property {boolean} folder Folder nodes have different default icons and click behavior.<br>
* Note: Also non-folders may have children.
* @property {string} statusNodeType null for standard nodes. Otherwise type of special system node: 'error', 'loading', 'nodata', or 'paging'.
* @property {boolean} lazy True if this node is loaded on demand, i.e. on first expansion.
* @property {boolean} selected Use isSelected(), setSelected() to access this property.
* @property {string} tooltip Alternative description used as hover popup
* @property {string} iconTooltip Description used as hover popup for icon. @since 2.27
* @property {string} type Node type, used with tree.types map. @since 2.27
*/
function FancytreeNode(parent, obj) {
var i, l, name, cl;
this.parent = parent;
this.tree = parent.tree;
this.ul = null;
this.li = null; // <li id='key' ftnode=this> tag
this.statusNodeType = null; // if this is a temp. node to display the status of its parent
this._isLoading = false; // if this node itself is loading
this._error = null; // {message: '...'} if a load error occurred
this.data = {};
// TODO: merge this code with node.toDict()
// copy attributes from obj object
for (i = 0, l = NODE_ATTRS.length; i < l; i++) {
name = NODE_ATTRS[i];
this[name] = obj[name];
}
// unselectableIgnore and unselectableStatus imply unselectable
if (
this.unselectableIgnore != null ||
this.unselectableStatus != null
) {
this.unselectable = true;
}
if (obj.hideCheckbox) {
$.error(
"'hideCheckbox' node option was removed in v2.23.0: use 'checkbox: false'"
);
}
// node.data += obj.data
if (obj.data) {
$.extend(this.data, obj.data);
}
// Copy all other attributes to this.data.NAME
for (name in obj) {
if (
!NODE_ATTR_MAP[name] &&
(this.tree.options.copyFunctionsToData ||
!$.isFunction(obj[name])) &&
!NONE_NODE_DATA_MAP[name]
) {
// node.data.NAME = obj.NAME
this.data[name] = obj[name];
}
}
// Fix missing key
if (this.key == null) {
// test for null OR undefined
if (this.tree.options.defaultKey) {
this.key = "" + this.tree.options.defaultKey(this);
_assert(this.key, "defaultKey() must return a unique key");
} else {
this.key = "_" + FT._nextNodeKey++;
}
} else {
this.key = "" + this.key; // Convert to string (#217)
}
// Fix tree.activeNode
// TODO: not elegant: we use obj.active as marker to set tree.activeNode
// when loading from a dictionary.
if (obj.active) {
_assert(
this.tree.activeNode === null,
"only one active node allowed"
);
this.tree.activeNode = this;
}
if (obj.selected) {
// #186
this.tree.lastSelectedNode = this;
}
// TODO: handle obj.focus = true
// Create child nodes
cl = obj.children;
if (cl) {
if (cl.length) {
this._setChildren(cl);
} else {
// if an empty array was passed for a lazy node, keep it, in order to mark it 'loaded'
this.children = this.lazy ? [] : null;
}
} else {
this.children = null;
}
// Add to key/ref map (except for root node)
// if( parent ) {
this.tree._callHook("treeRegisterNode", this.tree, true, this);
// }
}
FancytreeNode.prototype = /** @lends FancytreeNode# */ {
/* Return the direct child FancytreeNode with a given key, index. */
_findDirectChild: function(ptr) {
var i,
l,
cl = this.children;
if (cl) {
if (typeof ptr === "string") {
for (i = 0, l = cl.length; i < l; i++) {
if (cl[i].key === ptr) {
return cl[i];
}
}
} else if (typeof ptr === "number") {
return this.children[ptr];
} else if (ptr.parent === this) {
return ptr;
}
}
return null;
},
// TODO: activate()
// TODO: activateSilently()
/* Internal helper called in recursive addChildren sequence.*/
_setChildren: function(children) {
_assert(
children && (!this.children || this.children.length === 0),
"only init supported"
);
this.children = [];
for (var i = 0, l = children.length; i < l; i++) {
this.children.push(new FancytreeNode(this, children[i]));
}
this.tree._callHook(
"treeStructureChanged",
this.tree,
"setChildren"
);
},
/**
* Append (or insert) a list of child nodes.
*
* @param {NodeData[]} children array of child node definitions (also single child accepted)
* @param {FancytreeNode | string | Integer} [insertBefore] child node (or key or index of such).
* If omitted, the new children are appended.
* @returns {FancytreeNode} first child added
*
* @see FancytreeNode#applyPatch
*/
addChildren: function(children, insertBefore) {
var i,
l,
pos,
origFirstChild = this.getFirstChild(),
origLastChild = this.getLastChild(),
firstNode = null,
nodeList = [];
if ($.isPlainObject(children)) {
children = [children];
}
if (!this.children) {
this.children = [];
}
for (i = 0, l = children.length; i < l; i++) {
nodeList.push(new FancytreeNode(this, children[i]));
}
firstNode = nodeList[0];
if (insertBefore == null) {
this.children = this.children.concat(nodeList);
} else {
// Returns null if insertBefore is not a direct child:
insertBefore = this._findDirectChild(insertBefore);
pos = $.inArray(insertBefore, this.children);
_assert(pos >= 0, "insertBefore must be an existing child");
// insert nodeList after children[pos]
this.children.splice.apply(
this.children,
[pos, 0].concat(nodeList)
);
}
if (origFirstChild && !insertBefore) {
// #708: Fast path -- don't render every child of root, just the new ones!
// #723, #729: but only if it's appended to an existing child list
for (i = 0, l = nodeList.length; i < l; i++) {
nodeList[i].render(); // New nodes were never rendered before
}
// Adjust classes where status may have changed
// Has a first child
if (origFirstChild !== this.getFirstChild()) {
// Different first child -- recompute classes
origFirstChild.renderStatus();
}
if (origLastChild !== this.getLastChild()) {
// Different last child -- recompute classes
origLastChild.renderStatus();
}
} else if (!this.parent || this.parent.ul || this.tr) {
// render if the parent was rendered (or this is a root node)
this.render();
}
if (this.tree.options.selectMode === 3) {
this.fixSelection3FromEndNodes();
}
this.triggerModifyChild(
"add",
nodeList.length === 1 ? nodeList[0] : null
);
return firstNode;
},
/**
* Add class to node's span tag and to .extraClasses.
*
* @param {string} className class name
*
* @since 2.17
*/
addClass: function(className) {
return this.toggleClass(className, true);
},
/**
* Append or prepend a node, or append a child node.
*
* This a convenience function that calls addChildren()
*
* @param {NodeData} node node definition
* @param {string} [mode=child] 'before', 'after', 'firstChild', or 'child' ('over' is a synonym for 'child')
* @returns {FancytreeNode} new node
*/
addNode: function(node, mode) {
if (mode === undefined || mode === "over") {
mode = "child";
}
switch (mode) {
case "after":
return this.getParent().addChildren(
node,
this.getNextSibling()
);
case "before":
return this.getParent().addChildren(node, this);
case "firstChild":
// Insert before the first child if any
var insertBefore = this.children ? this.children[0] : null;
return this.addChildren(node, insertBefore);
case "child":
case "over":
return this.addChildren(node);
}
_assert(false, "Invalid mode: " + mode);
},
/**Add child status nodes that indicate 'More...', etc.
*
* This also maintains the node's `partload` property.
* @param {boolean|object} node optional node definition. Pass `false` to remove all paging nodes.
* @param {string} [mode='child'] 'child'|firstChild'
* @since 2.15
*/
addPagingNode: function(node, mode) {
var i, n;
mode = mode || "child";
if (node === false) {
for (i = this.children.length - 1; i >= 0; i--) {
n = this.children[i];
if (n.statusNodeType === "paging") {
this.removeChild(n);
}
}
this.partload = false;
return;
}
node = $.extend(
{
title: this.tree.options.strings.moreData,
statusNodeType: "paging",
icon: false,
},
node
);
this.partload = true;
return this.addNode(node, mode);
},
/**
* Append new node after this.
*
* This a convenience function that calls addNode(node, 'after')
*
* @param {NodeData} node node definition
* @returns {FancytreeNode} new node
*/
appendSibling: function(node) {
return this.addNode(node, "after");
},
/**
* (experimental) Apply a modification (or navigation) operation.
*
* @param {string} cmd
* @param {object} [opts]
* @see Fancytree#applyCommand
* @since 2.32
*/
applyCommand: function(cmd, opts) {
return this.tree.applyCommand(cmd, this, opts);
},
/**
* Modify existing child nodes.
*
* @param {NodePatch} patch
* @returns {$.Promise}
* @see FancytreeNode#addChildren
*/
applyPatch: function(patch) {
// patch [key, null] means 'remove'
if (patch === null) {
this.remove();
return _getResolvedPromise(this);
}
// TODO: make sure that root node is not collapsed or modified
// copy (most) attributes to node.ATTR or node.data.ATTR
var name,
promise,
v,
IGNORE_MAP = { children: true, expanded: true, parent: true }; // TODO: should be global
for (name in patch) {
if (patch.hasOwnProperty(name)) {
v = patch[name];
if (!IGNORE_MAP[name] && !$.isFunction(v)) {
if (NODE_ATTR_MAP[name]) {
this[name] = v;
} else {
this.data[name] = v;
}
}
}
}
// Remove and/or create children
if (patch.hasOwnProperty("children")) {
this.removeChildren();
if (patch.children) {
// only if not null and not empty list
// TODO: addChildren instead?
this._setChildren(patch.children);
}
// TODO: how can we APPEND or INSERT child nodes?
}
if (this.isVisible()) {
this.renderTitle();
this.renderStatus();
}
// Expand collapse (final step, since this may be async)
if (patch.hasOwnProperty("expanded")) {
promise = this.setExpanded(patch.expanded);
} else {
promise = _getResolvedPromise(this);
}
return promise;
},
/** Collapse all sibling nodes.
* @returns {$.Promise}
*/
collapseSiblings: function() {
return this.tree._callHook("nodeCollapseSiblings", this);
},
/** Copy this node as sibling or child of `node`.
*
* @param {FancytreeNode} node source node
* @param {string} [mode=child] 'before' | 'after' | 'child'
* @param {Function} [map] callback function(NodeData, FancytreeNode) that could modify the new node
* @returns {FancytreeNode} new
*/
copyTo: function(node, mode, map) {
return node.addNode(this.toDict(true, map), mode);
},
/** Count direct and indirect children.
*
* @param {boolean} [deep=true] pass 'false' to only count direct children
* @returns {int} number of child nodes
*/
countChildren: function(deep) {
var cl = this.children,
i,
l,
n;
if (!cl) {
return 0;
}
n = cl.length;
if (deep !== false) {
for (i = 0, l = n; i < l; i++) {
n += cl[i].countChildren();
}
}
return n;
},
// TODO: deactivate()
/** Write to browser console if debugLevel >= 4 (prepending node info)
*
* @param {*} msg string or object or array of such
*/
debug: function(msg) {
if (this.tree.options.debugLevel >= 4) {
Array.prototype.unshift.call(arguments, this.toString());
consoleApply("log", arguments);
}
},
/** Deprecated.
* @deprecated since 2014-02-16. Use resetLazy() instead.
*/
discard: function() {
this.warn(
"FancytreeNode.discard() is deprecated since 2014-02-16. Use .resetLazy() instead."
);
return this.resetLazy();
},
/** Remove DOM elements for all descendents. May be called on .collapse event
* to keep the DOM small.
* @param {boolean} [includeSelf=false]
*/
discardMarkup: function(includeSelf) {
var fn = includeSelf ? "nodeRemoveMarkup" : "nodeRemoveChildMarkup";
this.tree._callHook(fn, this);
},
/** Write error to browser console if debugLevel >= 1 (prepending tree info)
*
* @param {*} msg string or object or array of such
*/
error: function(msg) {
if (this.tree.options.debugLevel >= 1) {
Array.prototype.unshift.call(arguments, this.toString());
consoleApply("error", arguments);
}
},
/**Find all nodes that match condition (excluding self).
*
* @param {string | function(node)} match title string to search for, or a
* callback function that returns `true` if a node is matched.
* @returns {FancytreeNode[]} array of nodes (may be empty)
*/
findAll: function(match) {
match = $.isFunction(match) ? match : _makeNodeTitleMatcher(match);
var res = [];
this.visit(function(n) {
if (match(n)) {
res.push(n);
}
});
return res;
},
/**Find first node that matches condition (excluding self).
*
* @param {string | function(node)} match title string to search for, or a
* callback function that returns `true` if a node is matched.
* @returns {FancytreeNode} matching node or null
* @see FancytreeNode#findAll
*/
findFirst: function(match) {
match = $.isFunction(match) ? match : _makeNodeTitleMatcher(match);
var res = null;
this.visit(function(n) {
if (match(n)) {
res = n;
return false;
}
});
return res;
},
/** Find a node relative to self.
*
* @param {number|string} where The keyCode that would normally trigger this move,
* or a keyword ('down', 'first', 'last', 'left', 'parent', 'right', 'up').
* @returns {FancytreeNode}
* @since v2.31
*/
findRelatedNode: function(where, includeHidden) {
return this.tree.findRelatedNode(this, where, includeHidden);
},
/* Apply selection state (internal use only) */
_changeSelectStatusAttrs: function(state) {
var changed = false,
opts = this.tree.options,
unselectable = FT.evalOption(
"unselectable",
this,
this,
opts,
false
),
unselectableStatus = FT.evalOption(
"unselectableStatus",
this,
this,
opts,
undefined
);
if (unselectable && unselectableStatus != null) {
state = unselectableStatus;
}
switch (state) {
case false:
changed = this.selected || this.partsel;
this.selected = false;
this.partsel = false;
break;
case true:
changed = !this.selected || !this.partsel;
this.selected = true;
this.partsel = true;
break;
case undefined:
changed = this.selected || !this.partsel;
this.selected = false;
this.partsel = true;
break;
default:
_assert(false, "invalid state: " + state);
}
// this.debug("fixSelection3AfterLoad() _changeSelectStatusAttrs()", state, changed);
if (changed) {
this.renderStatus();
}
return changed;
},
/**
* Fix selection status, after this node was (de)selected in multi-hier mode.
* This includes (de)selecting all children.
*/
fixSelection3AfterClick: function(callOpts) {
var flag = this.isSelected();
// this.debug("fixSelection3AfterClick()");
this.visit(function(node) {
node._changeSelectStatusAttrs(flag);
if (node.radiogroup) {
// #931: don't (de)select this branch
return "skip";
}
});
this.fixSelection3FromEndNodes(callOpts);
},
/**
* Fix selection status for multi-hier mode.
* Only end-nodes are considered to update the descendants branch and parents.
* Should be called after this node has loaded new children or after
* children have been modified using the API.
*/
fixSelection3FromEndNodes: function(callOpts) {
var opts = this.tree.options;
// this.debug("fixSelection3FromEndNodes()");
_assert(opts.selectMode === 3, "expected selectMode 3");
// Visit all end nodes and adjust their parent's `selected` and `partsel`
// attributes. Return selection state true, false, or undefined.
function _walk(node) {
var i,
l,
child,
s,
state,
allSelected,
someSelected,
unselIgnore,
unselState,
children = node.children;
if (children && children.length) {
// check all children recursively
allSelected = true;
someSelected = false;
for (i = 0, l = children.length; i < l; i++) {
child = children[i];
// the selection state of a node is not relevant; we need the end-nodes
s = _walk(child);
// if( !child.unselectableIgnore ) {
unselIgnore = FT.evalOption(
"unselectableIgnore",
child,
child,
opts,
false
);
if (!unselIgnore) {
if (s !== false) {
someSelected = true;
}
if (s !== true) {
allSelected = false;
}
}
}
// eslint-disable-next-line no-nested-ternary
state = allSelected
? true
: someSelected
? undefined
: false;
} else {
// This is an end-node: simply report the status
unselState = FT.evalOption(
"unselectableStatus",
node,
node,
opts,
undefined
);
state = unselState == null ? !!node.selected : !!unselState;
}
// #939: Keep a `partsel` flag that was explicitly set on a lazy node
if (
node.partsel &&
!node.selected &&
node.lazy &&
node.children == null
) {
state = undefined;
}
node._changeSelectStatusAttrs(state);
return state;
}
_walk(this);
// Update parent's state
this.visitParents(function(node) {
var i,
l,
child,
state,
unselIgnore,
unselState,
children = node.children,
allSelected = true,
someSelected = false;
for (i = 0, l = children.length; i < l; i++) {
child = children[i];
unselIgnore = FT.evalOption(
"unselectableIgnore",
child,
child,
opts,
false
);
if (!unselIgnore) {
unselState = FT.evalOption(
"unselectableStatus",
child,
child,
opts,
undefined
);
state =
unselState == null
? !!child.selected
: !!unselState;
// When fixing the parents, we trust the sibling status (i.e.
// we don't recurse)
if (state || child.partsel) {
someSelected = true;
}
if (!state) {
allSelected = false;
}
}
}
// eslint-disable-next-line no-nested-ternary
state = allSelected ? true : someSelected ? undefined : false;
node._changeSelectStatusAttrs(state);
});
},
// TODO: focus()
/**
* Update node data. If dict contains 'children', then also replace
* the hole sub tree.
* @param {NodeData} dict
*
* @see FancytreeNode#addChildren
* @see FancytreeNode#applyPatch
*/
fromDict: function(dict) {
// copy all other attributes to this.data.xxx
for (var name in dict) {
if (NODE_ATTR_MAP[name]) {
// node.NAME = dict.NAME
this[name] = dict[name];
} else if (name === "data") {
// node.data += dict.data
$.extend(this.data, dict.data);
} else if (
!$.isFunction(dict[name]) &&
!NONE_NODE_DATA_MAP[name]
) {
// node.data.NAME = dict.NAME
this.data[name] = dict[name];
}
}
if (dict.children) {
// recursively set children and render
this.removeChildren();
this.addChildren(dict.children);
}
this.renderTitle();
/*
var children = dict.children;
if(children === undefined){
this.data = $.extend(this.data, dict);
this.render();
return;
}
dict = $.extend({}, dict);
dict.children = undefined;
this.data = $.extend(this.data, dict);
this.removeChildren();
this.addChild(children);
*/
},
/** Return the list of child nodes (undefined for unexpanded lazy nodes).
* @returns {FancytreeNode[] | undefined}
*/
getChildren: function() {
if (this.hasChildren() === undefined) {
// TODO: only required for lazy nodes?
return undefined; // Lazy node: unloaded, currently loading, or load error
}
return this.children;
},
/** Return the first child node or null.
* @returns {FancytreeNode | null}
*/
getFirstChild: function() {
return this.children ? this.children[0] : null;
},
/** Return the 0-based child index.
* @returns {int}
*/
getIndex: function() {
// return this.parent.children.indexOf(this);
return $.inArray(this, this.parent.children); // indexOf doesn't work in IE7
},
/** Return the hierarchical child index (1-based, e.g. '3.2.4').
* @param {string} [separator="."]
* @param {int} [digits=1]
* @returns {string}
*/
getIndexHier: function(separator, digits) {
separator = separator || ".";
var s,
res = [];
$.each(this.getParentList(false, true), function(i, o) {
s = "" + (o.getIndex() + 1);
if (digits) {
// prepend leading zeroes
s = ("0000000" + s).substr(-digits);
}
res.push(s);
});
return res.join(separator);
},
/** Return the parent keys separated by options.keyPathSeparator, e.g. "/id_1/id_17/id_32".
*
* (Unlike `node.getPath()`, this method prepends a "/" and inverts the first argument.)
*
* @see FancytreeNode#getPath
* @param {boolean} [excludeSelf=false]
* @returns {string}
*/
getKeyPath: function(excludeSelf) {
var sep = this.tree.options.keyPathSeparator;
return sep + this.getPath(!excludeSelf, "key", sep);
},
/** Return the last child of this node or null.
* @returns {FancytreeNode | null}
*/
getLastChild: function() {
return this.children
? this.children[this.children.length - 1]
: null;
},
/** Return node depth. 0: System root node, 1: visible top-level node, 2: first sub-level, ... .
* @returns {int}
*/
getLevel: function() {
var level = 0,
dtn = this.parent;
while (dtn) {
level++;
dtn = dtn.parent;
}
return level;
},
/** Return the successor node (under the same parent) or null.
* @returns {FancytreeNode | null}
*/
getNextSibling: function() {
// TODO: use indexOf, if available: (not in IE6)
if (this.parent) {
var i,
l,
ac = this.parent.children;
for (i = 0, l = ac.length - 1; i < l; i++) {
// up to length-2, so next(last) = null
if (ac[i] === this) {
return ac[i + 1];
}
}
}
return null;
},
/** Return the parent node (null for the system root node).
* @returns {FancytreeNode | null}
*/
getParent: function() {
// TODO: return null for top-level nodes?
return this.parent;
},
/** Return an array of all parent nodes (top-down).
* @param {boolean} [includeRoot=false] Include the invisible system root node.
* @param {boolean} [includeSelf=false] Include the node itself.
* @returns {FancytreeNode[]}
*/
getParentList: function(includeRoot, includeSelf) {
var l = [],
dtn = includeSelf ? this : this.parent;
while (dtn) {
if (includeRoot || dtn.parent) {
l.unshift(dtn);
}
dtn = dtn.parent;
}
return l;
},
/** Return a string representing the hierachical node path, e.g. "a/b/c".
* @param {boolean} [includeSelf=true]
* @param {string | function} [part="title"] node property name or callback
* @param {string} [separator="/"]
* @returns {string}
* @since v2.31
*/
getPath: function(includeSelf, part, separator) {
includeSelf = includeSelf !== false;
part = part || "title";
separator = separator || "/";
var val,
path = [],
isFunc = $.isFunction(part);
this.visitParents(function(n) {
if (n.parent) {
val = isFunc ? part(n) : n[part];
path.unshift(val);
}
}, includeSelf);
return path.join(separator);
},
/** Return the predecessor node (under the same parent) or null.
* @returns {FancytreeNode | null}
*/
getPrevSibling: function() {
if (this.parent) {
var i,
l,
ac = this.parent.children;
for (i = 1, l = ac.length; i < l; i++) {
// start with 1, so prev(first) = null
if (ac[i] === this) {
return ac[i - 1];
}
}
}
return null;
},
/**
* Return an array of selected descendant nodes.
* @param {boolean} [stopOnParents=false] only return the topmost selected
* node (useful with selectMode 3)
* @returns {FancytreeNode[]}
*/
getSelectedNodes: function(stopOnParents) {
var nodeList = [];
this.visit(function(node) {
if (node.selected) {
nodeList.push(node);
if (stopOnParents === true) {
return "skip"; // stop processing this branch
}
}
});
return nodeList;
},
/** Return true if node has children. Return undefined if not sure, i.e. the node is lazy and not yet loaded).
* @returns {boolean | undefined}
*/
hasChildren: function() {
if (this.lazy) {
if (this.children == null) {
// null or undefined: Not yet loaded
return undefined;
} else if (this.children.length === 0) {
// Loaded, but response was empty
return false;
} else if (
this.children.length === 1 &&
this.children[0].isStatusNode()
) {
// Currently loading or load error
return undefined;
}
return true;
}
return !!(this.children && this.children.length);
},
/**
* Return true if node has `className` defined in .extraClasses.
*
* @param {string} className class name (separate multiple classes by space)
* @returns {boolean}
*
* @since 2.32
*/
hasClass: function(className) {
return (
(" " + (this.extraClasses || "") + " ").indexOf(
" " + className + " "
) >= 0
);
},
/** Return true if node has keyboard focus.
* @returns {boolean}
*/
hasFocus: function() {
return this.tree.hasFocus() && this.tree.focusNode === this;
},
/** Write to browser console if debugLevel >= 3 (prepending node info)
*
* @param {*} msg string or object or array of such
*/
info: function(msg) {
if (this.tree.options.debugLevel >= 3) {
Array.prototype.unshift.call(arguments, this.toString());
consoleApply("info", arguments);
}
},
/** Return true if node is active (see also FancytreeNode#isSelected).
* @returns {boolean}
*/
isActive: function() {
return this.tree.activeNode === this;
},
/** Return true if node is vertically below `otherNode`, i.e. rendered in a subsequent row.
* @param {FancytreeNode} otherNode
* @returns {boolean}
* @since 2.28
*/
isBelowOf: function(otherNode) {
return this.getIndexHier(".", 5) > otherNode.getIndexHier(".", 5);
},
/** Return true if node is a direct child of otherNode.
* @param {FancytreeNode} otherNode
* @returns {boolean}
*/
isChildOf: function(otherNode) {
return this.parent && this.parent === otherNode;
},
/** Return true, if node is a direct or indirect sub node of otherNode.
* @param {FancytreeNode} otherNode
* @returns {boolean}
*/
isDescendantOf: function(otherNode) {
if (!otherNode || otherNode.tree !== this.tree) {
return false;
}
var p = this.parent;
while (p) {
if (p === otherNode) {
return true;
}
if (p === p.parent) {
$.error("Recursive parent link: " + p);
}
p = p.parent;
}
return false;
},
/** Return true if node is expanded.
* @returns {boolean}
*/
isExpanded: function() {
return !!this.expanded;
},
/** Return true if node is the first node of its parent's children.
* @returns {boolean}
*/
isFirstSibling: function() {
var p = this.parent;
return !p || p.children[0] === this;
},
/** Return true if node is a folder, i.e. has the node.folder attribute set.
* @returns {boolean}
*/
isFolder: function() {
return !!this.folder;
},
/** Return true if node is the last node of its parent's children.
* @returns {boolean}
*/
isLastSibling: function() {
var p = this.parent;
return !p || p.children[p.children.length - 1] === this;
},
/** Return true if node is lazy (even if data was already loaded)
* @returns {boolean}
*/
isLazy: function() {
return !!this.lazy;
},
/** Return true if node is lazy and loaded. For non-lazy nodes always return true.
* @returns {boolean}
*/
isLoaded: function() {
return !this.lazy || this.hasChildren() !== undefined; // Also checks if the only child is a status node
},
/** Return true if children are currently beeing loaded, i.e. a Ajax request is pending.
* @returns {boolean}
*/
isLoading: function() {
return !!this._isLoading;
},
/*
* @deprecated since v2.4.0: Use isRootNode() instead
*/
isRoot: function() {
return this.isRootNode();
},
/** Return true if node is partially selected (tri-state).
* @returns {boolean}
* @since 2.23
*/
isPartsel: function() {
return !this.selected && !!this.partsel;
},
/** (experimental) Return true if this is partially loaded.
* @returns {boolean}
* @since 2.15
*/
isPartload: function() {
return !!this.partload;
},
/** Return true if this is the (invisible) system root node.
* @returns {boolean}
* @since 2.4
*/
isRootNode: function() {
return this.tree.rootNode === this;
},
/** Return true if node is selected, i.e. has a checkmark set (see also FancytreeNode#isActive).
* @returns {boolean}
*/
isSelected: function() {
return !!this.selected;
},
/** Return true if this node is a temporarily generated system node like
* 'loading', 'paging', or 'error' (node.statusNodeType contains the type).
* @returns {boolean}
*/
isStatusNode: function() {
return !!this.statusNodeType;
},
/** Return true if this node is a status node of type 'paging'.
* @returns {boolean}
* @since 2.15
*/
isPagingNode: function() {
return this.statusNodeType === "paging";
},
/** Return true if this a top level node, i.e. a direct child of the (invisible) system root node.
* @returns {boolean}
* @since 2.4
*/
isTopLevel: function() {
return this.tree.rootNode === this.parent;
},
/** Return true if node is lazy and not yet loaded. For non-lazy nodes always return false.
* @returns {boolean}
*/
isUndefined: function() {
return this.hasChildren() === undefined; // also checks if the only child is a status node
},
/** Return true if all parent nodes are expanded. Note: this does not check
* whether the node is scrolled into the visible part of the screen.
* @returns {boolean}
*/
isVisible: function() {
var i,
l,
n,
hasFilter = this.tree.enableFilter,
parents = this.getParentList(false, false);
// TODO: check $(n.span).is(":visible")
// i.e. return false for nodes (but not parents) that are hidden
// by a filter
if (hasFilter && !this.match && !this.subMatchCount) {
// this.debug( "isVisible: HIDDEN (" + hasFilter + ", " + this.match + ", " + this.match + ")" );
return false;
}
for (i = 0, l = parents.length; i < l; i++) {
n = parents[i];
if (!n.expanded) {
// this.debug("isVisible: HIDDEN (parent collapsed)");
return false;
}
// if (hasFilter && !n.match && !n.subMatchCount) {
// this.debug("isVisible: HIDDEN (" + hasFilter + ", " + this.match + ", " + this.match + ")");
// return false;
// }
}
// this.debug("isVisible: VISIBLE");
return true;
},
/** Deprecated.
* @deprecated since 2014-02-16: use load() instead.
*/
lazyLoad: function(discard) {
$.error(
"FancytreeNode.lazyLoad() is deprecated since 2014-02-16. Use .load() instead."
);
},
/**
* Load all children of a lazy node if neccessary. The <i>expanded</i> state is maintained.
* @param {boolean} [forceReload=false] Pass true to discard any existing nodes before. Otherwise this method does nothing if the node was already loaded.
* @returns {$.Promise}
*/
load: function(forceReload) {
var res,
source,
self = this,
wasExpanded = this.isExpanded();
_assert(this.isLazy(), "load() requires a lazy node");
// _assert( forceReload || this.isUndefined(), "Pass forceReload=true to re-load a lazy node" );
if (!forceReload && !this.isUndefined()) {
return _getResolvedPromise(this);
}
if (this.isLoaded()) {
this.resetLazy(); // also collapses
}
// This method is also called by setExpanded() and loadKeyPath(), so we
// have to avoid recursion.
source = this.tree._triggerNodeEvent("lazyLoad", this);
if (source === false) {
// #69
return _getResolvedPromise(this);
}
_assert(
typeof source !== "boolean",
"lazyLoad event must return source in data.result"
);
res = this.tree._callHook("nodeLoadChildren", this, source);
if (wasExpanded) {
this.expanded = true;
res.always(function() {
self.render();
});
} else {
res.always(function() {
self.renderStatus(); // fix expander icon to 'loaded'
});
}
return res;
},
/** Expand all parents and optionally scroll into visible area as neccessary.
* Promise is resolved, when lazy loading and animations are done.
* @param {object} [opts] passed to `setExpanded()`.
* Defaults to {noAnimation: false, noEvents: false, scrollIntoView: true}
* @returns {$.Promise}
*/
makeVisible: function(opts) {
var i,
self = this,
deferreds = [],
dfd = new $.Deferred(),
parents = this.getParentList(false, false),
len = parents.length,
effects = !(opts && opts.noAnimation === true),
scroll = !(opts && opts.scrollIntoView === false);
// Expand bottom-up, so only the top node is animated
for (i = len - 1; i >= 0; i--) {
// self.debug("pushexpand" + parents[i]);
deferreds.push(parents[i].setExpanded(true, opts));
}
$.when.apply($, deferreds).done(function() {
// All expands have finished
// self.debug("expand DONE", scroll);
if (scroll) {
self.scrollIntoView(effects).done(function() {
// self.debug("scroll DONE");
dfd.resolve();
});
} else {
dfd.resolve();
}
});
return dfd.promise();
},
/** Move this node to targetNode.
* @param {FancytreeNode} targetNode
* @param {string} mode <pre>
* 'child': append this node as last child of targetNode.
* This is the default. To be compatble with the D'n'd
* hitMode, we also accept 'over'.
* 'firstChild': add this node as first child of targetNode.
* 'before': add this node as sibling before targetNode.
* 'after': add this node as sibling after targetNode.</pre>
* @param {function} [map] optional callback(FancytreeNode) to allow modifcations
*/
moveTo: function(targetNode, mode, map) {
if (mode === undefined || mode === "over") {
mode = "child";
} else if (mode === "firstChild") {
if (targetNode.children && targetNode.children.length) {
mode = "before";
targetNode = targetNode.children[0];
} else {
mode = "child";
}
}
var pos,
tree = this.tree,
prevParent = this.parent,
targetParent =
mode === "child" ? targetNode : targetNode.parent;
if (this === targetNode) {
return;
} else if (!this.parent) {
$.error("Cannot move system root");
} else if (targetParent.isDescendantOf(this)) {
$.error("Cannot move a node to its own descendant");
}
if (targetParent !== prevParent) {
prevParent.triggerModifyChild("remove", this);
}
// Unlink this node from current parent
if (this.parent.children.length === 1) {
if (this.parent === targetParent) {
return; // #258
}
this.parent.children = this.parent.lazy ? [] : null;
this.parent.expanded = false;
} else {
pos = $.inArray(this, this.parent.children);
_assert(pos >= 0, "invalid source parent");
this.parent.children.splice(pos, 1);
}
// Remove from source DOM parent
// if(this.parent.ul){
// this.parent.ul.removeChild(this.li);
// }
// Insert this node to target parent's child list
this.parent = targetParent;
if (targetParent.hasChildren()) {
switch (mode) {
case "child":
// Append to existing target children
targetParent.children.push(this);
break;
case "before":
// Insert this node before target node
pos = $.inArray(targetNode, targetParent.children);
_assert(pos >= 0, "invalid target parent");
targetParent.children.splice(pos, 0, this);
break;
case "after":
// Insert this node after target node
pos = $.inArray(targetNode, targetParent.children);
_assert(pos >= 0, "invalid target parent");
targetParent.children.splice(pos + 1, 0, this);
break;
default:
$.error("Invalid mode " + mode);
}
} else {
targetParent.children = [this];
}
// Parent has no <ul> tag yet:
// if( !targetParent.ul ) {
// // This is the parent's first child: create UL tag
// // (Hidden, because it will be
// targetParent.ul = document.createElement("ul");
// targetParent.ul.style.display = "none";
// targetParent.li.appendChild(targetParent.ul);
// }
// // Issue 319: Add to target DOM parent (only if node was already rendered(expanded))
// if(this.li){
// targetParent.ul.appendChild(this.li);
// }
// Let caller modify the nodes
if (map) {
targetNode.visit(map, true);
}
if (targetParent === prevParent) {
targetParent.triggerModifyChild("move", this);
} else {
// prevParent.triggerModifyChild("remove", this);
targetParent.triggerModifyChild("add", this);
}
// Handle cross-tree moves
if (tree !== targetNode.tree) {
// Fix node.tree for all source nodes
// _assert(false, "Cross-tree move is not yet implemented.");
this.warn("Cross-tree moveTo is experimental!");
this.visit(function(n) {
// TODO: fix selection state and activation, ...
n.tree = targetNode.tree;
}, true);
}
// A collaposed node won't re-render children, so we have to remove it manually
// if( !targetParent.expanded ){
// prevParent.ul.removeChild(this.li);
// }
tree._callHook("treeStructureChanged", tree, "moveTo");
// Update HTML markup
if (!prevParent.isDescendantOf(targetParent)) {
prevParent.render();
}
if (
!targetParent.isDescendantOf(prevParent) &&
targetParent !== prevParent
) {
targetParent.render();
}
// TODO: fix selection state
// TODO: fix active state
/*
var tree = this.tree;
var opts = tree.options;
var pers = tree.persistence;
// Always expand, if it's below minExpandLevel
// tree.logDebug ("%s._addChildNode(%o), l=%o", this, ftnode, ftnode.getLevel());
if ( opts.minExpandLevel >= ftnode.getLevel() ) {
// tree.logDebug ("Force expand for %o", ftnode);
this.bExpanded = true;
}
// In multi-hier mode, update the parents selection state
// DT issue #82: only if not initializing, because the children may not exist yet
// if( !ftnode.data.isStatusNode() && opts.selectMode==3 && !isInitializing )
// ftnode._fixSelectionState();
// In multi-hier mode, update the parents selection state
if( ftnode.bSelected && opts.selectMode==3 ) {
var p = this;
while( p ) {
if( !p.hasSubSel )
p._setSubSel(true);
p = p.parent;
}
}
// render this node and the new child
if ( tree.bEnableUpdate )
this.render();
return ftnode;
*/
},
/** Set focus relative to this node and optionally activate.
*
* 'left' collapses the node if it is expanded, or move to the parent
* otherwise.
* 'right' expands the node if it is collapsed, or move to the first
* child otherwise.
*
* @param {string|number} where 'down', 'first', 'last', 'left', 'parent', 'right', or 'up'.
* (Alternatively the keyCode that would normally trigger this move,
* e.g. `$.ui.keyCode.LEFT` = 'left'.
* @param {boolean} [activate=true]
* @returns {$.Promise}
*/
navigate: function(where, activate) {
var node,
KC = $.ui.keyCode;
// Handle optional expand/collapse action for LEFT/RIGHT
switch (where) {
case "left":
case KC.LEFT:
if (this.expanded) {
return this.setExpanded(false);
}
break;
case "right":
case KC.RIGHT:
if (!this.expanded && (this.children || this.lazy)) {
return this.setExpanded();
}
break;
}
// Otherwise activate or focus the related node
node = this.findRelatedNode(where);
if (node) {
// setFocus/setActive will scroll later (if autoScroll is specified)
try {
node.makeVisible({ scrollIntoView: false });
} catch (e) {} // #272
if (activate === false) {
node.setFocus();
return _getResolvedPromise();
}
return node.setActive();
}
this.warn("Could not find related node '" + where + "'.");
return _getResolvedPromise();
},
/**
* Remove this node (not allowed for system root).
*/
remove: function() {
return this.parent.removeChild(this);
},
/**
* Remove childNode from list of direct children.
* @param {FancytreeNode} childNode
*/
removeChild: function(childNode) {
return this.tree._callHook("nodeRemoveChild", this, childNode);
},
/**
* Remove all child nodes and descendents. This converts the node into a leaf.<br>
* If this was a lazy node, it is still considered 'loaded'; call node.resetLazy()
* in order to trigger lazyLoad on next expand.
*/
removeChildren: function() {
return this.tree._callHook("nodeRemoveChildren", this);
},
/**
* Remove class from node's span tag and .extraClasses.
*
* @param {string} className class name
*
* @since 2.17
*/
removeClass: function(className) {
return this.toggleClass(className, false);
},
/**
* This method renders and updates all HTML markup that is required
* to display this node in its current state.<br>
* Note:
* <ul>
* <li>It should only be neccessary to call this method after the node object
* was modified by direct access to its properties, because the common
* API methods (node.setTitle(), moveTo(), addChildren(), remove(), ...)
* already handle this.
* <li> {@link FancytreeNode#renderTitle} and {@link FancytreeNode#renderStatus}
* are implied. If changes are more local, calling only renderTitle() or
* renderStatus() may be sufficient and faster.
* </ul>
*
* @param {boolean} [force=false] re-render, even if html markup was already created
* @param {boolean} [deep=false] also render all descendants, even if parent is collapsed
*/
render: function(force, deep) {
return this.tree._callHook("nodeRender", this, force, deep);
},
/** Create HTML markup for the node's outer `<span>` (expander, checkbox, icon, and title).
* Implies {@link FancytreeNode#renderStatus}.
* @see Fancytree_Hooks#nodeRenderTitle
*/
renderTitle: function() {
return this.tree._callHook("nodeRenderTitle", this);
},
/** Update element's CSS classes according to node state.
* @see Fancytree_Hooks#nodeRenderStatus
*/
renderStatus: function() {
return this.tree._callHook("nodeRenderStatus", this);
},
/**
* (experimental) Replace this node with `source`.
* (Currently only available for paging nodes.)
* @param {NodeData[]} source List of child node definitions
* @since 2.15
*/
replaceWith: function(source) {
var res,
parent = this.parent,
pos = $.inArray(this, parent.children),
self = this;
_assert(
this.isPagingNode(),
"replaceWith() currently requires a paging status node"
);
res = this.tree._callHook("nodeLoadChildren", this, source);
res.done(function(data) {
// New nodes are currently children of `this`.
var children = self.children;
// Prepend newly loaded child nodes to `this`
// Move new children after self
for (i = 0; i < children.length; i++) {
children[i].parent = parent;
}
parent.children.splice.apply(
parent.children,
[pos + 1, 0].concat(children)
);
// Remove self
self.children = null;
self.remove();
// Redraw new nodes
parent.render();
// TODO: set node.partload = false if this was tha last paging node?
// parent.addPagingNode(false);
}).fail(function() {
self.setExpanded();
});
return res;
// $.error("Not implemented: replaceWith()");
},
/**
* Remove all children, collapse, and set the lazy-flag, so that the lazyLoad
* event is triggered on next expand.
*/
resetLazy: function() {
this.removeChildren();
this.expanded = false;
this.lazy = true;
this.children = undefined;
this.renderStatus();
},
/** Schedule activity for delayed execution (cancel any pending request).
* scheduleAction('cancel') will only cancel a pending request (if any).
* @param {string} mode
* @param {number} ms
*/
scheduleAction: function(mode, ms) {
if (this.tree.timer) {
clearTimeout(this.tree.timer);
this.tree.debug("clearTimeout(%o)", this.tree.timer);
}
this.tree.timer = null;
var self = this; // required for closures
switch (mode) {
case "cancel":
// Simply made sure that timer was cleared
break;
case "expand":
this.tree.timer = setTimeout(function() {
self.tree.debug("setTimeout: trigger expand");
self.setExpanded(true);
}, ms);
break;
case "activate":
this.tree.timer = setTimeout(function() {
self.tree.debug("setTimeout: trigger activate");
self.setActive(true);
}, ms);
break;
default:
$.error("Invalid mode " + mode);
}
// this.tree.debug("setTimeout(%s, %s): %s", mode, ms, this.tree.timer);
},
/**
*
* @param {boolean | PlainObject} [effects=false] animation options.
* @param {object} [options=null] {topNode: null, effects: ..., parent: ...} this node will remain visible in
* any case, even if `this` is outside the scroll pane.
* @returns {$.Promise}
*/
scrollIntoView: function(effects, options) {
if (options !== undefined && _isNode(options)) {
throw Error(
"scrollIntoView() with 'topNode' option is deprecated since 2014-05-08. Use 'options.topNode' instead."
);
}
// The scroll parent is typically the plain tree's <UL> container.
// For ext-table, we choose the nearest parent that has `position: relative`
// and `overflow` set.
// (This default can be overridden by the local or global `scrollParent` option.)
var opts = $.extend(
{
effects:
effects === true
? { duration: 200, queue: false }
: effects,
scrollOfs: this.tree.options.scrollOfs,
scrollParent: this.tree.options.scrollParent,
topNode: null,
},
options
),
$scrollParent = opts.scrollParent,
$container = this.tree.$container,
overflowY = $container.css("overflow-y");
if (!$scrollParent) {
if (this.tree.tbody) {
$scrollParent = $container.scrollParent();
} else if (overflowY === "scroll" || overflowY === "auto") {
$scrollParent = $container;
} else {
// #922 plain tree in a non-fixed-sized UL scrolls inside its parent
$scrollParent = $container.scrollParent();
}
} else if (!$scrollParent.jquery) {
// Make sure we have a jQuery object
$scrollParent = $($scrollParent);
}
if (
$scrollParent[0] === document ||
$scrollParent[0] === document.body
) {
// `document` may be returned by $().scrollParent(), if nothing is found,
// but would not work: (see #894)
this.debug(
"scrollIntoView(): normalizing scrollParent to 'window':",
$scrollParent[0]
);
$scrollParent = $(window);
}
// eslint-disable-next-line one-var
var topNodeY,
nodeY,
horzScrollbarHeight,
containerOffsetTop,
dfd = new $.Deferred(),
self = this,
nodeHeight = $(this.span).height(),
topOfs = opts.scrollOfs.top || 0,
bottomOfs = opts.scrollOfs.bottom || 0,
containerHeight = $scrollParent.height(),
scrollTop = $scrollParent.scrollTop(),
$animateTarget = $scrollParent,
isParentWindow = $scrollParent[0] === window,
topNode = opts.topNode || null,
newScrollTop = null;
// this.debug("scrollIntoView(), scrollTop=" + scrollTop, opts.scrollOfs);
// _assert($(this.span).is(":visible"), "scrollIntoView node is invisible"); // otherwise we cannot calc offsets
if (this.isRootNode() || !this.isVisible()) {
// We cannot calc offsets for hidden elements
this.info("scrollIntoView(): node is invisible.");
return _getResolvedPromise();
}
if (isParentWindow) {
nodeY = $(this.span).offset().top;
topNodeY =
topNode && topNode.span ? $(topNode.span).offset().top : 0;
$animateTarget = $("html,body");
} else {
_assert(
$scrollParent[0] !== document &&
$scrollParent[0] !== document.body,
"scrollParent should be a simple element or `window`, not document or body."
);
containerOffsetTop = $scrollParent.offset().top;
nodeY =
$(this.span).offset().top - containerOffsetTop + scrollTop; // relative to scroll parent
topNodeY = topNode
? $(topNode.span).offset().top -
containerOffsetTop +
scrollTop
: 0;
horzScrollbarHeight = Math.max(
0,
$scrollParent.innerHeight() - $scrollParent[0].clientHeight
);
containerHeight -= horzScrollbarHeight;
}
// this.debug(" scrollIntoView(), nodeY=" + nodeY + ", containerHeight=" + containerHeight);
if (nodeY < scrollTop + topOfs) {
// Node is above visible container area
newScrollTop = nodeY - topOfs;
// this.debug(" scrollIntoView(), UPPER newScrollTop=" + newScrollTop);
} else if (
nodeY + nodeHeight >
scrollTop + containerHeight - bottomOfs
) {
newScrollTop = nodeY + nodeHeight - containerHeight + bottomOfs;
// this.debug(" scrollIntoView(), LOWER newScrollTop=" + newScrollTop);
// If a topNode was passed, make sure that it is never scrolled
// outside the upper border
if (topNode) {
_assert(
topNode.isRootNode() || topNode.isVisible(),
"topNode must be visible"
);
if (topNodeY < newScrollTop) {
newScrollTop = topNodeY - topOfs;
// this.debug(" scrollIntoView(), TOP newScrollTop=" + newScrollTop);
}
}
}
if (newScrollTop === null) {
dfd.resolveWith(this);
} else {
// this.debug(" scrollIntoView(), SET newScrollTop=" + newScrollTop);
if (opts.effects) {
opts.effects.complete = function() {
dfd.resolveWith(self);
};
$animateTarget.stop(true).animate(
{
scrollTop: newScrollTop,
},
opts.effects
);
} else {
$animateTarget[0].scrollTop = newScrollTop;
dfd.resolveWith(this);
}
}
return dfd.promise();
},
/**Activate this node.
*
* The `cell` option requires the ext-table and ext-ariagrid extensions.
*
* @param {boolean} [flag=true] pass false to deactivate
* @param {object} [opts] additional options. Defaults to {noEvents: false, noFocus: false, cell: null}
* @returns {$.Promise}
*/
setActive: function(flag, opts) {
return this.tree._callHook("nodeSetActive", this, flag, opts);
},
/**Expand or collapse this node. Promise is resolved, when lazy loading and animations are done.
* @param {boolean} [flag=true] pass false to collapse
* @param {object} [opts] additional options. Defaults to {noAnimation: false, noEvents: false}
* @returns {$.Promise}
*/
setExpanded: function(flag, opts) {
return this.tree._callHook("nodeSetExpanded", this, flag, opts);
},
/**Set keyboard focus to this node.
* @param {boolean} [flag=true] pass false to blur
* @see Fancytree#setFocus
*/
setFocus: function(flag) {
return this.tree._callHook("nodeSetFocus", this, flag);
},
/**Select this node, i.e. check the checkbox.
* @param {boolean} [flag=true] pass false to deselect
* @param {object} [opts] additional options. Defaults to {noEvents: false, p
* propagateDown: null, propagateUp: null, callback: null }
*/
setSelected: function(flag, opts) {
return this.tree._callHook("nodeSetSelected", this, flag, opts);
},
/**Mark a lazy node as 'error', 'loading', 'nodata', or 'ok'.
* @param {string} status 'error'|'loading'|'nodata'|'ok'
* @param {string} [message]
* @param {string} [details]
*/
setStatus: function(status, message, details) {
return this.tree._callHook(
"nodeSetStatus",
this,
status,
message,
details
);
},
/**Rename this node.
* @param {string} title
*/
setTitle: function(title) {
this.title = title;
this.renderTitle();
this.triggerModify("rename");
},
/**Sort child list by title.
* @param {function} [cmp] custom compare function(a, b) that returns -1, 0, or 1 (defaults to sort by title).
* @param {boolean} [deep=false] pass true to sort all descendant nodes
*/
sortChildren: function(cmp, deep) {
var i,
l,
cl = this.children;
if (!cl) {
return;
}
cmp =
cmp ||
function(a, b) {
var x = a.title.toLowerCase(),
y = b.title.toLowerCase();
// eslint-disable-next-line no-nested-ternary
return x === y ? 0 : x > y ? 1 : -1;
};
cl.sort(cmp);
if (deep) {
for (i = 0, l = cl.length; i < l; i++) {
if (cl[i].children) {
cl[i].sortChildren(cmp, "$norender$");
}
}
}
if (deep !== "$norender$") {
this.render();
}
this.triggerModifyChild("sort");
},
/** Convert node (or whole branch) into a plain object.
*
* The result is compatible with node.addChildren().
*
* @param {boolean} [recursive=false] include child nodes
* @param {function} [callback] callback(dict, node) is called for every node, in order to allow modifications.
* Return `false` to ignore this node or `"skip"` to include this node without its children.
* @returns {NodeData}
*/
toDict: function(recursive, callback) {
var i,
l,
node,
res,
dict = {},
self = this;
$.each(NODE_ATTRS, function(i, a) {
if (self[a] || self[a] === false) {
dict[a] = self[a];
}
});
if (!$.isEmptyObject(this.data)) {
dict.data = $.extend({}, this.data);
if ($.isEmptyObject(dict.data)) {
delete dict.data;
}
}
if (callback) {
res = callback(dict, self);
if (res === false) {
return false; // Don't include this node nor its children
}
if (res === "skip") {
recursive = false; // Include this node, but not the children
}
}
if (recursive) {
if ($.isArray(this.children)) {
dict.children = [];
for (i = 0, l = this.children.length; i < l; i++) {
node = this.children[i];
if (!node.isStatusNode()) {
res = node.toDict(true, callback);
if (res !== false) {
dict.children.push(res);
}
}
}
}
}
return dict;
},
/**
* Set, clear, or toggle class of node's span tag and .extraClasses.
*
* @param {string} className class name (separate multiple classes by space)
* @param {boolean} [flag] true/false to add/remove class. If omitted, class is toggled.
* @returns {boolean} true if a class was added
*
* @since 2.17
*/
toggleClass: function(value, flag) {
var className,
hasClass,
rnotwhite = /\S+/g,
classNames = value.match(rnotwhite) || [],
i = 0,
wasAdded = false,
statusElem = this[this.tree.statusClassPropName],
curClasses = " " + (this.extraClasses || "") + " ";
// this.info("toggleClass('" + value + "', " + flag + ")", curClasses);
// Modify DOM element directly if it already exists
if (statusElem) {
$(statusElem).toggleClass(value, flag);
}
// Modify node.extraClasses to make this change persistent
// Toggle if flag was not passed
while ((className = classNames[i++])) {
hasClass = curClasses.indexOf(" " + className + " ") >= 0;
flag = flag === undefined ? !hasClass : !!flag;
if (flag) {
if (!hasClass) {
curClasses += className + " ";
wasAdded = true;
}
} else {
while (curClasses.indexOf(" " + className + " ") > -1) {
curClasses = curClasses.replace(
" " + className + " ",
" "
);
}
}
}
this.extraClasses = $.trim(curClasses);
// this.info("-> toggleClass('" + value + "', " + flag + "): '" + this.extraClasses + "'");
return wasAdded;
},
/** Flip expanded status. */
toggleExpanded: function() {
return this.tree._callHook("nodeToggleExpanded", this);
},
/** Flip selection status. */
toggleSelected: function() {
return this.tree._callHook("nodeToggleSelected", this);
},
toString: function() {
return "FancytreeNode@" + this.key + "[title='" + this.title + "']";
// return "<FancytreeNode(#" + this.key + ", '" + this.title + "')>";
},
/**
* Trigger `modifyChild` event on a parent to signal that a child was modified.
* @param {string} operation Type of change: 'add', 'remove', 'rename', 'move', 'data', ...
* @param {FancytreeNode} [childNode]
* @param {object} [extra]
*/
triggerModifyChild: function(operation, childNode, extra) {
var data,
modifyChild = this.tree.options.modifyChild;
if (modifyChild) {
if (childNode && childNode.parent !== this) {
$.error(
"childNode " + childNode + " is not a child of " + this
);
}
data = {
node: this,
tree: this.tree,
operation: operation,
childNode: childNode || null,
};
if (extra) {
$.extend(data, extra);
}
modifyChild({ type: "modifyChild" }, data);
}
},
/**
* Trigger `modifyChild` event on node.parent(!).
* @param {string} operation Type of change: 'add', 'remove', 'rename', 'move', 'data', ...
* @param {object} [extra]
*/
triggerModify: function(operation, extra) {
this.parent.triggerModifyChild(operation, this, extra);
},
/** Call fn(node) for all child nodes in hierarchical order (depth-first).<br>
* Stop iteration, if fn() returns false. Skip current branch, if fn() returns "skip".<br>
* Return false if iteration was stopped.
*
* @param {function} fn the callback function.
* Return false to stop iteration, return "skip" to skip this node and
* its children only.
* @param {boolean} [includeSelf=false]
* @returns {boolean}
*/
visit: function(fn, includeSelf) {
var i,
l,
res = true,
children = this.children;
if (includeSelf === true) {
res = fn(this);
if (res === false || res === "skip") {
return res;
}
}
if (children) {
for (i = 0, l = children.length; i < l; i++) {
res = children[i].visit(fn, true);
if (res === false) {
break;
}
}
}
return res;
},
/** Call fn(node) for all child nodes and recursively load lazy children.<br>
* <b>Note:</b> If you need this method, you probably should consider to review
* your architecture! Recursivley loading nodes is a perfect way for lazy
* programmers to flood the server with requests ;-)
*
* @param {function} [fn] optional callback function.
* Return false to stop iteration, return "skip" to skip this node and
* its children only.
* @param {boolean} [includeSelf=false]
* @returns {$.Promise}
* @since 2.4
*/
visitAndLoad: function(fn, includeSelf, _recursion) {
var dfd,
res,
loaders,
node = this;
// node.debug("visitAndLoad");
if (fn && includeSelf === true) {
res = fn(node);
if (res === false || res === "skip") {
return _recursion ? res : _getResolvedPromise();
}
}
if (!node.children && !node.lazy) {
return _getResolvedPromise();
}
dfd = new $.Deferred();
loaders = [];
// node.debug("load()...");
node.load().done(function() {
// node.debug("load()... done.");
for (var i = 0, l = node.children.length; i < l; i++) {
res = node.children[i].visitAndLoad(fn, true, true);
if (res === false) {
dfd.reject();
break;
} else if (res !== "skip") {
loaders.push(res); // Add promise to the list
}
}
$.when.apply(this, loaders).then(function() {
dfd.resolve();
});
});
return dfd.promise();
},
/** Call fn(node) for all parent nodes, bottom-up, including invisible system root.<br>
* Stop iteration, if fn() returns false.<br>
* Return false if iteration was stopped.
*
* @param {function} fn the callback function.
* Return false to stop iteration, return "skip" to skip this node and children only.
* @param {boolean} [includeSelf=false]
* @returns {boolean}
*/
visitParents: function(fn, includeSelf) {
// Visit parent nodes (bottom up)
if (includeSelf && fn(this) === false) {
return false;
}
var p = this.parent;
while (p) {
if (fn(p) === false) {
return false;
}
p = p.parent;
}
return true;
},
/** Call fn(node) for all sibling nodes.<br>
* Stop iteration, if fn() returns false.<br>
* Return false if iteration was stopped.
*
* @param {function} fn the callback function.
* Return false to stop iteration.
* @param {boolean} [includeSelf=false]
* @returns {boolean}
*/
visitSiblings: function(fn, includeSelf) {
var i,
l,
n,
ac = this.parent.children;
for (i = 0, l = ac.length; i < l; i++) {
n = ac[i];
if (includeSelf || n !== this) {
if (fn(n) === false) {
return false;
}
}
}
return true;
},
/** Write warning to browser console if debugLevel >= 2 (prepending node info)
*
* @param {*} msg string or object or array of such
*/
warn: function(msg) {
if (this.tree.options.debugLevel >= 2) {
Array.prototype.unshift.call(arguments, this.toString());
consoleApply("warn", arguments);
}
},
};
/******************************************************************************
* Fancytree
*/
/**
* Construct a new tree object.
*
* @class Fancytree
* @classdesc The controller behind a fancytree.
* This class also contains 'hook methods': see {@link Fancytree_Hooks}.
*
* @param {Widget} widget
*
* @property {string} _id Automatically generated unique tree instance ID, e.g. "1".
* @property {string} _ns Automatically generated unique tree namespace, e.g. ".fancytree-1".
* @property {FancytreeNode} activeNode Currently active node or null.
* @property {string} ariaPropName Property name of FancytreeNode that contains the element which will receive the aria attributes.
* Typically "li", but "tr" for table extension.
* @property {jQueryObject} $container Outer `<ul>` element (or `<table>` element for ext-table).
* @property {jQueryObject} $div A jQuery object containing the element used to instantiate the tree widget (`widget.element`)
* @property {object|array} columns Recommended place to store shared column meta data. @since 2.27
* @property {object} data Metadata, i.e. properties that may be passed to `source` in addition to a children array.
* @property {object} ext Hash of all active plugin instances.
* @property {FancytreeNode} focusNode Currently focused node or null.
* @property {FancytreeNode} lastSelectedNode Used to implement selectMode 1 (single select)
* @property {string} nodeContainerAttrName Property name of FancytreeNode that contains the outer element of single nodes.
* Typically "li", but "tr" for table extension.
* @property {FancytreeOptions} options Current options, i.e. default options + options passed to constructor.
* @property {FancytreeNode} rootNode Invisible system root node.
* @property {string} statusClassPropName Property name of FancytreeNode that contains the element which will receive the status classes.
* Typically "span", but "tr" for table extension.
* @property {object} types Map for shared type specific meta data, used with node.type attribute. @since 2.27
* @property {object} viewport See ext-vieport. @since v2.31
* @property {object} widget Base widget instance.
*/
function Fancytree(widget) {
this.widget = widget;
this.$div = widget.element;
this.options = widget.options;
if (this.options) {
if (this.options.lazyload !== undefined) {
$.error(
"The 'lazyload' event is deprecated since 2014-02-25. Use 'lazyLoad' (with uppercase L) instead."
);
}
if (this.options.loaderror !== undefined) {
$.error(
"The 'loaderror' event was renamed since 2014-07-03. Use 'loadError' (with uppercase E) instead."
);
}
if (this.options.fx !== undefined) {
$.error(
"The 'fx' option was replaced by 'toggleEffect' since 2014-11-30."
);
}
if (this.options.removeNode !== undefined) {
$.error(
"The 'removeNode' event was replaced by 'modifyChild' since 2.20 (2016-09-10)."
);
}
}
this.ext = {}; // Active extension instances
this.types = {};
this.columns = {};
// allow to init tree.data.foo from <div data-foo=''>
this.data = _getElementDataAsDict(this.$div);
// TODO: use widget.uuid instead?
this._id = "" + (this.options.treeId || $.ui.fancytree._nextId++);
// TODO: use widget.eventNamespace instead?
this._ns = ".fancytree-" + this._id; // append for namespaced events
this.activeNode = null;
this.focusNode = null;
this._hasFocus = null;
this._tempCache = {};
this._lastMousedownNode = null;
this._enableUpdate = true;
this.lastSelectedNode = null;
this.systemFocusElement = null;
this.lastQuicksearchTerm = "";
this.lastQuicksearchTime = 0;
this.viewport = null; // ext-grid
this.statusClassPropName = "span";
this.ariaPropName = "li";
this.nodeContainerAttrName = "li";
// Remove previous markup if any
this.$div.find(">ul.fancytree-container").remove();
// Create a node without parent.
var fakeParent = { tree: this },
$ul;
this.rootNode = new FancytreeNode(fakeParent, {
title: "root",
key: "root_" + this._id,
children: null,
expanded: true,
});
this.rootNode.parent = null;
// Create root markup
$ul = $("<ul>", {
id: "ft-id-" + this._id,
class: "ui-fancytree fancytree-container fancytree-plain",
}).appendTo(this.$div);
this.$container = $ul;
this.rootNode.ul = $ul[0];
if (this.options.debugLevel == null) {
this.options.debugLevel = FT.debugLevel;
}
// // Add container to the TAB chain
// // See http://www.w3.org/TR/wai-aria-practices/#focus_activedescendant
// // #577: Allow to set tabindex to "0", "-1" and ""
// this.$container.attr("tabindex", this.options.tabindex);
// if( this.options.rtl ) {
// this.$container.attr("DIR", "RTL").addClass("fancytree-rtl");
// // }else{
// // this.$container.attr("DIR", null).removeClass("fancytree-rtl");
// }
// if(this.options.aria){
// this.$container.attr("role", "tree");
// if( this.options.selectMode !== 1 ) {
// this.$container.attr("aria-multiselectable", true);
// }
// }
}
Fancytree.prototype = /** @lends Fancytree# */ {
/* Return a context object that can be re-used for _callHook().
* @param {Fancytree | FancytreeNode | EventData} obj
* @param {Event} originalEvent
* @param {Object} extra
* @returns {EventData}
*/
_makeHookContext: function(obj, originalEvent, extra) {
var ctx, tree;
if (obj.node !== undefined) {
// obj is already a context object
if (originalEvent && obj.originalEvent !== originalEvent) {
$.error("invalid args");
}
ctx = obj;
} else if (obj.tree) {
// obj is a FancytreeNode
tree = obj.tree;
ctx = {
node: obj,
tree: tree,
widget: tree.widget,
options: tree.widget.options,
originalEvent: originalEvent,
typeInfo: tree.types[obj.type] || {},
};
} else if (obj.widget) {
// obj is a Fancytree
ctx = {
node: null,
tree: obj,
widget: obj.widget,
options: obj.widget.options,
originalEvent: originalEvent,
};
} else {
$.error("invalid args");
}
if (extra) {
$.extend(ctx, extra);
}
return ctx;
},
/* Trigger a hook function: funcName(ctx, [...]).
*
* @param {string} funcName
* @param {Fancytree|FancytreeNode|EventData} contextObject
* @param {any} [_extraArgs] optional additional arguments
* @returns {any}
*/
_callHook: function(funcName, contextObject, _extraArgs) {
var ctx = this._makeHookContext(contextObject),
fn = this[funcName],
args = Array.prototype.slice.call(arguments, 2);
if (!$.isFunction(fn)) {
$.error("_callHook('" + funcName + "') is not a function");
}
args.unshift(ctx);
// this.debug("_hook", funcName, ctx.node && ctx.node.toString() || ctx.tree.toString(), args);
return fn.apply(this, args);
},
_setExpiringValue: function(key, value, ms) {
this._tempCache[key] = {
value: value,
expire: Date.now() + (+ms || 50),
};
},
_getExpiringValue: function(key) {
var entry = this._tempCache[key];
if (entry && entry.expire > Date.now()) {
return entry.value;
}
delete this._tempCache[key];
return null;
},
/* Check if this tree has extension `name` enabled.
*
* @param {string} name name of the required extension
*/
_usesExtension: function(name) {
return $.inArray(name, this.options.extensions) >= 0;
},
/* Check if current extensions dependencies are met and throw an error if not.
*
* This method may be called inside the `treeInit` hook for custom extensions.
*
* @param {string} name name of the required extension
* @param {boolean} [required=true] pass `false` if the extension is optional, but we want to check for order if it is present
* @param {boolean} [before] `true` if `name` must be included before this, `false` otherwise (use `null` if order doesn't matter)
* @param {string} [message] optional error message (defaults to a descriptve error message)
*/
_requireExtension: function(name, required, before, message) {
if (before != null) {
before = !!before;
}
var thisName = this._local.name,
extList = this.options.extensions,
isBefore =
$.inArray(name, extList) < $.inArray(thisName, extList),
isMissing = required && this.ext[name] == null,
badOrder = !isMissing && before != null && before !== isBefore;
_assert(
thisName && thisName !== name,
"invalid or same name '" + thisName + "' (require yourself?)"
);
if (isMissing || badOrder) {
if (!message) {
if (isMissing || required) {
message =
"'" +
thisName +
"' extension requires '" +
name +
"'";
if (badOrder) {
message +=
" to be registered " +
(before ? "before" : "after") +
" itself";
}
} else {
message =
"If used together, `" +
name +
"` must be registered " +
(before ? "before" : "after") +
" `" +
thisName +
"`";
}
}
$.error(message);
return false;
}
return true;
},
/** Activate node with a given key and fire focus and activate events.
*
* A previously activated node will be deactivated.
* If activeVisible option is set, all parents will be expanded as necessary.
* Pass key = false, to deactivate the current node only.
* @param {string} key
* @param {object} [opts] additional options. Defaults to {noEvents: false, noFocus: false}
* @returns {FancytreeNode} activated node (null, if not found)
*/
activateKey: function(key, opts) {
var node = this.getNodeByKey(key);
if (node) {
node.setActive(true, opts);
} else if (this.activeNode) {
this.activeNode.setActive(false, opts);
}
return node;
},
/** (experimental) Add child status nodes that indicate 'More...', ....
* @param {boolean|object} node optional node definition. Pass `false` to remove all paging nodes.
* @param {string} [mode='append'] 'child'|firstChild'
* @since 2.15
*/
addPagingNode: function(node, mode) {
return this.rootNode.addPagingNode(node, mode);
},
/**
* (experimental) Apply a modification (or navigation) operation.
*
* Valid commands:
* - 'moveUp', 'moveDown'
* - 'indent', 'outdent'
* - 'remove'
* - 'edit', 'addChild', 'addSibling': (reqires ext-edit extension)
* - 'cut', 'copy', 'paste': (use an internal singleton 'clipboard')
* - 'down', 'first', 'last', 'left', 'parent', 'right', 'up': navigate
*
* @param {string} cmd
* @param {FancytreeNode} [node=active_node]
* @param {object} [opts] Currently unused
*
* @since 2.32
*/
applyCommand: function(cmd, node, opts_) {
var // clipboard,
refNode;
// opts = $.extend(
// { setActive: true, clipboard: CLIPBOARD },
// opts_
// );
node = node || this.getActiveNode();
// clipboard = opts.clipboard;
switch (cmd) {
// Sorting and indentation:
case "moveUp":
refNode = node.getPrevSibling();
if (refNode) {
node.moveTo(refNode, "before");
node.setActive();
}
break;
case "moveDown":
refNode = node.getNextSibling();
if (refNode) {
node.moveTo(refNode, "after");
node.setActive();
}
break;
case "indent":
refNode = node.getPrevSibling();
if (refNode) {
node.moveTo(refNode, "child");
refNode.setExpanded();
node.setActive();
}
break;
case "outdent":
if (!node.isTopLevel()) {
node.moveTo(node.getParent(), "after");
node.setActive();
}
break;
// Remove:
case "remove":
refNode = node.getPrevSibling() || node.getParent();
node.remove();
if (refNode) {
refNode.setActive();
}
break;
// Add, edit (requires ext-edit):
case "addChild":
node.editCreateNode("child", "");
break;
case "addSibling":
node.editCreateNode("after", "");
break;
case "rename":
node.editStart();
break;
// Simple clipboard simulation:
// case "cut":
// clipboard = { mode: cmd, data: node };
// break;
// case "copy":
// clipboard = {
// mode: cmd,
// data: node.toDict(function(d, n) {
// delete d.key;
// }),
// };
// break;
// case "clear":
// clipboard = null;
// break;
// case "paste":
// if (clipboard.mode === "cut") {
// // refNode = node.getPrevSibling();
// clipboard.data.moveTo(node, "child");
// clipboard.data.setActive();
// } else if (clipboard.mode === "copy") {
// node.addChildren(clipboard.data).setActive();
// }
// break;
// Navigation commands:
case "down":
case "first":
case "last":
case "left":
case "parent":
case "right":
case "up":
return node.navigate(cmd);
default:
$.error("Unhandled command: '" + cmd + "'");
}
},
/** (experimental) Modify existing data model.
*
* @param {Array} patchList array of [key, NodePatch] arrays
* @returns {$.Promise} resolved, when all patches have been applied
* @see TreePatch
*/
applyPatch: function(patchList) {
var dfd,
i,
p2,
key,
patch,
node,
patchCount = patchList.length,
deferredList = [];
for (i = 0; i < patchCount; i++) {
p2 = patchList[i];
_assert(
p2.length === 2,
"patchList must be an array of length-2-arrays"
);
key = p2[0];
patch = p2[1];
node = key === null ? this.rootNode : this.getNodeByKey(key);
if (node) {
dfd = new $.Deferred();
deferredList.push(dfd);
node.applyPatch(patch).always(_makeResolveFunc(dfd, node));
} else {
this.warn("could not find node with key '" + key + "'");
}
}
// Return a promise that is resolved, when ALL patches were applied
return $.when.apply($, deferredList).promise();
},
/* TODO: implement in dnd extension
cancelDrag: function() {
var dd = $.ui.ddmanager.current;
if(dd){
dd.cancel();
}
},
*/
/** Remove all nodes.
* @since 2.14
*/
clear: function(source) {
this._callHook("treeClear", this);
},
/** Return the number of nodes.
* @returns {integer}
*/
count: function() {
return this.rootNode.countChildren();
},
/** Write to browser console if debugLevel >= 4 (prepending tree name)
*
* @param {*} msg string or object or array of such
*/
debug: function(msg) {
if (this.options.debugLevel >= 4) {
Array.prototype.unshift.call(arguments, this.toString());
consoleApply("log", arguments);
}
},
/** Destroy this widget, restore previous markup and cleanup resources.
*
* @since 2.34
*/
destroy: function() {
this.widget.destroy();
},
/** Enable (or disable) the tree control.
*
* @param {boolean} [flag=true] pass false to disable
* @since 2.30
*/
enable: function(flag) {
if (flag === false) {
this.widget.disable();
} else {
this.widget.enable();
}
},
/** Temporarily suppress rendering to improve performance on bulk-updates.
*
* @param {boolean} flag
* @returns {boolean} previous status
* @since 2.19
*/
enableUpdate: function(flag) {
flag = flag !== false;
if (!!this._enableUpdate === !!flag) {
return flag;
}
this._enableUpdate = flag;
if (flag) {
this.debug("enableUpdate(true): redraw "); //, this._dirtyRoots);
this._callHook("treeStructureChanged", this, "enableUpdate");
this.render();
} else {
// this._dirtyRoots = null;
this.debug("enableUpdate(false)...");
}
return !flag; // return previous value
},
/** Write error to browser console if debugLevel >= 1 (prepending tree info)
*
* @param {*} msg string or object or array of such
*/
error: function(msg) {
if (this.options.debugLevel >= 1) {
Array.prototype.unshift.call(arguments, this.toString());
consoleApply("error", arguments);
}
},
/** Expand (or collapse) all parent nodes.
*
* This convenience method uses `tree.visit()` and `tree.setExpanded()`
* internally.
*
* @param {boolean} [flag=true] pass false to collapse
* @param {object} [opts] passed to setExpanded()
* @since 2.30
*/
expandAll: function(flag, opts) {
var prev = this.enableUpdate(false);
flag = flag !== false;
this.visit(function(node) {
if (
node.hasChildren() !== false &&
node.isExpanded() !== flag
) {
node.setExpanded(flag, opts);
}
});
this.enableUpdate(prev);
},
/**Find all nodes that matches condition.
*
* @param {string | function(node)} match title string to search for, or a
* callback function that returns `true` if a node is matched.
* @returns {FancytreeNode[]} array of nodes (may be empty)
* @see FancytreeNode#findAll
* @since 2.12
*/
findAll: function(match) {
return this.rootNode.findAll(match);
},
/**Find first node that matches condition.
*
* @param {string | function(node)} match title string to search for, or a
* callback function that returns `true` if a node is matched.
* @returns {FancytreeNode} matching node or null
* @see FancytreeNode#findFirst
* @since 2.12
*/
findFirst: function(match) {
return this.rootNode.findFirst(match);
},
/** Find the next visible node that starts with `match`, starting at `startNode`
* and wrap-around at the end.
*
* @param {string|function} match
* @param {FancytreeNode} [startNode] defaults to first node
* @returns {FancytreeNode} matching node or null
*/
findNextNode: function(match, startNode) {
//, visibleOnly) {
var res = null,
firstNode = this.getFirstChild();
match =
typeof match === "string"
? _makeNodeTitleStartMatcher(match)
: match;
startNode = startNode || firstNode;
function _checkNode(n) {
// console.log("_check " + n)
if (match(n)) {
res = n;
}
if (res || n === startNode) {
return false;
}
}
this.visitRows(_checkNode, {
start: startNode,
includeSelf: false,
});
// Wrap around search
if (!res && startNode !== firstNode) {
this.visitRows(_checkNode, {
start: firstNode,
includeSelf: true,
});
}
return res;
},
/** Find a node relative to another node.
*
* @param {FancytreeNode} node
* @param {string|number} where 'down', 'first', 'last', 'left', 'parent', 'right', or 'up'.
* (Alternatively the keyCode that would normally trigger this move,
* e.g. `$.ui.keyCode.LEFT` = 'left'.
* @param {boolean} [includeHidden=false] Not yet implemented
* @returns {FancytreeNode|null}
* @since v2.31
*/
findRelatedNode: function(node, where, includeHidden) {
var res = null,
KC = $.ui.keyCode;
switch (where) {
case "parent":
case KC.BACKSPACE:
if (node.parent && node.parent.parent) {
res = node.parent;
}
break;
case "first":
case KC.HOME:
// First visible node
this.visit(function(n) {
if (n.isVisible()) {
res = n;
return false;
}
});
break;
case "last":
case KC.END:
this.visit(function(n) {
// last visible node
if (n.isVisible()) {
res = n;
}
});
break;
case "left":
case KC.LEFT:
if (node.expanded) {
node.setExpanded(false);
} else if (node.parent && node.parent.parent) {
res = node.parent;
}
break;
case "right":
case KC.RIGHT:
if (!node.expanded && (node.children || node.lazy)) {
node.setExpanded();
res = node;
} else if (node.children && node.children.length) {
res = node.children[0];
}
break;
case "up":
case KC.UP:
this.visitRows(
function(n) {
res = n;
return false;
},
{ start: node, reverse: true, includeSelf: false }
);
break;
case "down":
case KC.DOWN:
this.visitRows(
function(n) {
res = n;
return false;
},
{ start: node, includeSelf: false }
);
break;
default:
this.tree.warn("Unknown relation '" + where + "'.");
}
return res;
},
// TODO: fromDict
/**
* Generate INPUT elements that can be submitted with html forms.
*
* In selectMode 3 only the topmost selected nodes are considered, unless
* `opts.stopOnParents: false` is passed.
*
* @example
* // Generate input elements for active and selected nodes
* tree.generateFormElements();
* // Generate input elements selected nodes, using a custom `name` attribute
* tree.generateFormElements("cust_sel", false);
* // Generate input elements using a custom filter
* tree.generateFormElements(true, true, { filter: function(node) {
* return node.isSelected() && node.data.yes;
* }});
*
* @param {boolean | string} [selected=true] Pass false to disable, pass a string to override the field name (default: 'ft_ID[]')
* @param {boolean | string} [active=true] Pass false to disable, pass a string to override the field name (default: 'ft_ID_active')
* @param {object} [opts] default { filter: null, stopOnParents: true }
*/
generateFormElements: function(selected, active, opts) {
opts = opts || {};
var nodeList,
selectedName =
typeof selected === "string"
? selected
: "ft_" + this._id + "[]",
activeName =
typeof active === "string"
? active
: "ft_" + this._id + "_active",
id = "fancytree_result_" + this._id,
$result = $("#" + id),
stopOnParents =
this.options.selectMode === 3 &&
opts.stopOnParents !== false;
if ($result.length) {
$result.empty();
} else {
$result = $("<div>", {
id: id,
})
.hide()
.insertAfter(this.$container);
}
if (active !== false && this.activeNode) {
$result.append(
$("<input>", {
type: "radio",
name: activeName,
value: this.activeNode.key,
checked: true,
})
);
}
function _appender(node) {
$result.append(
$("<input>", {
type: "checkbox",
name: selectedName,
value: node.key,
checked: true,
})
);
}
if (opts.filter) {
this.visit(function(node) {
var res = opts.filter(node);
if (res === "skip") {
return res;
}
if (res !== false) {
_appender(node);
}
});
} else if (selected !== false) {
nodeList = this.getSelectedNodes(stopOnParents);
$.each(nodeList, function(idx, node) {
_appender(node);
});
}
},
/**
* Return the currently active node or null.
* @returns {FancytreeNode}
*/
getActiveNode: function() {
return this.activeNode;
},
/** Return the first top level node if any (not the invisible root node).
* @returns {FancytreeNode | null}
*/
getFirstChild: function() {
return this.rootNode.getFirstChild();
},
/**
* Return node that has keyboard focus or null.
* @returns {FancytreeNode}
*/
getFocusNode: function() {
return this.focusNode;
},
/**
* Return current option value.
* (Note: this is the preferred variant of `$().fancytree("option", "KEY")`)
*
* @param {string} name option name (may contain '.')
* @returns {any}
*/
getOption: function(optionName) {
return this.widget.option(optionName);
},
/**
* Return node with a given key or null if not found.
*
* @param {string} key
* @param {FancytreeNode} [searchRoot] only search below this node
* @returns {FancytreeNode | null}
*/
getNodeByKey: function(key, searchRoot) {
// Search the DOM by element ID (assuming this is faster than traversing all nodes).
var el, match;
// TODO: use tree.keyMap if available
// TODO: check opts.generateIds === true
if (!searchRoot) {
el = document.getElementById(this.options.idPrefix + key);
if (el) {
return el.ftnode ? el.ftnode : null;
}
}
// Not found in the DOM, but still may be in an unrendered part of tree
searchRoot = searchRoot || this.rootNode;
match = null;
key = "" + key; // Convert to string (#1005)
searchRoot.visit(function(node) {
if (node.key === key) {
match = node;
return false; // Stop iteration
}
}, true);
return match;
},
/** Return the invisible system root node.
* @returns {FancytreeNode}
*/
getRootNode: function() {
return this.rootNode;
},
/**
* Return an array of selected nodes.
*
* Note: you cannot send this result via Ajax directly. Instead the
* node object need to be converted to plain objects, for example
* by using `$.map()` and `node.toDict()`.
* @param {boolean} [stopOnParents=false] only return the topmost selected
* node (useful with selectMode 3)
* @returns {FancytreeNode[]}
*/
getSelectedNodes: function(stopOnParents) {
return this.rootNode.getSelectedNodes(stopOnParents);
},
/** Return true if the tree control has keyboard focus
* @returns {boolean}
*/
hasFocus: function() {
// var ae = document.activeElement,
// hasFocus = !!(
// ae && $(ae).closest(".fancytree-container").length
// );
// if (hasFocus !== !!this._hasFocus) {
// this.warn(
// "hasFocus(): fix inconsistent container state, now: " +
// hasFocus
// );
// this._hasFocus = hasFocus;
// this.$container.toggleClass("fancytree-treefocus", hasFocus);
// }
// return hasFocus;
return !!this._hasFocus;
},
/** Write to browser console if debugLevel >= 3 (prepending tree name)
* @param {*} msg string or object or array of such
*/
info: function(msg) {
if (this.options.debugLevel >= 3) {
Array.prototype.unshift.call(arguments, this.toString());
consoleApply("info", arguments);
}
},
/** Return true if any node is currently beeing loaded, i.e. a Ajax request is pending.
* @returns {boolean}
* @since 2.32
*/
isLoading: function() {
var res = false;
this.rootNode.visit(function(n) {
// also visit rootNode
if (n._isLoading || n._requestId) {
res = true;
return false;
}
}, true);
return res;
},
/*
TODO: isInitializing: function() {
return ( this.phase=="init" || this.phase=="postInit" );
},
TODO: isReloading: function() {
return ( this.phase=="init" || this.phase=="postInit" ) && this.options.persist && this.persistence.cookiesFound;
},
TODO: isUserEvent: function() {
return ( this.phase=="userEvent" );
},
*/
/**
* Make sure that a node with a given ID is loaded, by traversing - and
* loading - its parents. This method is meant for lazy hierarchies.
* A callback is executed for every node as we go.
* @example
* // Resolve using node.key:
* tree.loadKeyPath("/_3/_23/_26/_27", function(node, status){
* if(status === "loaded") {
* console.log("loaded intermediate node " + node);
* }else if(status === "ok") {
* node.activate();
* }
* });
* // Use deferred promise:
* tree.loadKeyPath("/_3/_23/_26/_27").progress(function(data){
* if(data.status === "loaded") {
* console.log("loaded intermediate node " + data.node);
* }else if(data.status === "ok") {
* node.activate();
* }
* }).done(function(){
* ...
* });
* // Custom path segment resolver:
* tree.loadKeyPath("/321/431/21/2", {
* matchKey: function(node, key){
* return node.data.refKey === key;
* },
* callback: function(node, status){
* if(status === "loaded") {
* console.log("loaded intermediate node " + node);
* }else if(status === "ok") {
* node.activate();
* }
* }
* });
* @param {string | string[]} keyPathList one or more key paths (e.g. '/3/2_1/7')
* @param {function | object} optsOrCallback callback(node, status) is called for every visited node ('loading', 'loaded', 'ok', 'error').
* Pass an object to define custom key matchers for the path segments: {callback: function, matchKey: function}.
* @returns {$.Promise}
*/
loadKeyPath: function(keyPathList, optsOrCallback) {
var callback,
i,
path,
self = this,
dfd = new $.Deferred(),
parent = this.getRootNode(),
sep = this.options.keyPathSeparator,
pathSegList = [],
opts = $.extend({}, optsOrCallback);
// Prepare options
if (typeof optsOrCallback === "function") {
callback = optsOrCallback;
} else if (optsOrCallback && optsOrCallback.callback) {
callback = optsOrCallback.callback;
}
opts.callback = function(ctx, node, status) {
if (callback) {
callback.call(ctx, node, status);
}
dfd.notifyWith(ctx, [{ node: node, status: status }]);
};
if (opts.matchKey == null) {
opts.matchKey = function(node, key) {
return node.key === key;
};
}
// Convert array of path strings to array of segment arrays
if (!$.isArray(keyPathList)) {
keyPathList = [keyPathList];
}
for (i = 0; i < keyPathList.length; i++) {
path = keyPathList[i];
// strip leading slash
if (path.charAt(0) === sep) {
path = path.substr(1);
}
// segListMap[path] = { parent: parent, segList: path.split(sep) };
pathSegList.push(path.split(sep));
// targetList.push({ parent: parent, segList: path.split(sep)/* , path: path*/});
}
// The timeout forces async behavior always (even if nodes are all loaded)
// This way a potential progress() event will fire.
setTimeout(function() {
self._loadKeyPathImpl(dfd, opts, parent, pathSegList).done(
function() {
dfd.resolve();
}
);
}, 0);
return dfd.promise();
},
/*
* Resolve a list of paths, relative to one parent node.
*/
_loadKeyPathImpl: function(dfd, opts, parent, pathSegList) {
var deferredList,
i,
key,
node,
nodeKey,
remain,
remainMap,
tmpParent,
segList,
subDfd,
self = this;
function __findChild(parent, key) {
// console.log("__findChild", key, parent);
var i,
l,
cl = parent.children;
if (cl) {
for (i = 0, l = cl.length; i < l; i++) {
if (opts.matchKey(cl[i], key)) {
return cl[i];
}
}
}
return null;
}
// console.log("_loadKeyPathImpl, parent=", parent, ", pathSegList=", pathSegList);
// Pass 1:
// Handle all path segments for nodes that are already loaded.
// Collect distinct top-most lazy nodes in a map.
// Note that we can use node.key to de-dupe entries, even if a custom matcher would
// look for other node attributes.
// map[node.key] => {node: node, pathList: [list of remaining rest-paths]}
remainMap = {};
for (i = 0; i < pathSegList.length; i++) {
segList = pathSegList[i];
// target = targetList[i];
// Traverse and pop path segments (i.e. keys), until we hit a lazy, unloaded node
tmpParent = parent;
while (segList.length) {
key = segList.shift();
node = __findChild(tmpParent, key);
if (!node) {
this.warn(
"loadKeyPath: key not found: " +
key +
" (parent: " +
tmpParent +
")"
);
opts.callback(this, key, "error");
break;
} else if (segList.length === 0) {
opts.callback(this, node, "ok");
break;
} else if (!node.lazy || node.hasChildren() !== undefined) {
opts.callback(this, node, "loaded");
tmpParent = node;
} else {
opts.callback(this, node, "loaded");
key = node.key; //target.segList.join(sep);
if (remainMap[key]) {
remainMap[key].pathSegList.push(segList);
} else {
remainMap[key] = {
parent: node,
pathSegList: [segList],
};
}
break;
}
}
}
// console.log("_loadKeyPathImpl AFTER pass 1, remainMap=", remainMap);
// Now load all lazy nodes and continue iteration for remaining paths
deferredList = [];
// Avoid jshint warning 'Don't make functions within a loop.':
function __lazyload(dfd, parent, pathSegList) {
// console.log("__lazyload", parent, "pathSegList=", pathSegList);
opts.callback(self, parent, "loading");
parent
.load()
.done(function() {
self._loadKeyPathImpl
.call(self, dfd, opts, parent, pathSegList)
.always(_makeResolveFunc(dfd, self));
})
.fail(function(errMsg) {
self.warn("loadKeyPath: error loading lazy " + parent);
opts.callback(self, node, "error");
dfd.rejectWith(self);
});
}
// remainMap contains parent nodes, each with a list of relative sub-paths.
// We start loading all of them now, and pass the the list to each loader.
for (nodeKey in remainMap) {
if (remainMap.hasOwnProperty(nodeKey)) {
remain = remainMap[nodeKey];
// console.log("for(): remain=", remain, "remainMap=", remainMap);
// key = remain.segList.shift();
// node = __findChild(remain.parent, key);
// if (node == null) { // #576
// // Issue #576, refactored for v2.27:
// // The root cause was, that sometimes the wrong parent was used here
// // to find the next segment.
// // Falling back to getNodeByKey() was a hack that no longer works if a custom
// // matcher is used, because we cannot assume that a single segment-key is unique
// // throughout the tree.
// self.error("loadKeyPath: error loading child by key '" + key + "' (parent: " + target.parent + ")", target);
// // node = self.getNodeByKey(key);
// continue;
// }
subDfd = new $.Deferred();
deferredList.push(subDfd);
__lazyload(subDfd, remain.parent, remain.pathSegList);
}
}
// Return a promise that is resolved, when ALL paths were loaded
return $.when.apply($, deferredList).promise();
},
/** Re-fire beforeActivate, activate, and (optional) focus events.
* Calling this method in the `init` event, will activate the node that
* was marked 'active' in the source data, and optionally set the keyboard
* focus.
* @param [setFocus=false]
*/
reactivate: function(setFocus) {
var res,
node = this.activeNode;
if (!node) {
return _getResolvedPromise();
}
this.activeNode = null; // Force re-activating
res = node.setActive(true, { noFocus: true });
if (setFocus) {
node.setFocus();
}
return res;
},
/** Reload tree from source and return a promise.
* @param [source] optional new source (defaults to initial source data)
* @returns {$.Promise}
*/
reload: function(source) {
this._callHook("treeClear", this);
return this._callHook("treeLoad", this, source);
},
/**Render tree (i.e. create DOM elements for all top-level nodes).
* @param {boolean} [force=false] create DOM elemnts, even if parent is collapsed
* @param {boolean} [deep=false]
*/
render: function(force, deep) {
return this.rootNode.render(force, deep);
},
/**(De)select all nodes.
* @param {boolean} [flag=true]
* @since 2.28
*/
selectAll: function(flag) {
this.visit(function(node) {
node.setSelected(flag);
});
},
// TODO: selectKey: function(key, select)
// TODO: serializeArray: function(stopOnParents)
/**
* @param {boolean} [flag=true]
*/
setFocus: function(flag) {
return this._callHook("treeSetFocus", this, flag);
},
/**
* Set current option value.
* (Note: this is the preferred variant of `$().fancytree("option", "KEY", VALUE)`)
* @param {string} name option name (may contain '.')
* @param {any} new value
*/
setOption: function(optionName, value) {
return this.widget.option(optionName, value);
},
/**
* Call console.time() when in debug mode (verbose >= 4).
*
* @param {string} label
*/
debugTime: function(label) {
if (this.options.debugLevel >= 4) {
window.console.time(this + " - " + label);
}
},
/**
* Call console.timeEnd() when in debug mode (verbose >= 4).
*
* @param {string} label
*/
debugTimeEnd: function(label) {
if (this.options.debugLevel >= 4) {
window.console.timeEnd(this + " - " + label);
}
},
/**
* Return all nodes as nested list of {@link NodeData}.
*
* @param {boolean} [includeRoot=false] Returns the hidden system root node (and its children)
* @param {function} [callback] callback(dict, node) is called for every node, in order to allow modifications.
* Return `false` to ignore this node or "skip" to include this node without its children.
* @returns {Array | object}
* @see FancytreeNode#toDict
*/
toDict: function(includeRoot, callback) {
var res = this.rootNode.toDict(true, callback);
return includeRoot ? res : res.children;
},
/* Implicitly called for string conversions.
* @returns {string}
*/
toString: function() {
return "Fancytree@" + this._id;
// return "<Fancytree(#" + this._id + ")>";
},
/* _trigger a widget event with additional node ctx.
* @see EventData
*/
_triggerNodeEvent: function(type, node, originalEvent, extra) {
// this.debug("_trigger(" + type + "): '" + ctx.node.title + "'", ctx);
var ctx = this._makeHookContext(node, originalEvent, extra),
res = this.widget._trigger(type, originalEvent, ctx);
if (res !== false && ctx.result !== undefined) {
return ctx.result;
}
return res;
},
/* _trigger a widget event with additional tree data. */
_triggerTreeEvent: function(type, originalEvent, extra) {
// this.debug("_trigger(" + type + ")", ctx);
var ctx = this._makeHookContext(this, originalEvent, extra),
res = this.widget._trigger(type, originalEvent, ctx);
if (res !== false && ctx.result !== undefined) {
return ctx.result;
}
return res;
},
/** Call fn(node) for all nodes in hierarchical order (depth-first).
*
* @param {function} fn the callback function.
* Return false to stop iteration, return "skip" to skip this node and children only.
* @returns {boolean} false, if the iterator was stopped.
*/
visit: function(fn) {
return this.rootNode.visit(fn, false);
},
/** Call fn(node) for all nodes in vertical order, top down (or bottom up).<br>
* Stop iteration, if fn() returns false.<br>
* Return false if iteration was stopped.
*
* @param {function} fn the callback function.
* Return false to stop iteration, return "skip" to skip this node and children only.
* @param {object} [options]
* Defaults:
* {start: First top node, reverse: false, includeSelf: true, includeHidden: false}
* @returns {boolean} false if iteration was cancelled
* @since 2.28
*/
visitRows: function(fn, opts) {
if (!this.rootNode.hasChildren()) {
return false;
}
if (opts && opts.reverse) {
delete opts.reverse;
return this._visitRowsUp(fn, opts);
}
opts = opts || {};
var i,
nextIdx,
parent,
res,
siblings,
siblingOfs = 0,
skipFirstNode = opts.includeSelf === false,
includeHidden = !!opts.includeHidden,
checkFilter = !includeHidden && this.enableFilter,
node = opts.start || this.rootNode.children[0];
parent = node.parent;
while (parent) {
// visit siblings
siblings = parent.children;
nextIdx = siblings.indexOf(node) + siblingOfs;
for (i = nextIdx; i < siblings.length; i++) {
node = siblings[i];
if (checkFilter && !node.match && !node.subMatchCount) {
continue;
}
if (!skipFirstNode && fn(node) === false) {
return false;
}
skipFirstNode = false;
// Dive into node's child nodes
if (
node.children &&
node.children.length &&
(includeHidden || node.expanded)
) {
// Disable warning: Functions declared within loops referencing an outer
// scoped variable may lead to confusing semantics:
/*jshint -W083 */
res = node.visit(function(n) {
if (checkFilter && !n.match && !n.subMatchCount) {
return "skip";
}
if (fn(n) === false) {
return false;
}
if (!includeHidden && n.children && !n.expanded) {
return "skip";
}
}, false);
/*jshint +W083 */
if (res === false) {
return false;
}
}
}
// Visit parent nodes (bottom up)
node = parent;
parent = parent.parent;
siblingOfs = 1; //
}
return true;
},
/* Call fn(node) for all nodes in vertical order, bottom up.
*/
_visitRowsUp: function(fn, opts) {
var children,
idx,
parent,
includeHidden = !!opts.includeHidden,
node = opts.start || this.rootNode.children[0];
while (true) {
parent = node.parent;
children = parent.children;
if (children[0] === node) {
// If this is already the first sibling, goto parent
node = parent;
if (!node.parent) {
break; // first node of the tree
}
children = parent.children;
} else {
// Otherwise, goto prev. sibling
idx = children.indexOf(node);
node = children[idx - 1];
// If the prev. sibling has children, follow down to last descendant
while (
// See: https://github.com/eslint/eslint/issues/11302
// eslint-disable-next-line no-unmodified-loop-condition
(includeHidden || node.expanded) &&
node.children &&
node.children.length
) {
children = node.children;
parent = node;
node = children[children.length - 1];
}
}
// Skip invisible
if (!includeHidden && !node.isVisible()) {
continue;
}
if (fn(node) === false) {
return false;
}
}
},
/** Write warning to browser console if debugLevel >= 2 (prepending tree info)
*
* @param {*} msg string or object or array of such
*/
warn: function(msg) {
if (this.options.debugLevel >= 2) {
Array.prototype.unshift.call(arguments, this.toString());
consoleApply("warn", arguments);
}
},
};
/**
* These additional methods of the {@link Fancytree} class are 'hook functions'
* that can be used and overloaded by extensions.
*
* @see [writing extensions](https://github.com/mar10/fancytree/wiki/TutorialExtensions)
* @mixin Fancytree_Hooks
*/
$.extend(
Fancytree.prototype,
/** @lends Fancytree_Hooks# */
{
/** Default handling for mouse click events.
*
* @param {EventData} ctx
*/
nodeClick: function(ctx) {
var activate,
expand,
// event = ctx.originalEvent,
targetType = ctx.targetType,
node = ctx.node;
// this.debug("ftnode.onClick(" + event.type + "): ftnode:" + this + ", button:" + event.button + ", which: " + event.which, ctx);
// TODO: use switch
// TODO: make sure clicks on embedded <input> doesn't steal focus (see table sample)
if (targetType === "expander") {
if (node.isLoading()) {
// #495: we probably got a click event while a lazy load is pending.
// The 'expanded' state is not yet set, so 'toggle' would expand
// and trigger lazyLoad again.
// It would be better to allow to collapse/expand the status node
// while loading (instead of ignoring), but that would require some
// more work.
node.debug("Got 2nd click while loading: ignored");
return;
}
// Clicking the expander icon always expands/collapses
this._callHook("nodeToggleExpanded", ctx);
} else if (targetType === "checkbox") {
// Clicking the checkbox always (de)selects
this._callHook("nodeToggleSelected", ctx);
if (ctx.options.focusOnSelect) {
// #358
this._callHook("nodeSetFocus", ctx, true);
}
} else {
// Honor `clickFolderMode` for
expand = false;
activate = true;
if (node.folder) {
switch (ctx.options.clickFolderMode) {
case 2: // expand only
expand = true;
activate = false;
break;
case 3: // expand and activate
activate = true;
expand = true; //!node.isExpanded();
break;
// else 1 or 4: just activate
}
}
if (activate) {
this.nodeSetFocus(ctx);
this._callHook("nodeSetActive", ctx, true);
}
if (expand) {
if (!activate) {
// this._callHook("nodeSetFocus", ctx);
}
// this._callHook("nodeSetExpanded", ctx, true);
this._callHook("nodeToggleExpanded", ctx);
}
}
// Make sure that clicks stop, otherwise <a href='#'> jumps to the top
// if(event.target.localName === "a" && event.target.className === "fancytree-title"){
// event.preventDefault();
// }
// TODO: return promise?
},
/** Collapse all other children of same parent.
*
* @param {EventData} ctx
* @param {object} callOpts
*/
nodeCollapseSiblings: function(ctx, callOpts) {
// TODO: return promise?
var ac,
i,
l,
node = ctx.node;
if (node.parent) {
ac = node.parent.children;
for (i = 0, l = ac.length; i < l; i++) {
if (ac[i] !== node && ac[i].expanded) {
this._callHook(
"nodeSetExpanded",
ac[i],
false,
callOpts
);
}
}
}
},
/** Default handling for mouse douleclick events.
* @param {EventData} ctx
*/
nodeDblclick: function(ctx) {
// TODO: return promise?
if (
ctx.targetType === "title" &&
ctx.options.clickFolderMode === 4
) {
// this.nodeSetFocus(ctx);
// this._callHook("nodeSetActive", ctx, true);
this._callHook("nodeToggleExpanded", ctx);
}
// TODO: prevent text selection on dblclicks
if (ctx.targetType === "title") {
ctx.originalEvent.preventDefault();
}
},
/** Default handling for mouse keydown events.
*
* NOTE: this may be called with node == null if tree (but no node) has focus.
* @param {EventData} ctx
*/
nodeKeydown: function(ctx) {
// TODO: return promise?
var matchNode,
stamp,
_res,
focusNode,
event = ctx.originalEvent,
node = ctx.node,
tree = ctx.tree,
opts = ctx.options,
which = event.which,
// #909: Use event.key, to get unicode characters.
// We can't use `/\w/.test(key)`, because that would
// only detect plain ascii alpha-numerics. But we still need
// to ignore modifier-only, whitespace, cursor-keys, etc.
key = event.key || String.fromCharCode(which),
specialModifiers = !!(
event.altKey ||
event.ctrlKey ||
event.metaKey
),
isAlnum =
!MODIFIERS[which] &&
!SPECIAL_KEYCODES[which] &&
!specialModifiers,
$target = $(event.target),
handled = true,
activate = !(event.ctrlKey || !opts.autoActivate);
// (node || FT).debug("ftnode.nodeKeydown(" + event.type + "): ftnode:" + this + ", charCode:" + event.charCode + ", keyCode: " + event.keyCode + ", which: " + event.which);
// FT.debug( "eventToString(): " + FT.eventToString(event) + ", key='" + key + "', isAlnum: " + isAlnum );
// Set focus to active (or first node) if no other node has the focus yet
if (!node) {
focusNode = this.getActiveNode() || this.getFirstChild();
if (focusNode) {
focusNode.setFocus();
node = ctx.node = this.focusNode;
node.debug("Keydown force focus on active node");
}
}
if (
opts.quicksearch &&
isAlnum &&
!$target.is(":input:enabled")
) {
// Allow to search for longer streaks if typed in quickly
stamp = Date.now();
if (stamp - tree.lastQuicksearchTime > 500) {
tree.lastQuicksearchTerm = "";
}
tree.lastQuicksearchTime = stamp;
tree.lastQuicksearchTerm += key;
// tree.debug("quicksearch find", tree.lastQuicksearchTerm);
matchNode = tree.findNextNode(
tree.lastQuicksearchTerm,
tree.getActiveNode()
);
if (matchNode) {
matchNode.setActive();
}
event.preventDefault();
return;
}
switch (FT.eventToString(event)) {
case "+":
case "=": // 187: '+' @ Chrome, Safari
tree.nodeSetExpanded(ctx, true);
break;
case "-":
tree.nodeSetExpanded(ctx, false);
break;
case "space":
if (node.isPagingNode()) {
tree._triggerNodeEvent("clickPaging", ctx, event);
} else if (
FT.evalOption("checkbox", node, node, opts, false)
) {
// #768
tree.nodeToggleSelected(ctx);
} else {
tree.nodeSetActive(ctx, true);
}
break;
case "return":
tree.nodeSetActive(ctx, true);
break;
case "home":
case "end":
case "backspace":
case "left":
case "right":
case "up":
case "down":
_res = node.navigate(event.which, activate);
break;
default:
handled = false;
}
if (handled) {
event.preventDefault();
}
},
// /** Default handling for mouse keypress events. */
// nodeKeypress: function(ctx) {
// var event = ctx.originalEvent;
// },
// /** Trigger lazyLoad event (async). */
// nodeLazyLoad: function(ctx) {
// var node = ctx.node;
// if(this._triggerNodeEvent())
// },
/** Load child nodes (async).
*
* @param {EventData} ctx
* @param {object[]|object|string|$.Promise|function} source
* @returns {$.Promise} The deferred will be resolved as soon as the (ajax)
* data was rendered.
*/
nodeLoadChildren: function(ctx, source) {
var ajax,
delay,
ajaxDfd = null,
resultDfd,
isAsync = true,
tree = ctx.tree,
node = ctx.node,
nodePrevParent = node.parent,
tag = "nodeLoadChildren",
requestId = Date.now();
// `source` is a callback: use the returned result instead:
if ($.isFunction(source)) {
source = source.call(tree, { type: "source" }, ctx);
_assert(
!$.isFunction(source),
"source callback must not return another function"
);
}
// `source` is already a promise:
if ($.isFunction(source.then)) {
// _assert($.isFunction(source.always), "Expected jQuery?");
ajaxDfd = source;
} else if (source.url) {
// `source` is an Ajax options object
ajax = $.extend({}, ctx.options.ajax, source);
if (ajax.debugDelay) {
// Simulate a slow server
delay = ajax.debugDelay;
delete ajax.debugDelay; // remove debug option
if ($.isArray(delay)) {
// random delay range [min..max]
delay =
delay[0] +
Math.random() * (delay[1] - delay[0]);
}
node.warn(
"nodeLoadChildren waiting debugDelay " +
Math.round(delay) +
" ms ..."
);
ajaxDfd = $.Deferred(function(ajaxDfd) {
setTimeout(function() {
$.ajax(ajax)
.done(function() {
ajaxDfd.resolveWith(this, arguments);
})
.fail(function() {
ajaxDfd.rejectWith(this, arguments);
});
}, delay);
});
} else {
ajaxDfd = $.ajax(ajax);
}
} else if ($.isPlainObject(source) || $.isArray(source)) {
// `source` is already a constant dict or list, but we convert
// to a thenable for unified processing.
// 2020-01-03: refactored.
// `ajaxDfd = $.when(source)` would do the trick, but the returned
// promise will resolve async, which broke some tests and
// would probably also break current implementations out there.
// So we mock-up a thenable that resolves synchronously:
ajaxDfd = {
then: function(resolve, reject) {
resolve(source, null, null);
},
};
isAsync = false;
} else {
$.error("Invalid source type: " + source);
}
// Check for overlapping requests
if (node._requestId) {
node.warn(
"Recursive load request #" +
requestId +
" while #" +
node._requestId +
" is pending."
);
node._requestId = requestId;
// node.debug("Send load request #" + requestId);
}
if (isAsync) {
tree.debugTime(tag);
tree.nodeSetStatus(ctx, "loading");
}
// The async Ajax request has now started...
// Defer the deferred:
// we want to be able to reject invalid responses, even if
// the raw HTTP Ajax XHR resolved as Ok.
// We use the ajaxDfd.then() syntax here, which is compatible with
// jQuery and ECMA6.
// However resultDfd is a jQuery deferred, which is currently the
// expected result type of nodeLoadChildren()
resultDfd = new $.Deferred();
ajaxDfd.then(
function(data, textStatus, jqXHR) {
// ajaxDfd was resolved, but we reject or resolve resultDfd
// depending on the response data
var errorObj, res;
if (
(source.dataType === "json" ||
source.dataType === "jsonp") &&
typeof data === "string"
) {
$.error(
"Ajax request returned a string (did you get the JSON dataType wrong?)."
);
}
if (node._requestId && node._requestId > requestId) {
// The expected request time stamp is later than `requestId`
// (which was kept as as closure variable to this handler function)
// node.warn("Ignored load response for obsolete request #" + requestId + " (expected #" + node._requestId + ")");
resultDfd.rejectWith(this, [
RECURSIVE_REQUEST_ERROR,
]);
return;
// } else {
// node.debug("Response returned for load request #" + requestId);
}
if (node.parent === null && nodePrevParent !== null) {
resultDfd.rejectWith(this, [
INVALID_REQUEST_TARGET_ERROR,
]);
return;
}
// Allow to adjust the received response data in the `postProcess` event.
if (ctx.options.postProcess) {
// The handler may either
// - modify `ctx.response` in-place (and leave `ctx.result` undefined)
// => res = undefined
// - return a replacement in `ctx.result`
// => res = <new data>
// If res contains an `error` property, an error status is displayed
try {
res = tree._triggerNodeEvent(
"postProcess",
ctx,
ctx.originalEvent,
{
response: data,
error: null,
dataType: source.dataType,
}
);
if (res.error) {
tree.warn(
"postProcess returned error:",
res
);
}
} catch (e) {
res = {
error: e,
message: "" + e,
details: "postProcess failed",
};
}
if (res.error) {
// Either postProcess failed with an exception, or the returned
// result object has an 'error' property attached:
errorObj = $.isPlainObject(res.error)
? res.error
: { message: res.error };
errorObj = tree._makeHookContext(
node,
null,
errorObj
);
resultDfd.rejectWith(this, [errorObj]);
return;
}
if (
$.isArray(res) ||
($.isPlainObject(res) &&
$.isArray(res.children))
) {
// Use `ctx.result` if valid
// (otherwise use existing data, which may have been modified in-place)
data = res;
}
} else if (
data &&
data.hasOwnProperty("d") &&
ctx.options.enableAspx
) {
// Process ASPX WebMethod JSON object inside "d" property
// (only if no postProcess event was defined)
if (ctx.options.enableAspx === 42) {
tree.warn(
"The default for enableAspx will change to `false` in the fututure. " +
"Pass `enableAspx: true` or implement postProcess to silence this warning."
);
}
data =
typeof data.d === "string"
? $.parseJSON(data.d)
: data.d;
}
resultDfd.resolveWith(this, [data]);
},
function(jqXHR, textStatus, errorThrown) {
// ajaxDfd was rejected, so we reject resultDfd as well
var errorObj = tree._makeHookContext(node, null, {
error: jqXHR,
args: Array.prototype.slice.call(arguments),
message: errorThrown,
details: jqXHR.status + ": " + errorThrown,
});
resultDfd.rejectWith(this, [errorObj]);
}
);
// The async Ajax request has now started.
// resultDfd will be resolved/rejected after the response arrived,
// was postProcessed, and checked.
// Now we implement the UI update and add the data to the tree.
// We also return this promise to the caller.
resultDfd
.done(function(data) {
tree.nodeSetStatus(ctx, "ok");
var children, metaData, noDataRes;
if ($.isPlainObject(data)) {
// We got {foo: 'abc', children: [...]}
// Copy extra properties to tree.data.foo
_assert(
node.isRootNode(),
"source may only be an object for root nodes (expecting an array of child objects otherwise)"
);
_assert(
$.isArray(data.children),
"if an object is passed as source, it must contain a 'children' array (all other properties are added to 'tree.data')"
);
metaData = data;
children = data.children;
delete metaData.children;
// Copy some attributes to tree.data
$.each(TREE_ATTRS, function(i, attr) {
if (metaData[attr] !== undefined) {
tree[attr] = metaData[attr];
delete metaData[attr];
}
});
// Copy all other attributes to tree.data.NAME
$.extend(tree.data, metaData);
} else {
children = data;
}
_assert(
$.isArray(children),
"expected array of children"
);
node._setChildren(children);
if (tree.options.nodata && children.length === 0) {
if ($.isFunction(tree.options.nodata)) {
noDataRes = tree.options.nodata.call(
tree,
{ type: "nodata" },
ctx
);
} else if (
tree.options.nodata === true &&
node.isRootNode()
) {
noDataRes = tree.options.strings.noData;
} else if (
typeof tree.options.nodata === "string" &&
node.isRootNode()
) {
noDataRes = tree.options.nodata;
}
if (noDataRes) {
node.setStatus("nodata", noDataRes);
}
}
// trigger fancytreeloadchildren
tree._triggerNodeEvent("loadChildren", node);
})
.fail(function(error) {
var ctxErr;
if (error === RECURSIVE_REQUEST_ERROR) {
node.warn(
"Ignored response for obsolete load request #" +
requestId +
" (expected #" +
node._requestId +
")"
);
return;
} else if (error === INVALID_REQUEST_TARGET_ERROR) {
node.warn(
"Lazy parent node was removed while loading: discarding response."
);
return;
} else if (error.node && error.error && error.message) {
// error is already a context object
ctxErr = error;
} else {
ctxErr = tree._makeHookContext(node, null, {
error: error, // it can be jqXHR or any custom error
args: Array.prototype.slice.call(arguments),
message: error
? error.message || error.toString()
: "",
});
if (ctxErr.message === "[object Object]") {
ctxErr.message = "";
}
}
node.warn(
"Load children failed (" + ctxErr.message + ")",
ctxErr
);
if (
tree._triggerNodeEvent(
"loadError",
ctxErr,
null
) !== false
) {
tree.nodeSetStatus(
ctx,
"error",
ctxErr.message,
ctxErr.details
);
}
})
.always(function() {
node._requestId = null;
if (isAsync) {
tree.debugTimeEnd(tag);
}
});
return resultDfd.promise();
},
/** [Not Implemented] */
nodeLoadKeyPath: function(ctx, keyPathList) {
// TODO: implement and improve
// http://code.google.com/p/dynatree/issues/detail?id=222
},
/**
* Remove a single direct child of ctx.node.
* @param {EventData} ctx
* @param {FancytreeNode} childNode dircect child of ctx.node
*/
nodeRemoveChild: function(ctx, childNode) {
var idx,
node = ctx.node,
// opts = ctx.options,
subCtx = $.extend({}, ctx, { node: childNode }),
children = node.children;
// FT.debug("nodeRemoveChild()", node.toString(), childNode.toString());
if (children.length === 1) {
_assert(childNode === children[0], "invalid single child");
return this.nodeRemoveChildren(ctx);
}
if (
this.activeNode &&
(childNode === this.activeNode ||
this.activeNode.isDescendantOf(childNode))
) {
this.activeNode.setActive(false); // TODO: don't fire events
}
if (
this.focusNode &&
(childNode === this.focusNode ||
this.focusNode.isDescendantOf(childNode))
) {
this.focusNode = null;
}
// TODO: persist must take care to clear select and expand cookies
this.nodeRemoveMarkup(subCtx);
this.nodeRemoveChildren(subCtx);
idx = $.inArray(childNode, children);
_assert(idx >= 0, "invalid child");
// Notify listeners
node.triggerModifyChild("remove", childNode);
// Unlink to support GC
childNode.visit(function(n) {
n.parent = null;
}, true);
this._callHook("treeRegisterNode", this, false, childNode);
// remove from child list
children.splice(idx, 1);
},
/**Remove HTML markup for all descendents of ctx.node.
* @param {EventData} ctx
*/
nodeRemoveChildMarkup: function(ctx) {
var node = ctx.node;
// FT.debug("nodeRemoveChildMarkup()", node.toString());
// TODO: Unlink attr.ftnode to support GC
if (node.ul) {
if (node.isRootNode()) {
$(node.ul).empty();
} else {
$(node.ul).remove();
node.ul = null;
}
node.visit(function(n) {
n.li = n.ul = null;
});
}
},
/**Remove all descendants of ctx.node.
* @param {EventData} ctx
*/
nodeRemoveChildren: function(ctx) {
var //subCtx,
tree = ctx.tree,
node = ctx.node,
children = node.children;
// opts = ctx.options;
// FT.debug("nodeRemoveChildren()", node.toString());
if (!children) {
return;
}
if (this.activeNode && this.activeNode.isDescendantOf(node)) {
this.activeNode.setActive(false); // TODO: don't fire events
}
if (this.focusNode && this.focusNode.isDescendantOf(node)) {
this.focusNode = null;
}
// TODO: persist must take care to clear select and expand cookies
this.nodeRemoveChildMarkup(ctx);
// Unlink children to support GC
// TODO: also delete this.children (not possible using visit())
// subCtx = $.extend({}, ctx);
node.triggerModifyChild("remove", null);
node.visit(function(n) {
n.parent = null;
tree._callHook("treeRegisterNode", tree, false, n);
});
if (node.lazy) {
// 'undefined' would be interpreted as 'not yet loaded' for lazy nodes
node.children = [];
} else {
node.children = null;
}
if (!node.isRootNode()) {
node.expanded = false; // #449, #459
}
this.nodeRenderStatus(ctx);
},
/**Remove HTML markup for ctx.node and all its descendents.
* @param {EventData} ctx
*/
nodeRemoveMarkup: function(ctx) {
var node = ctx.node;
// FT.debug("nodeRemoveMarkup()", node.toString());
// TODO: Unlink attr.ftnode to support GC
if (node.li) {
$(node.li).remove();
node.li = null;
}
this.nodeRemoveChildMarkup(ctx);
},
/**
* Create `<li><span>..</span> .. </li>` tags for this node.
*
* This method takes care that all HTML markup is created that is required
* to display this node in its current state.
*
* Call this method to create new nodes, or after the strucuture
* was changed (e.g. after moving this node or adding/removing children)
* nodeRenderTitle() and nodeRenderStatus() are implied.
*
* ```html
* <li id='KEY' ftnode=NODE>
* <span class='fancytree-node fancytree-expanded fancytree-has-children fancytree-lastsib fancytree-exp-el fancytree-ico-e'>
* <span class="fancytree-expander"></span>
* <span class="fancytree-checkbox"></span> // only present in checkbox mode
* <span class="fancytree-icon"></span>
* <a href="#" class="fancytree-title"> Node 1 </a>
* </span>
* <ul> // only present if node has children
* <li id='KEY' ftnode=NODE> child1 ... </li>
* <li id='KEY' ftnode=NODE> child2 ... </li>
* </ul>
* </li>
* ```
*
* @param {EventData} ctx
* @param {boolean} [force=false] re-render, even if html markup was already created
* @param {boolean} [deep=false] also render all descendants, even if parent is collapsed
* @param {boolean} [collapsed=false] force root node to be collapsed, so we can apply animated expand later
*/
nodeRender: function(ctx, force, deep, collapsed, _recursive) {
/* This method must take care of all cases where the current data mode
* (i.e. node hierarchy) does not match the current markup.
*
* - node was not yet rendered:
* create markup
* - node was rendered: exit fast
* - children have been added
* - children have been removed
*/
var childLI,
childNode1,
childNode2,
i,
l,
next,
subCtx,
node = ctx.node,
tree = ctx.tree,
opts = ctx.options,
aria = opts.aria,
firstTime = false,
parent = node.parent,
isRootNode = !parent,
children = node.children,
successorLi = null;
// FT.debug("nodeRender(" + !!force + ", " + !!deep + ")", node.toString());
if (tree._enableUpdate === false) {
// tree.debug("no render", tree._enableUpdate);
return;
}
if (!isRootNode && !parent.ul) {
// Calling node.collapse on a deep, unrendered node
return;
}
_assert(isRootNode || parent.ul, "parent UL must exist");
// Render the node
if (!isRootNode) {
// Discard markup on force-mode, or if it is not linked to parent <ul>
if (
node.li &&
(force || node.li.parentNode !== node.parent.ul)
) {
if (node.li.parentNode === node.parent.ul) {
// #486: store following node, so we can insert the new markup there later
successorLi = node.li.nextSibling;
} else {
// May happen, when a top-level node was dropped over another
this.debug(
"Unlinking " +
node +
" (must be child of " +
node.parent +
")"
);
}
// this.debug("nodeRemoveMarkup...");
this.nodeRemoveMarkup(ctx);
}
// Create <li><span /> </li>
// node.debug("render...");
if (node.li) {
// this.nodeRenderTitle(ctx);
this.nodeRenderStatus(ctx);
} else {
// node.debug("render... really");
firstTime = true;
node.li = document.createElement("li");
node.li.ftnode = node;
if (node.key && opts.generateIds) {
node.li.id = opts.idPrefix + node.key;
}
node.span = document.createElement("span");
node.span.className = "fancytree-node";
if (aria && !node.tr) {
$(node.li).attr("role", "treeitem");
}
node.li.appendChild(node.span);
// Create inner HTML for the <span> (expander, checkbox, icon, and title)
this.nodeRenderTitle(ctx);
// Allow tweaking and binding, after node was created for the first time
if (opts.createNode) {
opts.createNode.call(
tree,
{ type: "createNode" },
ctx
);
}
}
// Allow tweaking after node state was rendered
if (opts.renderNode) {
opts.renderNode.call(tree, { type: "renderNode" }, ctx);
}
}
// Visit child nodes
if (children) {
if (isRootNode || node.expanded || deep === true) {
// Create a UL to hold the children
if (!node.ul) {
node.ul = document.createElement("ul");
if (
(collapsed === true && !_recursive) ||
!node.expanded
) {
// hide top UL, so we can use an animation to show it later
node.ul.style.display = "none";
}
if (aria) {
$(node.ul).attr("role", "group");
}
if (node.li) {
// issue #67
node.li.appendChild(node.ul);
} else {
node.tree.$div.append(node.ul);
}
}
// Add child markup
for (i = 0, l = children.length; i < l; i++) {
subCtx = $.extend({}, ctx, { node: children[i] });
this.nodeRender(subCtx, force, deep, false, true);
}
// Remove <li> if nodes have moved to another parent
childLI = node.ul.firstChild;
while (childLI) {
childNode2 = childLI.ftnode;
if (childNode2 && childNode2.parent !== node) {
node.debug(
"_fixParent: remove missing " + childNode2,
childLI
);
next = childLI.nextSibling;
childLI.parentNode.removeChild(childLI);
childLI = next;
} else {
childLI = childLI.nextSibling;
}
}
// Make sure, that <li> order matches node.children order.
childLI = node.ul.firstChild;
for (i = 0, l = children.length - 1; i < l; i++) {
childNode1 = children[i];
childNode2 = childLI.ftnode;
if (childNode1 === childNode2) {
childLI = childLI.nextSibling;
} else {
// node.debug("_fixOrder: mismatch at index " + i + ": " + childNode1 + " != " + childNode2);
node.ul.insertBefore(
childNode1.li,
childNode2.li
);
}
}
}
} else {
// No children: remove markup if any
if (node.ul) {
// alert("remove child markup for " + node);
this.warn("remove child markup for " + node);
this.nodeRemoveChildMarkup(ctx);
}
}
if (!isRootNode) {
// Update element classes according to node state
// this.nodeRenderStatus(ctx);
// Finally add the whole structure to the DOM, so the browser can render
if (firstTime) {
// #486: successorLi is set, if we re-rendered (i.e. discarded)
// existing markup, which we want to insert at the same position.
// (null is equivalent to append)
// parent.ul.appendChild(node.li);
parent.ul.insertBefore(node.li, successorLi);
}
}
},
/** Create HTML inside the node's outer `<span>` (i.e. expander, checkbox,
* icon, and title).
*
* nodeRenderStatus() is implied.
* @param {EventData} ctx
* @param {string} [title] optinal new title
*/
nodeRenderTitle: function(ctx, title) {
// set node connector images, links and text
var checkbox,
className,
icon,
nodeTitle,
role,
tabindex,
tooltip,
iconTooltip,
node = ctx.node,
tree = ctx.tree,
opts = ctx.options,
aria = opts.aria,
level = node.getLevel(),
ares = [];
if (title !== undefined) {
node.title = title;
}
if (!node.span || tree._enableUpdate === false) {
// Silently bail out if node was not rendered yet, assuming
// node.render() will be called as the node becomes visible
return;
}
// Connector (expanded, expandable or simple)
role =
aria && node.hasChildren() !== false
? " role='button'"
: "";
if (level < opts.minExpandLevel) {
if (!node.lazy) {
node.expanded = true;
}
if (level > 1) {
ares.push(
"<span " +
role +
" class='fancytree-expander fancytree-expander-fixed'></span>"
);
}
// .. else (i.e. for root level) skip expander/connector alltogether
} else {
ares.push(
"<span " + role + " class='fancytree-expander'></span>"
);
}
// Checkbox mode
checkbox = FT.evalOption("checkbox", node, node, opts, false);
if (checkbox && !node.isStatusNode()) {
role = aria ? " role='checkbox'" : "";
className = "fancytree-checkbox";
if (
checkbox === "radio" ||
(node.parent && node.parent.radiogroup)
) {
className += " fancytree-radio";
}
ares.push(
"<span " + role + " class='" + className + "'></span>"
);
}
// Folder or doctype icon
if (node.data.iconClass !== undefined) {
// 2015-11-16
// Handle / warn about backward compatibility
if (node.icon) {
$.error(
"'iconClass' node option is deprecated since v2.14.0: use 'icon' only instead"
);
} else {
node.warn(
"'iconClass' node option is deprecated since v2.14.0: use 'icon' instead"
);
node.icon = node.data.iconClass;
}
}
// If opts.icon is a callback and returns something other than undefined, use that
// else if node.icon is a boolean or string, use that
// else if opts.icon is a boolean or string, use that
// else show standard icon (which may be different for folders or documents)
icon = FT.evalOption("icon", node, node, opts, true);
// if( typeof icon !== "boolean" ) {
// // icon is defined, but not true/false: must be a string
// icon = "" + icon;
// }
if (icon !== false) {
role = aria ? " role='presentation'" : "";
iconTooltip = FT.evalOption(
"iconTooltip",
node,
node,
opts,
null
);
iconTooltip = iconTooltip
? " title='" + _escapeTooltip(iconTooltip) + "'"
: "";
if (typeof icon === "string") {
if (TEST_IMG.test(icon)) {
// node.icon is an image url. Prepend imagePath
icon =
icon.charAt(0) === "/"
? icon
: (opts.imagePath || "") + icon;
ares.push(
"<img src='" +
icon +
"' class='fancytree-icon'" +
iconTooltip +
" alt='' />"
);
} else {
ares.push(
"<span " +
role +
" class='fancytree-custom-icon " +
icon +
"'" +
iconTooltip +
"></span>"
);
}
} else if (icon.text) {
ares.push(
"<span " +
role +
" class='fancytree-custom-icon " +
(icon.addClass || "") +
"'" +
iconTooltip +
">" +
FT.escapeHtml(icon.text) +
"</span>"
);
} else if (icon.html) {
ares.push(
"<span " +
role +
" class='fancytree-custom-icon " +
(icon.addClass || "") +
"'" +
iconTooltip +
">" +
icon.html +
"</span>"
);
} else {
// standard icon: theme css will take care of this
ares.push(
"<span " +
role +
" class='fancytree-icon'" +
iconTooltip +
"></span>"
);
}
}
// Node title
nodeTitle = "";
if (opts.renderTitle) {
nodeTitle =
opts.renderTitle.call(
tree,
{ type: "renderTitle" },
ctx
) || "";
}
if (!nodeTitle) {
tooltip = FT.evalOption("tooltip", node, node, opts, null);
if (tooltip === true) {
tooltip = node.title;
}
// if( node.tooltip ) {
// tooltip = node.tooltip;
// } else if ( opts.tooltip ) {
// tooltip = opts.tooltip === true ? node.title : opts.tooltip.call(tree, node);
// }
tooltip = tooltip
? " title='" + _escapeTooltip(tooltip) + "'"
: "";
tabindex = opts.titlesTabbable ? " tabindex='0'" : "";
nodeTitle =
"<span class='fancytree-title'" +
tooltip +
tabindex +
">" +
(opts.escapeTitles
? FT.escapeHtml(node.title)
: node.title) +
"</span>";
}
ares.push(nodeTitle);
// Note: this will trigger focusout, if node had the focus
//$(node.span).html(ares.join("")); // it will cleanup the jQuery data currently associated with SPAN (if any), but it executes more slowly
node.span.innerHTML = ares.join("");
// Update CSS classes
this.nodeRenderStatus(ctx);
if (opts.enhanceTitle) {
ctx.$title = $(">span.fancytree-title", node.span);
nodeTitle =
opts.enhanceTitle.call(
tree,
{ type: "enhanceTitle" },
ctx
) || "";
}
},
/** Update element classes according to node state.
* @param {EventData} ctx
*/
nodeRenderStatus: function(ctx) {
// Set classes for current status
var $ariaElem,
node = ctx.node,
tree = ctx.tree,
opts = ctx.options,
// nodeContainer = node[tree.nodeContainerAttrName],
hasChildren = node.hasChildren(),
isLastSib = node.isLastSibling(),
aria = opts.aria,
cn = opts._classNames,
cnList = [],
statusElem = node[tree.statusClassPropName];
if (!statusElem || tree._enableUpdate === false) {
// if this function is called for an unrendered node, ignore it (will be updated on nect render anyway)
return;
}
if (aria) {
$ariaElem = $(node.tr || node.li);
}
// Build a list of class names that we will add to the node <span>
cnList.push(cn.node);
if (tree.activeNode === node) {
cnList.push(cn.active);
// $(">span.fancytree-title", statusElem).attr("tabindex", "0");
// tree.$container.removeAttr("tabindex");
// }else{
// $(">span.fancytree-title", statusElem).removeAttr("tabindex");
// tree.$container.attr("tabindex", "0");
}
if (tree.focusNode === node) {
cnList.push(cn.focused);
}
if (node.expanded) {
cnList.push(cn.expanded);
}
if (aria) {
if (hasChildren === false) {
$ariaElem.removeAttr("aria-expanded");
} else {
$ariaElem.attr("aria-expanded", Boolean(node.expanded));
}
}
if (node.folder) {
cnList.push(cn.folder);
}
if (hasChildren !== false) {
cnList.push(cn.hasChildren);
}
// TODO: required?
if (isLastSib) {
cnList.push(cn.lastsib);
}
if (node.lazy && node.children == null) {
cnList.push(cn.lazy);
}
if (node.partload) {
cnList.push(cn.partload);
}
if (node.partsel) {
cnList.push(cn.partsel);
}
if (FT.evalOption("unselectable", node, node, opts, false)) {
cnList.push(cn.unselectable);
}
if (node._isLoading) {
cnList.push(cn.loading);
}
if (node._error) {
cnList.push(cn.error);
}
if (node.statusNodeType) {
cnList.push(cn.statusNodePrefix + node.statusNodeType);
}
if (node.selected) {
cnList.push(cn.selected);
if (aria) {
$ariaElem.attr("aria-selected", true);
}
} else if (aria) {
$ariaElem.attr("aria-selected", false);
}
if (node.extraClasses) {
cnList.push(node.extraClasses);
}
// IE6 doesn't correctly evaluate multiple class names,
// so we create combined class names that can be used in the CSS
if (hasChildren === false) {
cnList.push(
cn.combinedExpanderPrefix + "n" + (isLastSib ? "l" : "")
);
} else {
cnList.push(
cn.combinedExpanderPrefix +
(node.expanded ? "e" : "c") +
(node.lazy && node.children == null ? "d" : "") +
(isLastSib ? "l" : "")
);
}
cnList.push(
cn.combinedIconPrefix +
(node.expanded ? "e" : "c") +
(node.folder ? "f" : "")
);
// node.span.className = cnList.join(" ");
statusElem.className = cnList.join(" ");
// TODO: we should not set this in the <span> tag also, if we set it here:
// Maybe most (all) of the classes should be set in LI instead of SPAN?
if (node.li) {
// #719: we have to consider that there may be already other classes:
$(node.li).toggleClass(cn.lastsib, isLastSib);
}
},
/** Activate node.
* flag defaults to true.
* If flag is true, the node is activated (must be a synchronous operation)
* If flag is false, the node is deactivated (must be a synchronous operation)
* @param {EventData} ctx
* @param {boolean} [flag=true]
* @param {object} [opts] additional options. Defaults to {noEvents: false, noFocus: false}
* @returns {$.Promise}
*/
nodeSetActive: function(ctx, flag, callOpts) {
// Handle user click / [space] / [enter], according to clickFolderMode.
callOpts = callOpts || {};
var subCtx,
node = ctx.node,
tree = ctx.tree,
opts = ctx.options,
noEvents = callOpts.noEvents === true,
noFocus = callOpts.noFocus === true,
scroll = callOpts.scrollIntoView !== false,
isActive = node === tree.activeNode;
// flag defaults to true
flag = flag !== false;
// node.debug("nodeSetActive", flag);
if (isActive === flag) {
// Nothing to do
return _getResolvedPromise(node);
} else if (
flag &&
!noEvents &&
this._triggerNodeEvent(
"beforeActivate",
node,
ctx.originalEvent
) === false
) {
// Callback returned false
return _getRejectedPromise(node, ["rejected"]);
}
if (flag) {
if (tree.activeNode) {
_assert(
tree.activeNode !== node,
"node was active (inconsistency)"
);
subCtx = $.extend({}, ctx, { node: tree.activeNode });
tree.nodeSetActive(subCtx, false);
_assert(
tree.activeNode === null,
"deactivate was out of sync?"
);
}
if (opts.activeVisible) {
// If no focus is set (noFocus: true) and there is no focused node, this node is made visible.
// scroll = noFocus && tree.focusNode == null;
// #863: scroll by default (unless `scrollIntoView: false` was passed)
node.makeVisible({ scrollIntoView: scroll });
}
tree.activeNode = node;
tree.nodeRenderStatus(ctx);
if (!noFocus) {
tree.nodeSetFocus(ctx);
}
if (!noEvents) {
tree._triggerNodeEvent(
"activate",
node,
ctx.originalEvent
);
}
} else {
_assert(
tree.activeNode === node,
"node was not active (inconsistency)"
);
tree.activeNode = null;
this.nodeRenderStatus(ctx);
if (!noEvents) {
ctx.tree._triggerNodeEvent(
"deactivate",
node,
ctx.originalEvent
);
}
}
return _getResolvedPromise(node);
},
/** Expand or collapse node, return Deferred.promise.
*
* @param {EventData} ctx
* @param {boolean} [flag=true]
* @param {object} [opts] additional options. Defaults to `{noAnimation: false, noEvents: false}`
* @returns {$.Promise} The deferred will be resolved as soon as the (lazy)
* data was retrieved, rendered, and the expand animation finished.
*/
nodeSetExpanded: function(ctx, flag, callOpts) {
callOpts = callOpts || {};
var _afterLoad,
dfd,
i,
l,
parents,
prevAC,
node = ctx.node,
tree = ctx.tree,
opts = ctx.options,
noAnimation = callOpts.noAnimation === true,
noEvents = callOpts.noEvents === true;
// flag defaults to true
flag = flag !== false;
// node.debug("nodeSetExpanded(" + flag + ")");
if ($(node.li).hasClass(opts._classNames.animating)) {
node.warn(
"setExpanded(" + flag + ") while animating: ignored."
);
return _getRejectedPromise(node, ["recursion"]);
}
if ((node.expanded && flag) || (!node.expanded && !flag)) {
// Nothing to do
// node.debug("nodeSetExpanded(" + flag + "): nothing to do");
return _getResolvedPromise(node);
} else if (flag && !node.lazy && !node.hasChildren()) {
// Prevent expanding of empty nodes
// return _getRejectedPromise(node, ["empty"]);
return _getResolvedPromise(node);
} else if (!flag && node.getLevel() < opts.minExpandLevel) {
// Prevent collapsing locked levels
return _getRejectedPromise(node, ["locked"]);
} else if (
!noEvents &&
this._triggerNodeEvent(
"beforeExpand",
node,
ctx.originalEvent
) === false
) {
// Callback returned false
return _getRejectedPromise(node, ["rejected"]);
}
// If this node inside a collpased node, no animation and scrolling is needed
if (!noAnimation && !node.isVisible()) {
noAnimation = callOpts.noAnimation = true;
}
dfd = new $.Deferred();
// Auto-collapse mode: collapse all siblings
if (flag && !node.expanded && opts.autoCollapse) {
parents = node.getParentList(false, true);
prevAC = opts.autoCollapse;
try {
opts.autoCollapse = false;
for (i = 0, l = parents.length; i < l; i++) {
// TODO: should return promise?
this._callHook(
"nodeCollapseSiblings",
parents[i],
callOpts
);
}
} finally {
opts.autoCollapse = prevAC;
}
}
// Trigger expand/collapse after expanding
dfd.done(function() {
var lastChild = node.getLastChild();
if (
flag &&
opts.autoScroll &&
!noAnimation &&
lastChild &&
tree._enableUpdate
) {
// Scroll down to last child, but keep current node visible
lastChild
.scrollIntoView(true, { topNode: node })
.always(function() {
if (!noEvents) {
ctx.tree._triggerNodeEvent(
flag ? "expand" : "collapse",
ctx
);
}
});
} else {
if (!noEvents) {
ctx.tree._triggerNodeEvent(
flag ? "expand" : "collapse",
ctx
);
}
}
});
// vvv Code below is executed after loading finished:
_afterLoad = function(callback) {
var cn = opts._classNames,
isVisible,
isExpanded,
effect = opts.toggleEffect;
node.expanded = flag;
tree._callHook(
"treeStructureChanged",
ctx,
flag ? "expand" : "collapse"
);
// Create required markup, but make sure the top UL is hidden, so we
// can animate later
tree._callHook("nodeRender", ctx, false, false, true);
// Hide children, if node is collapsed
if (node.ul) {
isVisible = node.ul.style.display !== "none";
isExpanded = !!node.expanded;
if (isVisible === isExpanded) {
node.warn(
"nodeSetExpanded: UL.style.display already set"
);
} else if (!effect || noAnimation) {
node.ul.style.display =
node.expanded || !parent ? "" : "none";
} else {
// The UI toggle() effect works with the ext-wide extension,
// while jQuery.animate() has problems when the title span
// has position: absolute.
// Since jQuery UI 1.12, the blind effect requires the parent
// element to have 'position: relative'.
// See #716, #717
$(node.li).addClass(cn.animating); // #717
if ($.isFunction($(node.ul)[effect.effect])) {
// tree.debug( "use jquery." + effect.effect + " method" );
$(node.ul)[effect.effect]({
duration: effect.duration,
always: function() {
// node.debug("fancytree-animating end: " + node.li.className);
$(this).removeClass(cn.animating); // #716
$(node.li).removeClass(cn.animating); // #717
callback();
},
});
} else {
// The UI toggle() effect works with the ext-wide extension,
// while jQuery.animate() has problems when the title span
// has positon: absolute.
// Since jQuery UI 1.12, the blind effect requires the parent
// element to have 'position: relative'.
// See #716, #717
// tree.debug("use specified effect (" + effect.effect + ") with the jqueryui.toggle method");
// try to stop an animation that might be already in progress
$(node.ul).stop(true, true); //< does not work after resetLazy has been called for a node whose animation wasn't complete and effect was "blind"
// dirty fix to remove a defunct animation (effect: "blind") after resetLazy has been called
$(node.ul)
.parent()
.find(".ui-effects-placeholder")
.remove();
$(node.ul).toggle(
effect.effect,
effect.options,
effect.duration,
function() {
// node.debug("fancytree-animating end: " + node.li.className);
$(this).removeClass(cn.animating); // #716
$(node.li).removeClass(cn.animating); // #717
callback();
}
);
}
return;
}
}
callback();
};
// ^^^ Code above is executed after loading finshed.
// Load lazy nodes, if any. Then continue with _afterLoad()
if (flag && node.lazy && node.hasChildren() === undefined) {
// node.debug("nodeSetExpanded: load start...");
node.load()
.done(function() {
// node.debug("nodeSetExpanded: load done");
if (dfd.notifyWith) {
// requires jQuery 1.6+
dfd.notifyWith(node, ["loaded"]);
}
_afterLoad(function() {
dfd.resolveWith(node);
});
})
.fail(function(errMsg) {
_afterLoad(function() {
dfd.rejectWith(node, [
"load failed (" + errMsg + ")",
]);
});
});
/*
var source = tree._triggerNodeEvent("lazyLoad", node, ctx.originalEvent);
_assert(typeof source !== "boolean", "lazyLoad event must return source in data.result");
node.debug("nodeSetExpanded: load start...");
this._callHook("nodeLoadChildren", ctx, source).done(function(){
node.debug("nodeSetExpanded: load done");
if(dfd.notifyWith){ // requires jQuery 1.6+
dfd.notifyWith(node, ["loaded"]);
}
_afterLoad.call(tree);
}).fail(function(errMsg){
dfd.rejectWith(node, ["load failed (" + errMsg + ")"]);
});
*/
} else {
_afterLoad(function() {
dfd.resolveWith(node);
});
}
// node.debug("nodeSetExpanded: returns");
return dfd.promise();
},
/** Focus or blur this node.
* @param {EventData} ctx
* @param {boolean} [flag=true]
*/
nodeSetFocus: function(ctx, flag) {
// ctx.node.debug("nodeSetFocus(" + flag + ")");
var ctx2,
tree = ctx.tree,
node = ctx.node,
opts = tree.options,
// et = ctx.originalEvent && ctx.originalEvent.type,
isInput = ctx.originalEvent
? $(ctx.originalEvent.target).is(":input")
: false;
flag = flag !== false;
// (node || tree).debug("nodeSetFocus(" + flag + "), event: " + et + ", isInput: "+ isInput);
// Blur previous node if any
if (tree.focusNode) {
if (tree.focusNode === node && flag) {
// node.debug("nodeSetFocus(" + flag + "): nothing to do");
return;
}
ctx2 = $.extend({}, ctx, { node: tree.focusNode });
tree.focusNode = null;
this._triggerNodeEvent("blur", ctx2);
this._callHook("nodeRenderStatus", ctx2);
}
// Set focus to container and node
if (flag) {
if (!this.hasFocus()) {
node.debug("nodeSetFocus: forcing container focus");
this._callHook("treeSetFocus", ctx, true, {
calledByNode: true,
});
}
node.makeVisible({ scrollIntoView: false });
tree.focusNode = node;
if (opts.titlesTabbable) {
if (!isInput) {
// #621
$(node.span)
.find(".fancytree-title")
.focus();
}
}
if (opts.aria) {
// Set active descendant to node's span ID (create one, if needed)
$(tree.$container).attr(
"aria-activedescendant",
$(node.tr || node.li)
.uniqueId()
.attr("id")
);
// "ftal_" + opts.idPrefix + node.key);
}
// $(node.span).find(".fancytree-title").focus();
this._triggerNodeEvent("focus", ctx);
// determine if we have focus on or inside tree container
var hasFancytreeFocus =
document.activeElement === tree.$container.get(0) ||
$(document.activeElement, tree.$container).length >= 1;
if (!hasFancytreeFocus) {
// We cannot set KB focus to a node, so use the tree container
// #563, #570: IE scrolls on every call to .focus(), if the container
// is partially outside the viewport. So do it only, when absolutely
// necessary.
$(tree.$container).focus();
}
// if( opts.autoActivate ){
// tree.nodeSetActive(ctx, true);
// }
if (opts.autoScroll) {
node.scrollIntoView();
}
this._callHook("nodeRenderStatus", ctx);
}
},
/** (De)Select node, return new status (sync).
*
* @param {EventData} ctx
* @param {boolean} [flag=true]
* @param {object} [opts] additional options. Defaults to {noEvents: false,
* propagateDown: null, propagateUp: null,
* callback: null,
* }
* @returns {boolean} previous status
*/
nodeSetSelected: function(ctx, flag, callOpts) {
callOpts = callOpts || {};
var node = ctx.node,
tree = ctx.tree,
opts = ctx.options,
noEvents = callOpts.noEvents === true,
parent = node.parent;
// flag defaults to true
flag = flag !== false;
// node.debug("nodeSetSelected(" + flag + ")", ctx);
// Cannot (de)select unselectable nodes directly (only by propagation or
// by setting the `.selected` property)
if (FT.evalOption("unselectable", node, node, opts, false)) {
return;
}
// Remember the user's intent, in case down -> up propagation prevents
// applying it to node.selected
node._lastSelectIntent = flag; // Confusing use of '!'
// Nothing to do?
if (!!node.selected === flag) {
if (opts.selectMode === 3 && node.partsel && !flag) {
// If propagation prevented selecting this node last time, we still
// want to allow to apply setSelected(false) now
} else {
return flag;
}
}
if (
!noEvents &&
this._triggerNodeEvent(
"beforeSelect",
node,
ctx.originalEvent
) === false
) {
return !!node.selected;
}
if (flag && opts.selectMode === 1) {
// single selection mode (we don't uncheck all tree nodes, for performance reasons)
if (tree.lastSelectedNode) {
tree.lastSelectedNode.setSelected(false);
}
node.selected = flag;
} else if (
opts.selectMode === 3 &&
parent &&
!parent.radiogroup &&
!node.radiogroup
) {
// multi-hierarchical selection mode
node.selected = flag;
node.fixSelection3AfterClick(callOpts);
} else if (parent && parent.radiogroup) {
node.visitSiblings(function(n) {
n._changeSelectStatusAttrs(flag && n === node);
}, true);
} else {
// default: selectMode: 2, multi selection mode
node.selected = flag;
}
this.nodeRenderStatus(ctx);
tree.lastSelectedNode = flag ? node : null;
if (!noEvents) {
tree._triggerNodeEvent("select", ctx);
}
},
/** Show node status (ok, loading, error, nodata) using styles and a dummy child node.
*
* @param {EventData} ctx
* @param status
* @param message
* @param details
* @since 2.3
*/
nodeSetStatus: function(ctx, status, message, details) {
var node = ctx.node,
tree = ctx.tree;
function _clearStatusNode() {
// Remove dedicated dummy node, if any
var firstChild = node.children ? node.children[0] : null;
if (firstChild && firstChild.isStatusNode()) {
try {
// I've seen exceptions here with loadKeyPath...
if (node.ul) {
node.ul.removeChild(firstChild.li);
firstChild.li = null; // avoid leaks (DT issue 215)
}
} catch (e) {}
if (node.children.length === 1) {
node.children = [];
} else {
node.children.shift();
}
tree._callHook(
"treeStructureChanged",
ctx,
"clearStatusNode"
);
}
}
function _setStatusNode(data, type) {
// Create/modify the dedicated dummy node for 'loading...' or
// 'error!' status. (only called for direct child of the invisible
// system root)
var firstChild = node.children ? node.children[0] : null;
if (firstChild && firstChild.isStatusNode()) {
$.extend(firstChild, data);
firstChild.statusNodeType = type;
tree._callHook("nodeRenderTitle", firstChild);
} else {
node._setChildren([data]);
tree._callHook(
"treeStructureChanged",
ctx,
"setStatusNode"
);
node.children[0].statusNodeType = type;
tree.render();
}
return node.children[0];
}
switch (status) {
case "ok":
_clearStatusNode();
node._isLoading = false;
node._error = null;
node.renderStatus();
break;
case "loading":
if (!node.parent) {
_setStatusNode(
{
title:
tree.options.strings.loading +
(message ? " (" + message + ")" : ""),
// icon: true, // needed for 'loding' icon
checkbox: false,
tooltip: details,
},
status
);
}
node._isLoading = true;
node._error = null;
node.renderStatus();
break;
case "error":
_setStatusNode(
{
title:
tree.options.strings.loadError +
(message ? " (" + message + ")" : ""),
// icon: false,
checkbox: false,
tooltip: details,
},
status
);
node._isLoading = false;
node._error = { message: message, details: details };
node.renderStatus();
break;
case "nodata":
_setStatusNode(
{
title: message || tree.options.strings.noData,
// icon: false,
checkbox: false,
tooltip: details,
},
status
);
node._isLoading = false;
node._error = null;
node.renderStatus();
break;
default:
$.error("invalid node status " + status);
}
},
/**
*
* @param {EventData} ctx
*/
nodeToggleExpanded: function(ctx) {
return this.nodeSetExpanded(ctx, !ctx.node.expanded);
},
/**
* @param {EventData} ctx
*/
nodeToggleSelected: function(ctx) {
var node = ctx.node,
flag = !node.selected;
// In selectMode: 3 this node may be unselected+partsel, even if
// setSelected(true) was called before, due to `unselectable` children.
// In this case, we now toggle as `setSelected(false)`
if (
node.partsel &&
!node.selected &&
node._lastSelectIntent === true
) {
flag = false;
node.selected = true; // so it is not considered 'nothing to do'
}
node._lastSelectIntent = flag;
return this.nodeSetSelected(ctx, flag);
},
/** Remove all nodes.
* @param {EventData} ctx
*/
treeClear: function(ctx) {
var tree = ctx.tree;
tree.activeNode = null;
tree.focusNode = null;
tree.$div.find(">ul.fancytree-container").empty();
// TODO: call destructors and remove reference loops
tree.rootNode.children = null;
tree._callHook("treeStructureChanged", ctx, "clear");
},
/** Widget was created (called only once, even it re-initialized).
* @param {EventData} ctx
*/
treeCreate: function(ctx) {},
/** Widget was destroyed.
* @param {EventData} ctx
*/
treeDestroy: function(ctx) {
this.$div.find(">ul.fancytree-container").remove();
if (this.$source) {
this.$source.removeClass("fancytree-helper-hidden");
}
},
/** Widget was (re-)initialized.
* @param {EventData} ctx
*/
treeInit: function(ctx) {
var tree = ctx.tree,
opts = tree.options;
//this.debug("Fancytree.treeInit()");
// Add container to the TAB chain
// See http://www.w3.org/TR/wai-aria-practices/#focus_activedescendant
// #577: Allow to set tabindex to "0", "-1" and ""
tree.$container.attr("tabindex", opts.tabindex);
// Copy some attributes to tree.data
$.each(TREE_ATTRS, function(i, attr) {
if (opts[attr] !== undefined) {
tree.info("Move option " + attr + " to tree");
tree[attr] = opts[attr];
delete opts[attr];
}
});
if (opts.checkboxAutoHide) {
tree.$container.addClass("fancytree-checkbox-auto-hide");
}
if (opts.rtl) {
tree.$container
.attr("DIR", "RTL")
.addClass("fancytree-rtl");
} else {
tree.$container
.removeAttr("DIR")
.removeClass("fancytree-rtl");
}
if (opts.aria) {
tree.$container.attr("role", "tree");
if (opts.selectMode !== 1) {
tree.$container.attr("aria-multiselectable", true);
}
}
this.treeLoad(ctx);
},
/** Parse Fancytree from source, as configured in the options.
* @param {EventData} ctx
* @param {object} [source] optional new source (use last data otherwise)
*/
treeLoad: function(ctx, source) {
var metaData,
type,
$ul,
tree = ctx.tree,
$container = ctx.widget.element,
dfd,
// calling context for root node
rootCtx = $.extend({}, ctx, { node: this.rootNode });
if (tree.rootNode.children) {
this.treeClear(ctx);
}
source = source || this.options.source;
if (!source) {
type = $container.data("type") || "html";
switch (type) {
case "html":
// There should be an embedded `<ul>` with initial nodes,
// but another `<ul class='fancytree-container'>` is appended
// to the tree's <div> on startup anyway.
$ul = $container
.find(">ul")
.not(".fancytree-container")
.first();
if ($ul.length) {
$ul.addClass(
"ui-fancytree-source fancytree-helper-hidden"
);
source = $.ui.fancytree.parseHtml($ul);
// allow to init tree.data.foo from <ul data-foo=''>
this.data = $.extend(
this.data,
_getElementDataAsDict($ul)
);
} else {
FT.warn(
"No `source` option was passed and container does not contain `<ul>`: assuming `source: []`."
);
source = [];
}
break;
case "json":
source = $.parseJSON($container.text());
// $container already contains the <ul>, but we remove the plain (json) text
// $container.empty();
$container
.contents()
.filter(function() {
return this.nodeType === 3;
})
.remove();
if ($.isPlainObject(source)) {
// We got {foo: 'abc', children: [...]}
_assert(
$.isArray(source.children),
"if an object is passed as source, it must contain a 'children' array (all other properties are added to 'tree.data')"
);
metaData = source;
source = source.children;
delete metaData.children;
// Copy some attributes to tree.data
$.each(TREE_ATTRS, function(i, attr) {
if (metaData[attr] !== undefined) {
tree[attr] = metaData[attr];
delete metaData[attr];
}
});
// Copy extra properties to tree.data.foo
$.extend(tree.data, metaData);
}
break;
default:
$.error("Invalid data-type: " + type);
}
} else if (typeof source === "string") {
// TODO: source is an element ID
$.error("Not implemented");
}
// preInit is fired when the widget markup is created, but nodes
// not yet loaded
tree._triggerTreeEvent("preInit", null);
// Trigger fancytreeinit after nodes have been loaded
dfd = this.nodeLoadChildren(rootCtx, source)
.done(function() {
tree._callHook(
"treeStructureChanged",
ctx,
"loadChildren"
);
tree.render();
if (ctx.options.selectMode === 3) {
tree.rootNode.fixSelection3FromEndNodes();
}
if (tree.activeNode && tree.options.activeVisible) {
tree.activeNode.makeVisible();
}
tree._triggerTreeEvent("init", null, { status: true });
})
.fail(function() {
tree.render();
tree._triggerTreeEvent("init", null, { status: false });
});
return dfd;
},
/** Node was inserted into or removed from the tree.
* @param {EventData} ctx
* @param {boolean} add
* @param {FancytreeNode} node
*/
treeRegisterNode: function(ctx, add, node) {
ctx.tree._callHook(
"treeStructureChanged",
ctx,
add ? "addNode" : "removeNode"
);
},
/** Widget got focus.
* @param {EventData} ctx
* @param {boolean} [flag=true]
*/
treeSetFocus: function(ctx, flag, callOpts) {
var targetNode;
flag = flag !== false;
// this.debug("treeSetFocus(" + flag + "), callOpts: ", callOpts, this.hasFocus());
// this.debug(" focusNode: " + this.focusNode);
// this.debug(" activeNode: " + this.activeNode);
if (flag !== this.hasFocus()) {
this._hasFocus = flag;
if (!flag && this.focusNode) {
// Node also looses focus if widget blurs
this.focusNode.setFocus(false);
} else if (flag && (!callOpts || !callOpts.calledByNode)) {
$(this.$container).focus();
}
this.$container.toggleClass("fancytree-treefocus", flag);
this._triggerTreeEvent(flag ? "focusTree" : "blurTree");
if (flag && !this.activeNode) {
// #712: Use last mousedowned node ('click' event fires after focusin)
targetNode =
this._lastMousedownNode || this.getFirstChild();
if (targetNode) {
targetNode.setFocus();
}
}
}
},
/** Widget option was set using `$().fancytree("option", "KEY", VALUE)`.
*
* Note: `key` may reference a nested option, e.g. 'dnd5.scroll'.
* In this case `value`contains the complete, modified `dnd5` option hash.
* We can check for changed values like
* if( value.scroll !== tree.options.dnd5.scroll ) {...}
*
* @param {EventData} ctx
* @param {string} key option name
* @param {any} value option value
*/
treeSetOption: function(ctx, key, value) {
var tree = ctx.tree,
callDefault = true,
callCreate = false,
callRender = false;
switch (key) {
case "aria":
case "checkbox":
case "icon":
case "minExpandLevel":
case "tabindex":
// tree._callHook("treeCreate", tree);
callCreate = true;
callRender = true;
break;
case "checkboxAutoHide":
tree.$container.toggleClass(
"fancytree-checkbox-auto-hide",
!!value
);
break;
case "escapeTitles":
case "tooltip":
callRender = true;
break;
case "rtl":
if (value === false) {
tree.$container
.removeAttr("DIR")
.removeClass("fancytree-rtl");
} else {
tree.$container
.attr("DIR", "RTL")
.addClass("fancytree-rtl");
}
callRender = true;
break;
case "source":
callDefault = false;
tree._callHook("treeLoad", tree, value);
callRender = true;
break;
}
tree.debug(
"set option " +
key +
"=" +
value +
" <" +
typeof value +
">"
);
if (callDefault) {
if (this.widget._super) {
// jQuery UI 1.9+
this.widget._super.call(this.widget, key, value);
} else {
// jQuery UI <= 1.8, we have to manually invoke the _setOption method from the base widget
$.Widget.prototype._setOption.call(
this.widget,
key,
value
);
}
}
if (callCreate) {
tree._callHook("treeCreate", tree);
}
if (callRender) {
tree.render(true, false); // force, not-deep
}
},
/** A Node was added, removed, moved, or it's visibility changed.
* @param {EventData} ctx
*/
treeStructureChanged: function(ctx, type) {},
}
);
/*******************************************************************************
* jQuery UI widget boilerplate
*/
/**
* The plugin (derrived from [jQuery.Widget](http://api.jqueryui.com/jQuery.widget/)).
*
* **Note:**
* These methods implement the standard jQuery UI widget API.
* It is recommended to use methods of the {Fancytree} instance instead
*
* @example
* // DEPRECATED: Access jQuery UI widget methods and members:
* var tree = $("#tree").fancytree("getTree", "#myTree");
* var node = $.ui.fancytree.getTree("#tree").getActiveNode();
*
* // RECOMMENDED: Use the Fancytree object API
* var tree = $.ui.fancytree.getTree("#myTree");
* var node = tree.getActiveNode();
*
* // or you may already have stored the tree instance upon creation:
* import {createTree, version} from 'jquery.fancytree'
* const tree = createTree('#tree', { ... });
* var node = tree.getActiveNode();
*
* @see {Fancytree_Static#getTree}
* @deprecated Use methods of the {Fancytree} instance instead
* @mixin Fancytree_Widget
*/
$.widget(
"ui.fancytree",
/** @lends Fancytree_Widget# */
{
/**These options will be used as defaults
* @type {FancytreeOptions}
*/
options: {
activeVisible: true,
ajax: {
type: "GET",
cache: false, // false: Append random '_' argument to the request url to prevent caching.
// timeout: 0, // >0: Make sure we get an ajax error if server is unreachable
dataType: "json", // Expect json format and pass json object to callbacks.
},
aria: true,
autoActivate: true,
autoCollapse: false,
autoScroll: false,
checkbox: false,
clickFolderMode: 4,
copyFunctionsToData: false,
debugLevel: null, // 0..4 (null: use global setting $.ui.fancytree.debugLevel)
disabled: false, // TODO: required anymore?
enableAspx: 42, // TODO: this is truethy, but distinguishable from true: default will change to false in the future
escapeTitles: false,
extensions: [],
focusOnSelect: false,
generateIds: false,
icon: true,
idPrefix: "ft_",
keyboard: true,
keyPathSeparator: "/",
minExpandLevel: 1,
nodata: true, // (bool, string, or callback) display message, when no data available
quicksearch: false,
rtl: false,
scrollOfs: { top: 0, bottom: 0 },
scrollParent: null,
selectMode: 2,
strings: {
loading: "Loading...", // … would be escaped when escapeTitles is true
loadError: "Load error!",
moreData: "More...",
noData: "No data.",
},
tabindex: "0",
titlesTabbable: false,
toggleEffect: { effect: "slideToggle", duration: 200 }, //< "toggle" or "slideToggle" to use jQuery instead of jQueryUI for toggleEffect animation
tooltip: false,
treeId: null,
_classNames: {
active: "fancytree-active",
animating: "fancytree-animating",
combinedExpanderPrefix: "fancytree-exp-",
combinedIconPrefix: "fancytree-ico-",
error: "fancytree-error",
expanded: "fancytree-expanded",
focused: "fancytree-focused",
folder: "fancytree-folder",
hasChildren: "fancytree-has-children",
lastsib: "fancytree-lastsib",
lazy: "fancytree-lazy",
loading: "fancytree-loading",
node: "fancytree-node",
partload: "fancytree-partload",
partsel: "fancytree-partsel",
radio: "fancytree-radio",
selected: "fancytree-selected",
statusNodePrefix: "fancytree-statusnode-",
unselectable: "fancytree-unselectable",
},
// events
lazyLoad: null,
postProcess: null,
},
_deprecationWarning: function(name) {
var tree = this.tree;
if (tree && tree.options.debugLevel >= 3) {
tree.warn(
"$().fancytree('" +
name +
"') is deprecated (see https://wwwendt.de/tech/fancytree/doc/jsdoc/Fancytree_Widget.html"
);
}
},
/* Set up the widget, Called on first $().fancytree() */
_create: function() {
this.tree = new Fancytree(this);
this.$source =
this.source || this.element.data("type") === "json"
? this.element
: this.element.find(">ul").first();
// Subclass Fancytree instance with all enabled extensions
var extension,
extName,
i,
opts = this.options,
extensions = opts.extensions,
base = this.tree;
for (i = 0; i < extensions.length; i++) {
extName = extensions[i];
extension = $.ui.fancytree._extensions[extName];
if (!extension) {
$.error(
"Could not apply extension '" +
extName +
"' (it is not registered, did you forget to include it?)"
);
}
// Add extension options as tree.options.EXTENSION
// _assert(!this.tree.options[extName], "Extension name must not exist as option name: " + extName);
// console.info("extend " + extName, extension.options, this.tree.options[extName])
// issue #876: we want to replace custom array-options, not merge them
this.tree.options[extName] = _simpleDeepMerge(
{},
extension.options,
this.tree.options[extName]
);
// this.tree.options[extName] = $.extend(true, {}, extension.options, this.tree.options[extName]);
// console.info("extend " + extName + " =>", this.tree.options[extName])
// console.info("extend " + extName + " org default =>", extension.options)
// Add a namespace tree.ext.EXTENSION, to hold instance data
_assert(
this.tree.ext[extName] === undefined,
"Extension name must not exist as Fancytree.ext attribute: '" +
extName +
"'"
);
// this.tree[extName] = extension;
this.tree.ext[extName] = {};
// Subclass Fancytree methods using proxies.
_subclassObject(this.tree, base, extension, extName);
// current extension becomes base for the next extension
base = extension;
}
//
if (opts.icons !== undefined) {
// 2015-11-16
if (opts.icon === true) {
this.tree.warn(
"'icons' tree option is deprecated since v2.14.0: use 'icon' instead"
);
opts.icon = opts.icons;
} else {
$.error(
"'icons' tree option is deprecated since v2.14.0: use 'icon' only instead"
);
}
}
if (opts.iconClass !== undefined) {
// 2015-11-16
if (opts.icon) {
$.error(
"'iconClass' tree option is deprecated since v2.14.0: use 'icon' only instead"
);
} else {
this.tree.warn(
"'iconClass' tree option is deprecated since v2.14.0: use 'icon' instead"
);
opts.icon = opts.iconClass;
}
}
if (opts.tabbable !== undefined) {
// 2016-04-04
opts.tabindex = opts.tabbable ? "0" : "-1";
this.tree.warn(
"'tabbable' tree option is deprecated since v2.17.0: use 'tabindex='" +
opts.tabindex +
"' instead"
);
}
//
this.tree._callHook("treeCreate", this.tree);
// Note: 'fancytreecreate' event is fired by widget base class
// this.tree._triggerTreeEvent("create");
},
/* Called on every $().fancytree() */
_init: function() {
this.tree._callHook("treeInit", this.tree);
// TODO: currently we call bind after treeInit, because treeInit
// might change tree.$container.
// It would be better, to move event binding into hooks altogether
this._bind();
},
/* Use the _setOption method to respond to changes to options. */
_setOption: function(key, value) {
return this.tree._callHook(
"treeSetOption",
this.tree,
key,
value
);
},
/** Use the destroy method to clean up any modifications your widget has made to the DOM */
_destroy: function() {
this._unbind();
this.tree._callHook("treeDestroy", this.tree);
// In jQuery UI 1.8, you must invoke the destroy method from the base widget
// $.Widget.prototype.destroy.call(this);
// TODO: delete tree and nodes to make garbage collect easier?
// TODO: In jQuery UI 1.9 and above, you would define _destroy instead of destroy and not call the base method
},
// -------------------------------------------------------------------------
/* Remove all event handlers for our namespace */
_unbind: function() {
var ns = this.tree._ns;
this.element.off(ns);
this.tree.$container.off(ns);
$(document).off(ns);
},
/* Add mouse and kyboard handlers to the container */
_bind: function() {
var self = this,
opts = this.options,
tree = this.tree,
ns = tree._ns;
// selstartEvent = ( $.support.selectstart ? "selectstart" : "mousedown" )
// Remove all previuous handlers for this tree
this._unbind();
//alert("keydown" + ns + "foc=" + tree.hasFocus() + tree.$container);
// tree.debug("bind events; container: ", tree.$container);
tree.$container
.on("focusin" + ns + " focusout" + ns, function(event) {
var node = FT.getNode(event),
flag = event.type === "focusin";
if (!flag && node && $(event.target).is("a")) {
// #764
node.debug(
"Ignored focusout on embedded <a> element."
);
return;
}
// tree.treeOnFocusInOut.call(tree, event);
// tree.debug("Tree container got event " + event.type, node, event, FT.getEventTarget(event));
if (flag) {
if (tree._getExpiringValue("focusin")) {
// #789: IE 11 may send duplicate focusin events
tree.debug("Ignored double focusin.");
return;
}
tree._setExpiringValue("focusin", true, 50);
if (!node) {
// #789: IE 11 may send focusin before mousdown(?)
node = tree._getExpiringValue("mouseDownNode");
if (node) {
tree.debug(
"Reconstruct mouse target for focusin from recent event."
);
}
}
}
if (node) {
// For example clicking into an <input> that is part of a node
tree._callHook(
"nodeSetFocus",
tree._makeHookContext(node, event),
flag
);
} else {
if (
tree.tbody &&
$(event.target).parents(
"table.fancytree-container > thead"
).length
) {
// #767: ignore events in the table's header
tree.debug(
"Ignore focus event outside table body.",
event
);
} else {
tree._callHook("treeSetFocus", tree, flag);
}
}
})
.on("selectstart" + ns, "span.fancytree-title", function(
event
) {
// prevent mouse-drags to select text ranges
// tree.debug("<span title> got event " + event.type);
event.preventDefault();
})
.on("keydown" + ns, function(event) {
// TODO: also bind keyup and keypress
// tree.debug("got event " + event.type + ", hasFocus:" + tree.hasFocus());
// if(opts.disabled || opts.keyboard === false || !tree.hasFocus() ){
if (opts.disabled || opts.keyboard === false) {
return true;
}
var res,
node = tree.focusNode, // node may be null
ctx = tree._makeHookContext(node || tree, event),
prevPhase = tree.phase;
try {
tree.phase = "userEvent";
// If a 'fancytreekeydown' handler returns false, skip the default
// handling (implemented by tree.nodeKeydown()).
if (node) {
res = tree._triggerNodeEvent(
"keydown",
node,
event
);
} else {
res = tree._triggerTreeEvent("keydown", event);
}
if (res === "preventNav") {
res = true; // prevent keyboard navigation, but don't prevent default handling of embedded input controls
} else if (res !== false) {
res = tree._callHook("nodeKeydown", ctx);
}
return res;
} finally {
tree.phase = prevPhase;
}
})
.on("mousedown" + ns, function(event) {
var et = FT.getEventTarget(event);
// self.tree.debug("event(" + event.type + "): node: ", et.node);
// #712: Store the clicked node, so we can use it when we get a focusin event
// ('click' event fires after focusin)
// tree.debug("event(" + event.type + "): node: ", et.node);
tree._lastMousedownNode = et ? et.node : null;
// #789: Store the node also for a short period, so we can use it
// in a *resulting* focusin event
tree._setExpiringValue(
"mouseDownNode",
tree._lastMousedownNode
);
})
.on("click" + ns + " dblclick" + ns, function(event) {
if (opts.disabled) {
return true;
}
var ctx,
et = FT.getEventTarget(event),
node = et.node,
tree = self.tree,
prevPhase = tree.phase;
// self.tree.debug("event(" + event.type + "): node: ", node);
if (!node) {
return true; // Allow bubbling of other events
}
ctx = tree._makeHookContext(node, event);
// self.tree.debug("event(" + event.type + "): node: ", node);
try {
tree.phase = "userEvent";
switch (event.type) {
case "click":
ctx.targetType = et.type;
if (node.isPagingNode()) {
return (
tree._triggerNodeEvent(
"clickPaging",
ctx,
event
) === true
);
}
return tree._triggerNodeEvent(
"click",
ctx,
event
) === false
? false
: tree._callHook("nodeClick", ctx);
case "dblclick":
ctx.targetType = et.type;
return tree._triggerNodeEvent(
"dblclick",
ctx,
event
) === false
? false
: tree._callHook("nodeDblclick", ctx);
}
} finally {
tree.phase = prevPhase;
}
});
},
/** Return the active node or null.
* @returns {FancytreeNode}
* @deprecated Use methods of the Fancytree instance instead (<a href="Fancytree_Widget.html">example above</a>).
*/
getActiveNode: function() {
this._deprecationWarning("getActiveNode");
return this.tree.activeNode;
},
/** Return the matching node or null.
* @param {string} key
* @returns {FancytreeNode}
* @deprecated Use methods of the Fancytree instance instead (<a href="Fancytree_Widget.html">example above</a>).
*/
getNodeByKey: function(key) {
this._deprecationWarning("getNodeByKey");
return this.tree.getNodeByKey(key);
},
/** Return the invisible system root node.
* @returns {FancytreeNode}
* @deprecated Use methods of the Fancytree instance instead (<a href="Fancytree_Widget.html">example above</a>).
*/
getRootNode: function() {
this._deprecationWarning("getRootNode");
return this.tree.rootNode;
},
/** Return the current tree instance.
* @returns {Fancytree}
* @deprecated Use `$.ui.fancytree.getTree()` instead (<a href="Fancytree_Widget.html">example above</a>).
*/
getTree: function() {
this._deprecationWarning("getTree");
return this.tree;
},
}
);
// $.ui.fancytree was created by the widget factory. Create a local shortcut:
FT = $.ui.fancytree;
/**
* Static members in the `$.ui.fancytree` namespace.
* This properties and methods can be accessed without instantiating a concrete
* Fancytree instance.
*
* @example
* // Access static members:
* var node = $.ui.fancytree.getNode(element);
* alert($.ui.fancytree.version);
*
* @mixin Fancytree_Static
*/
$.extend(
$.ui.fancytree,
/** @lends Fancytree_Static# */
{
/** Version number `"MAJOR.MINOR.PATCH"`
* @type {string} */
version: "2.37.0", // Set to semver by 'grunt release'
/** @type {string}
* @description `"production" for release builds` */
buildType: "production", // Set to 'production' by 'grunt build'
/** @type {int}
* @description 0: silent .. 5: verbose (default: 3 for release builds). */
debugLevel: 3, // Set to 3 by 'grunt build'
// Used by $.ui.fancytree.debug() and as default for tree.options.debugLevel
_nextId: 1,
_nextNodeKey: 1,
_extensions: {},
// focusTree: null,
/** Expose class object as `$.ui.fancytree._FancytreeClass`.
* Useful to extend `$.ui.fancytree._FancytreeClass.prototype`.
* @type {Fancytree}
*/
_FancytreeClass: Fancytree,
/** Expose class object as $.ui.fancytree._FancytreeNodeClass
* Useful to extend `$.ui.fancytree._FancytreeNodeClass.prototype`.
* @type {FancytreeNode}
*/
_FancytreeNodeClass: FancytreeNode,
/* Feature checks to provide backwards compatibility */
jquerySupports: {
// http://jqueryui.com/upgrade-guide/1.9/#deprecated-offset-option-merged-into-my-and-at
positionMyOfs: isVersionAtLeast($.ui.version, 1, 9),
},
/** Throw an error if condition fails (debug method).
* @param {boolean} cond
* @param {string} msg
*/
assert: function(cond, msg) {
return _assert(cond, msg);
},
/** Create a new Fancytree instance on a target element.
*
* @param {Element | jQueryObject | string} el Target DOM element or selector
* @param {FancytreeOptions} [opts] Fancytree options
* @returns {Fancytree} new tree instance
* @example
* var tree = $.ui.fancytree.createTree("#tree", {
* source: {url: "my/webservice"}
* }); // Create tree for this matching element
*
* @since 2.25
*/
createTree: function(el, opts) {
var $tree = $(el).fancytree(opts);
return FT.getTree($tree);
},
/** Return a function that executes *fn* at most every *timeout* ms.
* @param {integer} timeout
* @param {function} fn
* @param {boolean} [invokeAsap=false]
* @param {any} [ctx]
*/
debounce: function(timeout, fn, invokeAsap, ctx) {
var timer;
if (arguments.length === 3 && typeof invokeAsap !== "boolean") {
ctx = invokeAsap;
invokeAsap = false;
}
return function() {
var args = arguments;
ctx = ctx || this;
// eslint-disable-next-line no-unused-expressions
invokeAsap && !timer && fn.apply(ctx, args);
clearTimeout(timer);
timer = setTimeout(function() {
// eslint-disable-next-line no-unused-expressions
invokeAsap || fn.apply(ctx, args);
timer = null;
}, timeout);
};
},
/** Write message to console if debugLevel >= 4
* @param {string} msg
*/
debug: function(msg) {
if ($.ui.fancytree.debugLevel >= 4) {
consoleApply("log", arguments);
}
},
/** Write error message to console if debugLevel >= 1.
* @param {string} msg
*/
error: function(msg) {
if ($.ui.fancytree.debugLevel >= 1) {
consoleApply("error", arguments);
}
},
/** Convert `<`, `>`, `&`, `"`, `'`, and `/` to the equivalent entities.
*
* @param {string} s
* @returns {string}
*/
escapeHtml: function(s) {
return ("" + s).replace(REX_HTML, function(s) {
return ENTITY_MAP[s];
});
},
/** Make jQuery.position() arguments backwards compatible, i.e. if
* jQuery UI version <= 1.8, convert
* { my: "left+3 center", at: "left bottom", of: $target }
* to
* { my: "left center", at: "left bottom", of: $target, offset: "3 0" }
*
* See http://jqueryui.com/upgrade-guide/1.9/#deprecated-offset-option-merged-into-my-and-at
* and http://jsfiddle.net/mar10/6xtu9a4e/
*
* @param {object} opts
* @returns {object} the (potentially modified) original opts hash object
*/
fixPositionOptions: function(opts) {
if (opts.offset || ("" + opts.my + opts.at).indexOf("%") >= 0) {
$.error(
"expected new position syntax (but '%' is not supported)"
);
}
if (!$.ui.fancytree.jquerySupports.positionMyOfs) {
var // parse 'left+3 center' into ['left+3 center', 'left', '+3', 'center', undefined]
myParts = /(\w+)([+-]?\d+)?\s+(\w+)([+-]?\d+)?/.exec(
opts.my
),
atParts = /(\w+)([+-]?\d+)?\s+(\w+)([+-]?\d+)?/.exec(
opts.at
),
// convert to numbers
dx =
(myParts[2] ? +myParts[2] : 0) +
(atParts[2] ? +atParts[2] : 0),
dy =
(myParts[4] ? +myParts[4] : 0) +
(atParts[4] ? +atParts[4] : 0);
opts = $.extend({}, opts, {
// make a copy and overwrite
my: myParts[1] + " " + myParts[3],
at: atParts[1] + " " + atParts[3],
});
if (dx || dy) {
opts.offset = "" + dx + " " + dy;
}
}
return opts;
},
/** Return a {node: FancytreeNode, type: TYPE} object for a mouse event.
*
* @param {Event} event Mouse event, e.g. click, ...
* @returns {object} Return a {node: FancytreeNode, type: TYPE} object
* TYPE: 'title' | 'prefix' | 'expander' | 'checkbox' | 'icon' | undefined
*/
getEventTarget: function(event) {
var $target,
tree,
tcn = event && event.target ? event.target.className : "",
res = { node: this.getNode(event.target), type: undefined };
// We use a fast version of $(res.node).hasClass()
// See http://jsperf.com/test-for-classname/2
if (/\bfancytree-title\b/.test(tcn)) {
res.type = "title";
} else if (/\bfancytree-expander\b/.test(tcn)) {
res.type =
res.node.hasChildren() === false
? "prefix"
: "expander";
// }else if( /\bfancytree-checkbox\b/.test(tcn) || /\bfancytree-radio\b/.test(tcn) ){
} else if (/\bfancytree-checkbox\b/.test(tcn)) {
res.type = "checkbox";
} else if (/\bfancytree(-custom)?-icon\b/.test(tcn)) {
res.type = "icon";
} else if (/\bfancytree-node\b/.test(tcn)) {
// Somewhere near the title
res.type = "title";
} else if (event && event.target) {
$target = $(event.target);
if ($target.is("ul[role=group]")) {
// #nnn: Clicking right to a node may hit the surrounding UL
tree = res.node && res.node.tree;
(tree || FT).debug("Ignoring click on outer UL.");
res.node = null;
} else if ($target.closest(".fancytree-title").length) {
// #228: clicking an embedded element inside a title
res.type = "title";
} else if ($target.closest(".fancytree-checkbox").length) {
// E.g. <svg> inside checkbox span
res.type = "checkbox";
} else if ($target.closest(".fancytree-expander").length) {
res.type = "expander";
}
}
return res;
},
/** Return a string describing the affected node region for a mouse event.
*
* @param {Event} event Mouse event, e.g. click, mousemove, ...
* @returns {string} 'title' | 'prefix' | 'expander' | 'checkbox' | 'icon' | undefined
*/
getEventTargetType: function(event) {
return this.getEventTarget(event).type;
},
/** Return a FancytreeNode instance from element, event, or jQuery object.
*
* @param {Element | jQueryObject | Event} el
* @returns {FancytreeNode} matching node or null
*/
getNode: function(el) {
if (el instanceof FancytreeNode) {
return el; // el already was a FancytreeNode
} else if (el instanceof $) {
el = el[0]; // el was a jQuery object: use the DOM element
} else if (el.originalEvent !== undefined) {
el = el.target; // el was an Event
}
while (el) {
if (el.ftnode) {
return el.ftnode;
}
el = el.parentNode;
}
return null;
},
/** Return a Fancytree instance, from element, index, event, or jQueryObject.
*
* @param {Element | jQueryObject | Event | integer | string} [el]
* @returns {Fancytree} matching tree or null
* @example
* $.ui.fancytree.getTree(); // Get first Fancytree instance on page
* $.ui.fancytree.getTree(1); // Get second Fancytree instance on page
* $.ui.fancytree.getTree(event); // Get tree for this mouse- or keyboard event
* $.ui.fancytree.getTree("foo"); // Get tree for this `opts.treeId`
* $.ui.fancytree.getTree("#tree"); // Get tree for this matching element
*
* @since 2.13
*/
getTree: function(el) {
var widget,
orgEl = el;
if (el instanceof Fancytree) {
return el; // el already was a Fancytree
}
if (el === undefined) {
el = 0; // get first tree
}
if (typeof el === "number") {
el = $(".fancytree-container").eq(el); // el was an integer: return nth instance
} else if (typeof el === "string") {
// `el` may be a treeId or a selector:
el = $("#ft-id-" + orgEl).eq(0);
if (!el.length) {
el = $(orgEl).eq(0); // el was a selector: use first match
}
} else if (
el instanceof Element ||
el instanceof HTMLDocument
) {
el = $(el);
} else if (el instanceof $) {
el = el.eq(0); // el was a jQuery object: use the first
} else if (el.originalEvent !== undefined) {
el = $(el.target); // el was an Event
}
// el is a jQuery object wit one element here
el = el.closest(":ui-fancytree");
widget = el.data("ui-fancytree") || el.data("fancytree"); // the latter is required by jQuery <= 1.8
return widget ? widget.tree : null;
},
/** Return an option value that has a default, but may be overridden by a
* callback or a node instance attribute.
*
* Evaluation sequence:
*
* If `tree.options.<optionName>` is a callback that returns something, use that.
* Else if `node.<optionName>` is defined, use that.
* Else if `tree.options.<optionName>` is a value, use that.
* Else use `defaultValue`.
*
* @param {string} optionName name of the option property (on node and tree)
* @param {FancytreeNode} node passed to the callback
* @param {object} nodeObject where to look for the local option property, e.g. `node` or `node.data`
* @param {object} treeOption where to look for the tree option, e.g. `tree.options` or `tree.options.dnd5`
* @param {any} [defaultValue]
* @returns {any}
*
* @example
* // Check for node.foo, tree,options.foo(), and tree.options.foo:
* $.ui.fancytree.evalOption("foo", node, node, tree.options);
* // Check for node.data.bar, tree,options.qux.bar(), and tree.options.qux.bar:
* $.ui.fancytree.evalOption("bar", node, node.data, tree.options.qux);
*
* @since 2.22
*/
evalOption: function(
optionName,
node,
nodeObject,
treeOptions,
defaultValue
) {
var ctx,
res,
tree = node.tree,
treeOpt = treeOptions[optionName],
nodeOpt = nodeObject[optionName];
if ($.isFunction(treeOpt)) {
ctx = {
node: node,
tree: tree,
widget: tree.widget,
options: tree.widget.options,
typeInfo: tree.types[node.type] || {},
};
res = treeOpt.call(tree, { type: optionName }, ctx);
if (res == null) {
res = nodeOpt;
}
} else {
res = nodeOpt == null ? treeOpt : nodeOpt;
}
if (res == null) {
res = defaultValue; // no option set at all: return default
}
return res;
},
/** Set expander, checkbox, or node icon, supporting string and object format.
*
* @param {Element | jQueryObject} span
* @param {string} baseClass
* @param {string | object} icon
* @since 2.27
*/
setSpanIcon: function(span, baseClass, icon) {
var $span = $(span);
if (typeof icon === "string") {
$span.attr("class", baseClass + " " + icon);
} else {
// support object syntax: { text: ligature, addClasse: classname }
if (icon.text) {
$span.text("" + icon.text);
} else if (icon.html) {
span.innerHTML = icon.html;
}
$span.attr(
"class",
baseClass + " " + (icon.addClass || "")
);
}
},
/** Convert a keydown or mouse event to a canonical string like 'ctrl+a',
* 'ctrl+shift+f2', 'shift+leftdblclick'.
*
* This is especially handy for switch-statements in event handlers.
*
* @param {event}
* @returns {string}
*
* @example
switch( $.ui.fancytree.eventToString(event) ) {
case "-":
tree.nodeSetExpanded(ctx, false);
break;
case "shift+return":
tree.nodeSetActive(ctx, true);
break;
case "down":
res = node.navigate(event.which, activate);
break;
default:
handled = false;
}
if( handled ){
event.preventDefault();
}
*/
eventToString: function(event) {
// Poor-man's hotkeys. See here for a complete implementation:
// https://github.com/jeresig/jquery.hotkeys
var which = event.which,
et = event.type,
s = [];
if (event.altKey) {
s.push("alt");
}
if (event.ctrlKey) {
s.push("ctrl");
}
if (event.metaKey) {
s.push("meta");
}
if (event.shiftKey) {
s.push("shift");
}
if (et === "click" || et === "dblclick") {
s.push(MOUSE_BUTTONS[event.button] + et);
} else if (et === "wheel") {
s.push(et);
} else if (!IGNORE_KEYCODES[which]) {
s.push(
SPECIAL_KEYCODES[which] ||
String.fromCharCode(which).toLowerCase()
);
}
return s.join("+");
},
/** Write message to console if debugLevel >= 3
* @param {string} msg
*/
info: function(msg) {
if ($.ui.fancytree.debugLevel >= 3) {
consoleApply("info", arguments);
}
},
/* @deprecated: use eventToString(event) instead.
*/
keyEventToString: function(event) {
this.warn(
"keyEventToString() is deprecated: use eventToString()"
);
return this.eventToString(event);
},
/** Return a wrapped handler method, that provides `this._super`.
*
* @example
// Implement `opts.createNode` event to add the 'draggable' attribute
$.ui.fancytree.overrideMethod(ctx.options, "createNode", function(event, data) {
// Default processing if any
this._super.apply(this, arguments);
// Add 'draggable' attribute
data.node.span.draggable = true;
});
*
* @param {object} instance
* @param {string} methodName
* @param {function} handler
* @param {object} [context] optional context
*/
overrideMethod: function(instance, methodName, handler, context) {
var prevSuper,
_super = instance[methodName] || $.noop;
instance[methodName] = function() {
var self = context || this;
try {
prevSuper = self._super;
self._super = _super;
return handler.apply(self, arguments);
} finally {
self._super = prevSuper;
}
};
},
/**
* Parse tree data from HTML <ul> markup
*
* @param {jQueryObject} $ul
* @returns {NodeData[]}
*/
parseHtml: function($ul) {
var classes,
className,
extraClasses,
i,
iPos,
l,
tmp,
tmp2,
$children = $ul.find(">li"),
children = [];
$children.each(function() {
var allData,
lowerCaseAttr,
$li = $(this),
$liSpan = $li.find(">span", this).first(),
$liA = $liSpan.length ? null : $li.find(">a").first(),
d = { tooltip: null, data: {} };
if ($liSpan.length) {
d.title = $liSpan.html();
} else if ($liA && $liA.length) {
// If a <li><a> tag is specified, use it literally and extract href/target.
d.title = $liA.html();
d.data.href = $liA.attr("href");
d.data.target = $liA.attr("target");
d.tooltip = $liA.attr("title");
} else {
// If only a <li> tag is specified, use the trimmed string up to
// the next child <ul> tag.
d.title = $li.html();
iPos = d.title.search(/<ul/i);
if (iPos >= 0) {
d.title = d.title.substring(0, iPos);
}
}
d.title = $.trim(d.title);
// Make sure all fields exist
for (i = 0, l = CLASS_ATTRS.length; i < l; i++) {
d[CLASS_ATTRS[i]] = undefined;
}
// Initialize to `true`, if class is set and collect extraClasses
classes = this.className.split(" ");
extraClasses = [];
for (i = 0, l = classes.length; i < l; i++) {
className = classes[i];
if (CLASS_ATTR_MAP[className]) {
d[className] = true;
} else {
extraClasses.push(className);
}
}
d.extraClasses = extraClasses.join(" ");
// Parse node options from ID, title and class attributes
tmp = $li.attr("title");
if (tmp) {
d.tooltip = tmp; // overrides <a title='...'>
}
tmp = $li.attr("id");
if (tmp) {
d.key = tmp;
}
// Translate hideCheckbox -> checkbox:false
if ($li.attr("hideCheckbox")) {
d.checkbox = false;
}
// Add <li data-NAME='...'> as node.data.NAME
allData = _getElementDataAsDict($li);
if (allData && !$.isEmptyObject(allData)) {
// #507: convert data-hidecheckbox (lower case) to hideCheckbox
for (lowerCaseAttr in NODE_ATTR_LOWERCASE_MAP) {
if (allData.hasOwnProperty(lowerCaseAttr)) {
allData[
NODE_ATTR_LOWERCASE_MAP[lowerCaseAttr]
] = allData[lowerCaseAttr];
delete allData[lowerCaseAttr];
}
}
// #56: Allow to set special node.attributes from data-...
for (i = 0, l = NODE_ATTRS.length; i < l; i++) {
tmp = NODE_ATTRS[i];
tmp2 = allData[tmp];
if (tmp2 != null) {
delete allData[tmp];
d[tmp] = tmp2;
}
}
// All other data-... goes to node.data...
$.extend(d.data, allData);
}
// Recursive reading of child nodes, if LI tag contains an UL tag
$ul = $li.find(">ul").first();
if ($ul.length) {
d.children = $.ui.fancytree.parseHtml($ul);
} else {
d.children = d.lazy ? undefined : null;
}
children.push(d);
// FT.debug("parse ", d, children);
});
return children;
},
/** Add Fancytree extension definition to the list of globally available extensions.
*
* @param {object} definition
*/
registerExtension: function(definition) {
_assert(
definition.name != null,
"extensions must have a `name` property."
);
_assert(
definition.version != null,
"extensions must have a `version` property."
);
$.ui.fancytree._extensions[definition.name] = definition;
},
/** Inverse of escapeHtml().
*
* @param {string} s
* @returns {string}
*/
unescapeHtml: function(s) {
var e = document.createElement("div");
e.innerHTML = s;
return e.childNodes.length === 0
? ""
: e.childNodes[0].nodeValue;
},
/** Write warning message to console if debugLevel >= 2.
* @param {string} msg
*/
warn: function(msg) {
if ($.ui.fancytree.debugLevel >= 2) {
consoleApply("warn", arguments);
}
},
}
);
// Value returned by `require('jquery.fancytree')`
return $.ui.fancytree;
}); // End of closure
// Extending Fancytree
// ===================
//
// See also the [live demo](https://wwWendt.de/tech/fancytree/demo/sample-ext-childcounter.html) of this code.
//
// Every extension should have a comment header containing some information
// about the author, copyright and licensing. Also a pointer to the latest
// source code.
// Prefix with `/*!` so the comment is not removed by the minifier.
/*!
* jquery.fancytree.childcounter.js
*
* Add a child counter bubble to tree nodes.
* (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
*
* Copyright (c) 2008-2020, Martin Wendt (https://wwWendt.de)
*
* Released under the MIT license
* https://github.com/mar10/fancytree/wiki/LicenseInfo
*
* @version 2.37.0
* @date 2020-09-11T18:58:08Z
*/
// To keep the global namespace clean, we wrap everything in a closure.
// The UMD wrapper pattern defines the dependencies on jQuery and the
// Fancytree core module, and makes sure that we can use the `require()`
// syntax with package loaders.
(function(factory) {
if (typeof define === "function" && define.amd) {
// AMD. Register as an anonymous module.
define(["jquery", "./jquery.fancytree"], factory);
} else if (typeof module === "object" && module.exports) {
// Node/CommonJS
require("./jquery.fancytree");
module.exports = factory(require("jquery"));
} else {
// Browser globals
factory(jQuery);
}
})(function($) {
// Consider to use [strict mode](http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/)
"use strict";
// The [coding guidelines](http://contribute.jquery.org/style-guide/js/)
// require jshint /eslint compliance.
// But for this sample, we want to allow unused variables for demonstration purpose.
/*eslint-disable no-unused-vars */
// Adding methods
// --------------
// New member functions can be added to the `Fancytree` class.
// This function will be available for every tree instance:
//
// var tree = $.ui.fancytree.getTree("#tree");
// tree.countSelected(false);
$.ui.fancytree._FancytreeClass.prototype.countSelected = function(topOnly) {
var tree = this,
treeOptions = tree.options;
return tree.getSelectedNodes(topOnly).length;
};
// The `FancytreeNode` class can also be easily extended. This would be called
// like
// node.updateCounters();
//
// It is also good practice to add a docstring comment.
/**
* [ext-childcounter] Update counter badges for `node` and its parents.
* May be called in the `loadChildren` event, to update parents of lazy loaded
* nodes.
* @alias FancytreeNode#updateCounters
* @requires jquery.fancytree.childcounters.js
*/
$.ui.fancytree._FancytreeNodeClass.prototype.updateCounters = function() {
var node = this,
$badge = $("span.fancytree-childcounter", node.span),
extOpts = node.tree.options.childcounter,
count = node.countChildren(extOpts.deep);
node.data.childCounter = count;
if (
(count || !extOpts.hideZeros) &&
(!node.isExpanded() || !extOpts.hideExpanded)
) {
if (!$badge.length) {
$badge = $("<span class='fancytree-childcounter'/>").appendTo(
$(
"span.fancytree-icon,span.fancytree-custom-icon",
node.span
)
);
}
$badge.text(count);
} else {
$badge.remove();
}
if (extOpts.deep && !node.isTopLevel() && !node.isRootNode()) {
node.parent.updateCounters();
}
};
// Finally, we can extend the widget API and create functions that are called
// like so:
//
// $("#tree").fancytree("widgetMethod1", "abc");
$.ui.fancytree.prototype.widgetMethod1 = function(arg1) {
var tree = this.tree;
return arg1;
};
// Register a Fancytree extension
// ------------------------------
// A full blown extension, extension is available for all trees and can be
// enabled like so (see also the [live demo](https://wwWendt.de/tech/fancytree/demo/sample-ext-childcounter.html)):
//
// <script src="../src/jquery.fancytree.js"></script>
// <script src="../src/jquery.fancytree.childcounter.js"></script>
// ...
//
// $("#tree").fancytree({
// extensions: ["childcounter"],
// childcounter: {
// hideExpanded: true
// },
// ...
// });
//
/* 'childcounter' extension */
$.ui.fancytree.registerExtension({
// Every extension must be registered by a unique name.
name: "childcounter",
// Version information should be compliant with [semver](http://semver.org)
version: "2.37.0",
// Extension specific options and their defaults.
// This options will be available as `tree.options.childcounter.hideExpanded`
options: {
deep: true,
hideZeros: true,
hideExpanded: false,
},
// Attributes other than `options` (or functions) can be defined here, and
// will be added to the tree.ext.EXTNAME namespace, in this case `tree.ext.childcounter.foo`.
// They can also be accessed as `this._local.foo` from within the extension
// methods.
foo: 42,
// Local functions are prefixed with an underscore '_'.
// Callable as `this._local._appendCounter()`.
_appendCounter: function(bar) {
var tree = this;
},
// **Override virtual methods for this extension.**
//
// Fancytree implements a number of 'hook methods', prefixed by 'node...' or 'tree...'.
// with a `ctx` argument (see [EventData](https://wwWendt.de/tech/fancytree/doc/jsdoc/global.html#EventData)
// for details) and an extended calling context:<br>
// `this` : the Fancytree instance<br>
// `this._local`: the namespace that contains extension attributes and private methods (same as this.ext.EXTNAME)<br>
// `this._super`: the virtual function that was overridden (member of previous extension or Fancytree)
//
// See also the [complete list of available hook functions](https://wwWendt.de/tech/fancytree/doc/jsdoc/Fancytree_Hooks.html).
/* Init */
// `treeInit` is triggered when a tree is initalized. We can set up classes or
// bind event handlers here...
treeInit: function(ctx) {
var tree = this, // same as ctx.tree,
opts = ctx.options,
extOpts = ctx.options.childcounter;
// Optionally check for dependencies with other extensions
/* this._requireExtension("glyph", false, false); */
// Call the base implementation
this._superApply(arguments);
// Add a class to the tree container
this.$container.addClass("fancytree-ext-childcounter");
},
// Destroy this tree instance (we only call the default implementation, so
// this method could as well be omitted).
treeDestroy: function(ctx) {
this._superApply(arguments);
},
// Overload the `renderTitle` hook, to append a counter badge
nodeRenderTitle: function(ctx, title) {
var node = ctx.node,
extOpts = ctx.options.childcounter,
count =
node.data.childCounter == null
? node.countChildren(extOpts.deep)
: +node.data.childCounter;
// Let the base implementation render the title
// We use `_super()` instead of `_superApply()` here, since it is a little bit
// more performant when called often
this._super(ctx, title);
// Append a counter badge
if (
(count || !extOpts.hideZeros) &&
(!node.isExpanded() || !extOpts.hideExpanded)
) {
$(
"span.fancytree-icon,span.fancytree-custom-icon",
node.span
).append(
$("<span class='fancytree-childcounter'/>").text(count)
);
}
},
// Overload the `setExpanded` hook, so the counters are updated
nodeSetExpanded: function(ctx, flag, callOpts) {
var tree = ctx.tree,
node = ctx.node;
// Let the base implementation expand/collapse the node, then redraw the title
// after the animation has finished
return this._superApply(arguments).always(function() {
tree.nodeRenderTitle(ctx);
});
},
// End of extension definition
});
// Value returned by `require('jquery.fancytree..')`
return $.ui.fancytree;
}); // End of closure
/*!
*
* jquery.fancytree.clones.js
* Support faster lookup of nodes by key and shared ref-ids.
* (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
*
* Copyright (c) 2008-2020, Martin Wendt (https://wwWendt.de)
*
* Released under the MIT license
* https://github.com/mar10/fancytree/wiki/LicenseInfo
*
* @version 2.37.0
* @date 2020-09-11T18:58:08Z
*/
(function(factory) {
if (typeof define === "function" && define.amd) {
// AMD. Register as an anonymous module.
define(["jquery", "./jquery.fancytree"], factory);
} else if (typeof module === "object" && module.exports) {
// Node/CommonJS
require("./jquery.fancytree");
module.exports = factory(require("jquery"));
} else {
// Browser globals
factory(jQuery);
}
})(function($) {
"use strict";
/*******************************************************************************
* Private functions and variables
*/
function _assert(cond, msg) {
// TODO: see qunit.js extractStacktrace()
if (!cond) {
msg = msg ? ": " + msg : "";
$.error("Assertion failed" + msg);
}
}
/* Return first occurrence of member from array. */
function _removeArrayMember(arr, elem) {
// TODO: use Array.indexOf for IE >= 9
var i;
for (i = arr.length - 1; i >= 0; i--) {
if (arr[i] === elem) {
arr.splice(i, 1);
return true;
}
}
return false;
}
/**
* JS Implementation of MurmurHash3 (r136) (as of May 20, 2011)
*
* @author <a href="mailto:gary.court@gmail.com">Gary Court</a>
* @see http://github.com/garycourt/murmurhash-js
* @author <a href="mailto:aappleby@gmail.com">Austin Appleby</a>
* @see http://sites.google.com/site/murmurhash/
*
* @param {string} key ASCII only
* @param {boolean} [asString=false]
* @param {number} seed Positive integer only
* @return {number} 32-bit positive integer hash
*/
function hashMurmur3(key, asString, seed) {
/*eslint-disable no-bitwise */
var h1b,
k1,
remainder = key.length & 3,
bytes = key.length - remainder,
h1 = seed,
c1 = 0xcc9e2d51,
c2 = 0x1b873593,
i = 0;
while (i < bytes) {
k1 =
(key.charCodeAt(i) & 0xff) |
((key.charCodeAt(++i) & 0xff) << 8) |
((key.charCodeAt(++i) & 0xff) << 16) |
((key.charCodeAt(++i) & 0xff) << 24);
++i;
k1 =
((k1 & 0xffff) * c1 + ((((k1 >>> 16) * c1) & 0xffff) << 16)) &
0xffffffff;
k1 = (k1 << 15) | (k1 >>> 17);
k1 =
((k1 & 0xffff) * c2 + ((((k1 >>> 16) * c2) & 0xffff) << 16)) &
0xffffffff;
h1 ^= k1;
h1 = (h1 << 13) | (h1 >>> 19);
h1b =
((h1 & 0xffff) * 5 + ((((h1 >>> 16) * 5) & 0xffff) << 16)) &
0xffffffff;
h1 =
(h1b & 0xffff) +
0x6b64 +
((((h1b >>> 16) + 0xe654) & 0xffff) << 16);
}
k1 = 0;
switch (remainder) {
case 3:
k1 ^= (key.charCodeAt(i + 2) & 0xff) << 16;
// fall through
case 2:
k1 ^= (key.charCodeAt(i + 1) & 0xff) << 8;
// fall through
case 1:
k1 ^= key.charCodeAt(i) & 0xff;
k1 =
((k1 & 0xffff) * c1 +
((((k1 >>> 16) * c1) & 0xffff) << 16)) &
0xffffffff;
k1 = (k1 << 15) | (k1 >>> 17);
k1 =
((k1 & 0xffff) * c2 +
((((k1 >>> 16) * c2) & 0xffff) << 16)) &
0xffffffff;
h1 ^= k1;
}
h1 ^= key.length;
h1 ^= h1 >>> 16;
h1 =
((h1 & 0xffff) * 0x85ebca6b +
((((h1 >>> 16) * 0x85ebca6b) & 0xffff) << 16)) &
0xffffffff;
h1 ^= h1 >>> 13;
h1 =
((h1 & 0xffff) * 0xc2b2ae35 +
((((h1 >>> 16) * 0xc2b2ae35) & 0xffff) << 16)) &
0xffffffff;
h1 ^= h1 >>> 16;
if (asString) {
// Convert to 8 digit hex string
return ("0000000" + (h1 >>> 0).toString(16)).substr(-8);
}
return h1 >>> 0;
/*eslint-enable no-bitwise */
}
/*
* Return a unique key for node by calculating the hash of the parents refKey-list.
*/
function calcUniqueKey(node) {
var key,
h1,
path = $.map(node.getParentList(false, true), function(e) {
return e.refKey || e.key;
});
path = path.join("/");
// 32-bit has a high probability of collisions, so we pump up to 64-bit
// https://security.stackexchange.com/q/209882/207588
h1 = hashMurmur3(path, true);
key = "id_" + h1 + hashMurmur3(h1 + path, true);
return key;
}
/**
* [ext-clones] Return a list of clone-nodes (i.e. same refKey) or null.
* @param {boolean} [includeSelf=false]
* @returns {FancytreeNode[] | null}
*
* @alias FancytreeNode#getCloneList
* @requires jquery.fancytree.clones.js
*/
$.ui.fancytree._FancytreeNodeClass.prototype.getCloneList = function(
includeSelf
) {
var key,
tree = this.tree,
refList = tree.refMap[this.refKey] || null,
keyMap = tree.keyMap;
if (refList) {
key = this.key;
// Convert key list to node list
if (includeSelf) {
refList = $.map(refList, function(val) {
return keyMap[val];
});
} else {
refList = $.map(refList, function(val) {
return val === key ? null : keyMap[val];
});
if (refList.length < 1) {
refList = null;
}
}
}
return refList;
};
/**
* [ext-clones] Return true if this node has at least another clone with same refKey.
* @returns {boolean}
*
* @alias FancytreeNode#isClone
* @requires jquery.fancytree.clones.js
*/
$.ui.fancytree._FancytreeNodeClass.prototype.isClone = function() {
var refKey = this.refKey || null,
refList = (refKey && this.tree.refMap[refKey]) || null;
return !!(refList && refList.length > 1);
};
/**
* [ext-clones] Update key and/or refKey for an existing node.
* @param {string} key
* @param {string} refKey
* @returns {boolean}
*
* @alias FancytreeNode#reRegister
* @requires jquery.fancytree.clones.js
*/
$.ui.fancytree._FancytreeNodeClass.prototype.reRegister = function(
key,
refKey
) {
key = key == null ? null : "" + key;
refKey = refKey == null ? null : "" + refKey;
// this.debug("reRegister", key, refKey);
var tree = this.tree,
prevKey = this.key,
prevRefKey = this.refKey,
keyMap = tree.keyMap,
refMap = tree.refMap,
refList = refMap[prevRefKey] || null,
// curCloneKeys = refList ? node.getCloneList(true),
modified = false;
// Key has changed: update all references
if (key != null && key !== this.key) {
if (keyMap[key]) {
$.error(
"[ext-clones] reRegister(" +
key +
"): already exists: " +
this
);
}
// Update keyMap
delete keyMap[prevKey];
keyMap[key] = this;
// Update refMap
if (refList) {
refMap[prevRefKey] = $.map(refList, function(e) {
return e === prevKey ? key : e;
});
}
this.key = key;
modified = true;
}
// refKey has changed
if (refKey != null && refKey !== this.refKey) {
// Remove previous refKeys
if (refList) {
if (refList.length === 1) {
delete refMap[prevRefKey];
} else {
refMap[prevRefKey] = $.map(refList, function(e) {
return e === prevKey ? null : e;
});
}
}
// Add refKey
if (refMap[refKey]) {
refMap[refKey].append(key);
} else {
refMap[refKey] = [this.key];
}
this.refKey = refKey;
modified = true;
}
return modified;
};
/**
* [ext-clones] Define a refKey for an existing node.
* @param {string} refKey
* @returns {boolean}
*
* @alias FancytreeNode#setRefKey
* @requires jquery.fancytree.clones.js
* @since 2.16
*/
$.ui.fancytree._FancytreeNodeClass.prototype.setRefKey = function(refKey) {
return this.reRegister(null, refKey);
};
/**
* [ext-clones] Return all nodes with a given refKey (null if not found).
* @param {string} refKey
* @param {FancytreeNode} [rootNode] optionally restrict results to descendants of this node
* @returns {FancytreeNode[] | null}
* @alias Fancytree#getNodesByRef
* @requires jquery.fancytree.clones.js
*/
$.ui.fancytree._FancytreeClass.prototype.getNodesByRef = function(
refKey,
rootNode
) {
var keyMap = this.keyMap,
refList = this.refMap[refKey] || null;
if (refList) {
// Convert key list to node list
if (rootNode) {
refList = $.map(refList, function(val) {
var node = keyMap[val];
return node.isDescendantOf(rootNode) ? node : null;
});
} else {
refList = $.map(refList, function(val) {
return keyMap[val];
});
}
if (refList.length < 1) {
refList = null;
}
}
return refList;
};
/**
* [ext-clones] Replace a refKey with a new one.
* @param {string} oldRefKey
* @param {string} newRefKey
* @alias Fancytree#changeRefKey
* @requires jquery.fancytree.clones.js
*/
$.ui.fancytree._FancytreeClass.prototype.changeRefKey = function(
oldRefKey,
newRefKey
) {
var i,
node,
keyMap = this.keyMap,
refList = this.refMap[oldRefKey] || null;
if (refList) {
for (i = 0; i < refList.length; i++) {
node = keyMap[refList[i]];
node.refKey = newRefKey;
}
delete this.refMap[oldRefKey];
this.refMap[newRefKey] = refList;
}
};
/*******************************************************************************
* Extension code
*/
$.ui.fancytree.registerExtension({
name: "clones",
version: "2.37.0",
// Default options for this extension.
options: {
highlightActiveClones: true, // set 'fancytree-active-clone' on active clones and all peers
highlightClones: false, // set 'fancytree-clone' class on any node that has at least one clone
},
treeCreate: function(ctx) {
this._superApply(arguments);
ctx.tree.refMap = {};
ctx.tree.keyMap = {};
},
treeInit: function(ctx) {
this.$container.addClass("fancytree-ext-clones");
_assert(ctx.options.defaultKey == null);
// Generate unique / reproducible default keys
ctx.options.defaultKey = function(node) {
return calcUniqueKey(node);
};
// The default implementation loads initial data
this._superApply(arguments);
},
treeClear: function(ctx) {
ctx.tree.refMap = {};
ctx.tree.keyMap = {};
return this._superApply(arguments);
},
treeRegisterNode: function(ctx, add, node) {
var refList,
len,
tree = ctx.tree,
keyMap = tree.keyMap,
refMap = tree.refMap,
key = node.key,
refKey = node && node.refKey != null ? "" + node.refKey : null;
// ctx.tree.debug("clones.treeRegisterNode", add, node);
if (node.isStatusNode()) {
return this._super(ctx, add, node);
}
if (add) {
if (keyMap[node.key] != null) {
var other = keyMap[node.key],
msg =
"clones.treeRegisterNode: duplicate key '" +
node.key +
"': /" +
node.getPath(true) +
" => " +
other.getPath(true);
// Sometimes this exception is not visible in the console,
// so we also write it:
tree.error(msg);
$.error(msg);
}
keyMap[key] = node;
if (refKey) {
refList = refMap[refKey];
if (refList) {
refList.push(key);
if (
refList.length === 2 &&
ctx.options.clones.highlightClones
) {
// Mark peer node, if it just became a clone (no need to
// mark current node, since it will be rendered later anyway)
keyMap[refList[0]].renderStatus();
}
} else {
refMap[refKey] = [key];
}
// node.debug("clones.treeRegisterNode: add clone =>", refMap[refKey]);
}
} else {
if (keyMap[key] == null) {
$.error(
"clones.treeRegisterNode: node.key not registered: " +
node.key
);
}
delete keyMap[key];
if (refKey) {
refList = refMap[refKey];
// node.debug("clones.treeRegisterNode: remove clone BEFORE =>", refMap[refKey]);
if (refList) {
len = refList.length;
if (len <= 1) {
_assert(len === 1);
_assert(refList[0] === key);
delete refMap[refKey];
} else {
_removeArrayMember(refList, key);
// Unmark peer node, if this was the only clone
if (
len === 2 &&
ctx.options.clones.highlightClones
) {
// node.debug("clones.treeRegisterNode: last =>", node.getCloneList());
keyMap[refList[0]].renderStatus();
}
}
// node.debug("clones.treeRegisterNode: remove clone =>", refMap[refKey]);
}
}
}
return this._super(ctx, add, node);
},
nodeRenderStatus: function(ctx) {
var $span,
res,
node = ctx.node;
res = this._super(ctx);
if (ctx.options.clones.highlightClones) {
$span = $(node[ctx.tree.statusClassPropName]);
// Only if span already exists
if ($span.length && node.isClone()) {
// node.debug("clones.nodeRenderStatus: ", ctx.options.clones.highlightClones);
$span.addClass("fancytree-clone");
}
}
return res;
},
nodeSetActive: function(ctx, flag, callOpts) {
var res,
scpn = ctx.tree.statusClassPropName,
node = ctx.node;
res = this._superApply(arguments);
if (ctx.options.clones.highlightActiveClones && node.isClone()) {
$.each(node.getCloneList(true), function(idx, n) {
// n.debug("clones.nodeSetActive: ", flag !== false);
$(n[scpn]).toggleClass(
"fancytree-active-clone",
flag !== false
);
});
}
return res;
},
});
// Value returned by `require('jquery.fancytree..')`
return $.ui.fancytree;
}); // End of closure
/*!
* jquery.fancytree.dnd.js
*
* Drag-and-drop support (jQuery UI draggable/droppable).
* (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
*
* Copyright (c) 2008-2020, Martin Wendt (https://wwWendt.de)
*
* Released under the MIT license
* https://github.com/mar10/fancytree/wiki/LicenseInfo
*
* @version 2.37.0
* @date 2020-09-11T18:58:08Z
*/
(function(factory) {
if (typeof define === "function" && define.amd) {
// AMD. Register as an anonymous module.
define([
"jquery",
"jquery-ui/ui/widgets/draggable",
"jquery-ui/ui/widgets/droppable",
"./jquery.fancytree",
], factory);
} else if (typeof module === "object" && module.exports) {
// Node/CommonJS
require("./jquery.fancytree");
module.exports = factory(require("jquery"));
} else {
// Browser globals
factory(jQuery);
}
})(function($) {
"use strict";
/******************************************************************************
* Private functions and variables
*/
var didRegisterDnd = false,
classDropAccept = "fancytree-drop-accept",
classDropAfter = "fancytree-drop-after",
classDropBefore = "fancytree-drop-before",
classDropOver = "fancytree-drop-over",
classDropReject = "fancytree-drop-reject",
classDropTarget = "fancytree-drop-target";
/* Convert number to string and prepend +/-; return empty string for 0.*/
function offsetString(n) {
// eslint-disable-next-line no-nested-ternary
return n === 0 ? "" : n > 0 ? "+" + n : "" + n;
}
//--- Extend ui.draggable event handling --------------------------------------
function _registerDnd() {
if (didRegisterDnd) {
return;
}
// Register proxy-functions for draggable.start/drag/stop
$.ui.plugin.add("draggable", "connectToFancytree", {
start: function(event, ui) {
// 'draggable' was renamed to 'ui-draggable' since jQueryUI 1.10
var draggable =
$(this).data("ui-draggable") ||
$(this).data("draggable"),
sourceNode = ui.helper.data("ftSourceNode") || null;
if (sourceNode) {
// Adjust helper offset, so cursor is slightly outside top/left corner
draggable.offset.click.top = -2;
draggable.offset.click.left = +16;
// Trigger dragStart event
// TODO: when called as connectTo..., the return value is ignored(?)
return sourceNode.tree.ext.dnd._onDragEvent(
"start",
sourceNode,
null,
event,
ui,
draggable
);
}
},
drag: function(event, ui) {
var ctx,
isHelper,
logObject,
// 'draggable' was renamed to 'ui-draggable' since jQueryUI 1.10
draggable =
$(this).data("ui-draggable") ||
$(this).data("draggable"),
sourceNode = ui.helper.data("ftSourceNode") || null,
prevTargetNode = ui.helper.data("ftTargetNode") || null,
targetNode = $.ui.fancytree.getNode(event.target),
dndOpts = sourceNode && sourceNode.tree.options.dnd;
// logObject = sourceNode || prevTargetNode || $.ui.fancytree;
// logObject.debug("Drag event:", event, event.shiftKey);
if (event.target && !targetNode) {
// We got a drag event, but the targetNode could not be found
// at the event location. This may happen,
// 1. if the mouse jumped over the drag helper,
// 2. or if a non-fancytree element is dragged
// We ignore it:
isHelper =
$(event.target).closest(
"div.fancytree-drag-helper,#fancytree-drop-marker"
).length > 0;
if (isHelper) {
logObject =
sourceNode || prevTargetNode || $.ui.fancytree;
logObject.debug("Drag event over helper: ignored.");
return;
}
}
ui.helper.data("ftTargetNode", targetNode);
if (dndOpts && dndOpts.updateHelper) {
ctx = sourceNode.tree._makeHookContext(sourceNode, event, {
otherNode: targetNode,
ui: ui,
draggable: draggable,
dropMarker: $("#fancytree-drop-marker"),
});
dndOpts.updateHelper.call(sourceNode.tree, sourceNode, ctx);
}
// Leaving a tree node
if (prevTargetNode && prevTargetNode !== targetNode) {
prevTargetNode.tree.ext.dnd._onDragEvent(
"leave",
prevTargetNode,
sourceNode,
event,
ui,
draggable
);
}
if (targetNode) {
if (!targetNode.tree.options.dnd.dragDrop) {
// not enabled as drop target
} else if (targetNode === prevTargetNode) {
// Moving over same node
targetNode.tree.ext.dnd._onDragEvent(
"over",
targetNode,
sourceNode,
event,
ui,
draggable
);
} else {
// Entering this node first time
targetNode.tree.ext.dnd._onDragEvent(
"enter",
targetNode,
sourceNode,
event,
ui,
draggable
);
targetNode.tree.ext.dnd._onDragEvent(
"over",
targetNode,
sourceNode,
event,
ui,
draggable
);
}
}
// else go ahead with standard event handling
},
stop: function(event, ui) {
var logObject,
// 'draggable' was renamed to 'ui-draggable' since jQueryUI 1.10:
draggable =
$(this).data("ui-draggable") ||
$(this).data("draggable"),
sourceNode = ui.helper.data("ftSourceNode") || null,
targetNode = ui.helper.data("ftTargetNode") || null,
dropped = event.type === "mouseup" && event.which === 1;
if (!dropped) {
logObject = sourceNode || targetNode || $.ui.fancytree;
logObject.debug("Drag was cancelled");
}
if (targetNode) {
if (dropped) {
targetNode.tree.ext.dnd._onDragEvent(
"drop",
targetNode,
sourceNode,
event,
ui,
draggable
);
}
targetNode.tree.ext.dnd._onDragEvent(
"leave",
targetNode,
sourceNode,
event,
ui,
draggable
);
}
if (sourceNode) {
sourceNode.tree.ext.dnd._onDragEvent(
"stop",
sourceNode,
null,
event,
ui,
draggable
);
}
},
});
didRegisterDnd = true;
}
/******************************************************************************
* Drag and drop support
*/
function _initDragAndDrop(tree) {
var dnd = tree.options.dnd || null,
glyph = tree.options.glyph || null;
// Register 'connectToFancytree' option with ui.draggable
if (dnd) {
_registerDnd();
}
// Attach ui.draggable to this Fancytree instance
if (dnd && dnd.dragStart) {
tree.widget.element.draggable(
$.extend(
{
addClasses: false,
// DT issue 244: helper should be child of scrollParent:
appendTo: tree.$container,
// appendTo: "body",
containment: false,
// containment: "parent",
delay: 0,
distance: 4,
revert: false,
scroll: true, // to disable, also set css 'position: inherit' on ul.fancytree-container
scrollSpeed: 7,
scrollSensitivity: 10,
// Delegate draggable.start, drag, and stop events to our handler
connectToFancytree: true,
// Let source tree create the helper element
helper: function(event) {
var $helper,
$nodeTag,
opts,
sourceNode = $.ui.fancytree.getNode(
event.target
);
if (!sourceNode) {
// #405, DT issue 211: might happen, if dragging a table *header*
return "<div>ERROR?: helper requested but sourceNode not found</div>";
}
opts = sourceNode.tree.options.dnd;
$nodeTag = $(sourceNode.span);
// Only event and node argument is available
$helper = $(
"<div class='fancytree-drag-helper'><span class='fancytree-drag-helper-img' /></div>"
)
.css({ zIndex: 3, position: "relative" }) // so it appears above ext-wide selection bar
.append(
$nodeTag
.find("span.fancytree-title")
.clone()
);
// Attach node reference to helper object
$helper.data("ftSourceNode", sourceNode);
// Support glyph symbols instead of icons
if (glyph) {
$helper
.find(".fancytree-drag-helper-img")
.addClass(
glyph.map._addClass +
" " +
glyph.map.dragHelper
);
}
// Allow to modify the helper, e.g. to add multi-node-drag feedback
if (opts.initHelper) {
opts.initHelper.call(
sourceNode.tree,
sourceNode,
{
node: sourceNode,
tree: sourceNode.tree,
originalEvent: event,
ui: { helper: $helper },
}
);
}
// We return an unconnected element, so `draggable` will add this
// to the parent specified as `appendTo` option
return $helper;
},
start: function(event, ui) {
var sourceNode = ui.helper.data("ftSourceNode");
return !!sourceNode; // Abort dragging if no node could be found
},
},
tree.options.dnd.draggable
)
);
}
// Attach ui.droppable to this Fancytree instance
if (dnd && dnd.dragDrop) {
tree.widget.element.droppable(
$.extend(
{
addClasses: false,
tolerance: "intersect",
greedy: false,
/*
activate: function(event, ui) {
tree.debug("droppable - activate", event, ui, this);
},
create: function(event, ui) {
tree.debug("droppable - create", event, ui);
},
deactivate: function(event, ui) {
tree.debug("droppable - deactivate", event, ui);
},
drop: function(event, ui) {
tree.debug("droppable - drop", event, ui);
},
out: function(event, ui) {
tree.debug("droppable - out", event, ui);
},
over: function(event, ui) {
tree.debug("droppable - over", event, ui);
}
*/
},
tree.options.dnd.droppable
)
);
}
}
/******************************************************************************
*
*/
$.ui.fancytree.registerExtension({
name: "dnd",
version: "2.37.0",
// Default options for this extension.
options: {
// Make tree nodes accept draggables
autoExpandMS: 1000, // Expand nodes after n milliseconds of hovering.
draggable: null, // Additional options passed to jQuery draggable
droppable: null, // Additional options passed to jQuery droppable
focusOnClick: false, // Focus, although draggable cancels mousedown event (#270)
preventVoidMoves: true, // Prevent dropping nodes 'before self', etc.
preventRecursiveMoves: true, // Prevent dropping nodes on own descendants
smartRevert: true, // set draggable.revert = true if drop was rejected
dropMarkerOffsetX: -24, // absolute position offset for .fancytree-drop-marker relatively to ..fancytree-title (icon/img near a node accepting drop)
dropMarkerInsertOffsetX: -16, // additional offset for drop-marker with hitMode = "before"/"after"
// Events (drag support)
dragStart: null, // Callback(sourceNode, data), return true, to enable dnd
dragStop: null, // Callback(sourceNode, data)
initHelper: null, // Callback(sourceNode, data)
updateHelper: null, // Callback(sourceNode, data)
// Events (drop support)
dragEnter: null, // Callback(targetNode, data)
dragOver: null, // Callback(targetNode, data)
dragExpand: null, // Callback(targetNode, data), return false to prevent autoExpand
dragDrop: null, // Callback(targetNode, data)
dragLeave: null, // Callback(targetNode, data)
},
treeInit: function(ctx) {
var tree = ctx.tree;
this._superApply(arguments);
// issue #270: draggable eats mousedown events
if (tree.options.dnd.dragStart) {
tree.$container.on("mousedown", function(event) {
// if( !tree.hasFocus() && ctx.options.dnd.focusOnClick ) {
if (ctx.options.dnd.focusOnClick) {
// #270
var node = $.ui.fancytree.getNode(event);
if (node) {
node.debug(
"Re-enable focus that was prevented by jQuery UI draggable."
);
// node.setFocus();
// $(node.span).closest(":tabbable").focus();
// $(event.target).trigger("focus");
// $(event.target).closest(":tabbable").trigger("focus");
}
setTimeout(function() {
// #300
$(event.target)
.closest(":tabbable")
.focus();
}, 10);
}
});
}
_initDragAndDrop(tree);
},
/* Display drop marker according to hitMode ('after', 'before', 'over'). */
_setDndStatus: function(
sourceNode,
targetNode,
helper,
hitMode,
accept
) {
var markerOffsetX,
pos,
markerAt = "center",
instData = this._local,
dndOpt = this.options.dnd,
glyphOpt = this.options.glyph,
$source = sourceNode ? $(sourceNode.span) : null,
$target = $(targetNode.span),
$targetTitle = $target.find("span.fancytree-title");
if (!instData.$dropMarker) {
instData.$dropMarker = $(
"<div id='fancytree-drop-marker'></div>"
)
.hide()
.css({ "z-index": 1000 })
.prependTo($(this.$div).parent());
// .prependTo("body");
if (glyphOpt) {
instData.$dropMarker.addClass(
glyphOpt.map._addClass + " " + glyphOpt.map.dropMarker
);
}
}
if (
hitMode === "after" ||
hitMode === "before" ||
hitMode === "over"
) {
markerOffsetX = dndOpt.dropMarkerOffsetX || 0;
switch (hitMode) {
case "before":
markerAt = "top";
markerOffsetX += dndOpt.dropMarkerInsertOffsetX || 0;
break;
case "after":
markerAt = "bottom";
markerOffsetX += dndOpt.dropMarkerInsertOffsetX || 0;
break;
}
pos = {
my: "left" + offsetString(markerOffsetX) + " center",
at: "left " + markerAt,
of: $targetTitle,
};
if (this.options.rtl) {
pos.my = "right" + offsetString(-markerOffsetX) + " center";
pos.at = "right " + markerAt;
}
instData.$dropMarker
.toggleClass(classDropAfter, hitMode === "after")
.toggleClass(classDropOver, hitMode === "over")
.toggleClass(classDropBefore, hitMode === "before")
.toggleClass("fancytree-rtl", !!this.options.rtl)
.show()
.position($.ui.fancytree.fixPositionOptions(pos));
} else {
instData.$dropMarker.hide();
}
if ($source) {
$source
.toggleClass(classDropAccept, accept === true)
.toggleClass(classDropReject, accept === false);
}
$target
.toggleClass(
classDropTarget,
hitMode === "after" ||
hitMode === "before" ||
hitMode === "over"
)
.toggleClass(classDropAfter, hitMode === "after")
.toggleClass(classDropBefore, hitMode === "before")
.toggleClass(classDropAccept, accept === true)
.toggleClass(classDropReject, accept === false);
helper
.toggleClass(classDropAccept, accept === true)
.toggleClass(classDropReject, accept === false);
},
/*
* Handles drag'n'drop functionality.
*
* A standard jQuery drag-and-drop process may generate these calls:
*
* start:
* _onDragEvent("start", sourceNode, null, event, ui, draggable);
* drag:
* _onDragEvent("leave", prevTargetNode, sourceNode, event, ui, draggable);
* _onDragEvent("over", targetNode, sourceNode, event, ui, draggable);
* _onDragEvent("enter", targetNode, sourceNode, event, ui, draggable);
* stop:
* _onDragEvent("drop", targetNode, sourceNode, event, ui, draggable);
* _onDragEvent("leave", targetNode, sourceNode, event, ui, draggable);
* _onDragEvent("stop", sourceNode, null, event, ui, draggable);
*/
_onDragEvent: function(
eventName,
node,
otherNode,
event,
ui,
draggable
) {
// if(eventName !== "over"){
// this.debug("tree.ext.dnd._onDragEvent(%s, %o, %o) - %o", eventName, node, otherNode, this);
// }
var accept,
nodeOfs,
parentRect,
rect,
relPos,
relPos2,
enterResponse,
hitMode,
r,
opts = this.options,
dnd = opts.dnd,
ctx = this._makeHookContext(node, event, {
otherNode: otherNode,
ui: ui,
draggable: draggable,
}),
res = null,
self = this,
$nodeTag = $(node.span);
if (dnd.smartRevert) {
draggable.options.revert = "invalid";
}
switch (eventName) {
case "start":
if (node.isStatusNode()) {
res = false;
} else if (dnd.dragStart) {
res = dnd.dragStart(node, ctx);
}
if (res === false) {
this.debug("tree.dragStart() cancelled");
//draggable._clear();
// NOTE: the return value seems to be ignored (drag is not cancelled, when false is returned)
// TODO: call this._cancelDrag()?
ui.helper.trigger("mouseup").hide();
} else {
if (dnd.smartRevert) {
// #567, #593: fix revert position
// rect = node.li.getBoundingClientRect();
rect = node[
ctx.tree.nodeContainerAttrName
].getBoundingClientRect();
parentRect = $(
draggable.options.appendTo
)[0].getBoundingClientRect();
draggable.originalPosition.left = Math.max(
0,
rect.left - parentRect.left
);
draggable.originalPosition.top = Math.max(
0,
rect.top - parentRect.top
);
}
$nodeTag.addClass("fancytree-drag-source");
// Register global handlers to allow cancel
$(document).on(
"keydown.fancytree-dnd,mousedown.fancytree-dnd",
function(event) {
// node.tree.debug("dnd global event", event.type, event.which);
if (
event.type === "keydown" &&
event.which === $.ui.keyCode.ESCAPE
) {
self.ext.dnd._cancelDrag();
} else if (event.type === "mousedown") {
self.ext.dnd._cancelDrag();
}
}
);
}
break;
case "enter":
if (
dnd.preventRecursiveMoves &&
node.isDescendantOf(otherNode)
) {
r = false;
} else {
r = dnd.dragEnter ? dnd.dragEnter(node, ctx) : null;
}
if (!r) {
// convert null, undefined, false to false
res = false;
} else if ($.isArray(r)) {
// TODO: also accept passing an object of this format directly
res = {
over: $.inArray("over", r) >= 0,
before: $.inArray("before", r) >= 0,
after: $.inArray("after", r) >= 0,
};
} else {
res = {
over: r === true || r === "over",
before: r === true || r === "before",
after: r === true || r === "after",
};
}
ui.helper.data("enterResponse", res);
// this.debug("helper.enterResponse: %o", res);
break;
case "over":
enterResponse = ui.helper.data("enterResponse");
hitMode = null;
if (enterResponse === false) {
// Don't call dragOver if onEnter returned false.
// break;
} else if (typeof enterResponse === "string") {
// Use hitMode from onEnter if provided.
hitMode = enterResponse;
} else {
// Calculate hitMode from relative cursor position.
nodeOfs = $nodeTag.offset();
relPos = {
x: event.pageX - nodeOfs.left,
y: event.pageY - nodeOfs.top,
};
relPos2 = {
x: relPos.x / $nodeTag.width(),
y: relPos.y / $nodeTag.height(),
};
if (enterResponse.after && relPos2.y > 0.75) {
hitMode = "after";
} else if (
!enterResponse.over &&
enterResponse.after &&
relPos2.y > 0.5
) {
hitMode = "after";
} else if (enterResponse.before && relPos2.y <= 0.25) {
hitMode = "before";
} else if (
!enterResponse.over &&
enterResponse.before &&
relPos2.y <= 0.5
) {
hitMode = "before";
} else if (enterResponse.over) {
hitMode = "over";
}
// Prevent no-ops like 'before source node'
// TODO: these are no-ops when moving nodes, but not in copy mode
if (dnd.preventVoidMoves) {
if (node === otherNode) {
this.debug(
" drop over source node prevented"
);
hitMode = null;
} else if (
hitMode === "before" &&
otherNode &&
node === otherNode.getNextSibling()
) {
this.debug(
" drop after source node prevented"
);
hitMode = null;
} else if (
hitMode === "after" &&
otherNode &&
node === otherNode.getPrevSibling()
) {
this.debug(
" drop before source node prevented"
);
hitMode = null;
} else if (
hitMode === "over" &&
otherNode &&
otherNode.parent === node &&
otherNode.isLastSibling()
) {
this.debug(
" drop last child over own parent prevented"
);
hitMode = null;
}
}
// this.debug("hitMode: %s - %s - %s", hitMode, (node.parent === otherNode), node.isLastSibling());
ui.helper.data("hitMode", hitMode);
}
// Auto-expand node (only when 'over' the node, not 'before', or 'after')
if (
hitMode !== "before" &&
hitMode !== "after" &&
dnd.autoExpandMS &&
node.hasChildren() !== false &&
!node.expanded &&
(!dnd.dragExpand || dnd.dragExpand(node, ctx) !== false)
) {
node.scheduleAction("expand", dnd.autoExpandMS);
}
if (hitMode && dnd.dragOver) {
// TODO: http://code.google.com/p/dynatree/source/detail?r=625
ctx.hitMode = hitMode;
res = dnd.dragOver(node, ctx);
}
accept = res !== false && hitMode !== null;
if (dnd.smartRevert) {
draggable.options.revert = !accept;
}
this._local._setDndStatus(
otherNode,
node,
ui.helper,
hitMode,
accept
);
break;
case "drop":
hitMode = ui.helper.data("hitMode");
if (hitMode && dnd.dragDrop) {
ctx.hitMode = hitMode;
dnd.dragDrop(node, ctx);
}
break;
case "leave":
// Cancel pending expand request
node.scheduleAction("cancel");
ui.helper.data("enterResponse", null);
ui.helper.data("hitMode", null);
this._local._setDndStatus(
otherNode,
node,
ui.helper,
"out",
undefined
);
if (dnd.dragLeave) {
dnd.dragLeave(node, ctx);
}
break;
case "stop":
$nodeTag.removeClass("fancytree-drag-source");
$(document).off(".fancytree-dnd");
if (dnd.dragStop) {
dnd.dragStop(node, ctx);
}
break;
default:
$.error("Unsupported drag event: " + eventName);
}
return res;
},
_cancelDrag: function() {
var dd = $.ui.ddmanager.current;
if (dd) {
dd.cancel();
}
},
});
// Value returned by `require('jquery.fancytree..')`
return $.ui.fancytree;
}); // End of closure
/*!
* jquery.fancytree.dnd5.js
*
* Drag-and-drop support (native HTML5).
* (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
*
* Copyright (c) 2008-2020, Martin Wendt (https://wwWendt.de)
*
* Released under the MIT license
* https://github.com/mar10/fancytree/wiki/LicenseInfo
*
* @version 2.37.0
* @date 2020-09-11T18:58:08Z
*/
/*
#TODO
Compatiblity when dragging between *separate* windows:
Drag from Chrome Edge FF IE11 Safari
To Chrome ok ok ok NO ?
Edge ok ok ok NO ?
FF ok ok ok NO ?
IE 11 ok ok ok ok ?
Safari ? ? ? ? ok
*/
(function(factory) {
if (typeof define === "function" && define.amd) {
// AMD. Register as an anonymous module.
define(["jquery", "./jquery.fancytree"], factory);
} else if (typeof module === "object" && module.exports) {
// Node/CommonJS
require("./jquery.fancytree");
module.exports = factory(require("jquery"));
} else {
// Browser globals
factory(jQuery);
}
})(function($) {
"use strict";
/******************************************************************************
* Private functions and variables
*/
var FT = $.ui.fancytree,
isMac = /Mac/.test(navigator.platform),
classDragSource = "fancytree-drag-source",
classDragRemove = "fancytree-drag-remove",
classDropAccept = "fancytree-drop-accept",
classDropAfter = "fancytree-drop-after",
classDropBefore = "fancytree-drop-before",
classDropOver = "fancytree-drop-over",
classDropReject = "fancytree-drop-reject",
classDropTarget = "fancytree-drop-target",
nodeMimeType = "application/x-fancytree-node",
$dropMarker = null,
$dragImage,
$extraHelper,
SOURCE_NODE = null,
SOURCE_NODE_LIST = null,
$sourceList = null,
DRAG_ENTER_RESPONSE = null,
// SESSION_DATA = null, // plain object passed to events as `data`
SUGGESTED_DROP_EFFECT = null,
REQUESTED_DROP_EFFECT = null,
REQUESTED_EFFECT_ALLOWED = null,
LAST_HIT_MODE = null,
DRAG_OVER_STAMP = null; // Time when a node entered the 'over' hitmode
/* */
function _clearGlobals() {
DRAG_ENTER_RESPONSE = null;
DRAG_OVER_STAMP = null;
REQUESTED_DROP_EFFECT = null;
REQUESTED_EFFECT_ALLOWED = null;
SUGGESTED_DROP_EFFECT = null;
SOURCE_NODE = null;
SOURCE_NODE_LIST = null;
if ($sourceList) {
$sourceList.removeClass(classDragSource + " " + classDragRemove);
}
$sourceList = null;
if ($dropMarker) {
$dropMarker.hide();
}
// Take this badge off of me - I can't use it anymore:
if ($extraHelper) {
$extraHelper.remove();
$extraHelper = null;
}
}
/* Convert number to string and prepend +/-; return empty string for 0.*/
function offsetString(n) {
// eslint-disable-next-line no-nested-ternary
return n === 0 ? "" : n > 0 ? "+" + n : "" + n;
}
/* Convert a dragEnter() or dragOver() response to a canonical form.
* Return false or plain object
* @param {string|object|boolean} r
* @return {object|false}
*/
function normalizeDragEnterResponse(r) {
var res;
if (!r) {
return false;
}
if ($.isPlainObject(r)) {
res = {
over: !!r.over,
before: !!r.before,
after: !!r.after,
};
} else if ($.isArray(r)) {
res = {
over: $.inArray("over", r) >= 0,
before: $.inArray("before", r) >= 0,
after: $.inArray("after", r) >= 0,
};
} else {
res = {
over: r === true || r === "over",
before: r === true || r === "before",
after: r === true || r === "after",
};
}
if (Object.keys(res).length === 0) {
return false;
}
// if( Object.keys(res).length === 1 ) {
// res.unique = res[0];
// }
return res;
}
/* Convert a dataTransfer.effectAllowed to a canonical form.
* Return false or plain object
* @param {string|boolean} r
* @return {object|false}
*/
// function normalizeEffectAllowed(r) {
// if (!r || r === "none") {
// return false;
// }
// var all = r === "all",
// res = {
// copy: all || /copy/i.test(r),
// link: all || /link/i.test(r),
// move: all || /move/i.test(r),
// };
// return res;
// }
/* Implement auto scrolling when drag cursor is in top/bottom area of scroll parent. */
function autoScroll(tree, event) {
var spOfs,
scrollTop,
delta,
dndOpts = tree.options.dnd5,
sp = tree.$scrollParent[0],
sensitivity = dndOpts.scrollSensitivity,
speed = dndOpts.scrollSpeed,
scrolled = 0;
if (sp !== document && sp.tagName !== "HTML") {
spOfs = tree.$scrollParent.offset();
scrollTop = sp.scrollTop;
if (spOfs.top + sp.offsetHeight - event.pageY < sensitivity) {
delta =
sp.scrollHeight -
tree.$scrollParent.innerHeight() -
scrollTop;
// console.log ("sp.offsetHeight: " + sp.offsetHeight
// + ", spOfs.top: " + spOfs.top
// + ", scrollTop: " + scrollTop
// + ", innerHeight: " + tree.$scrollParent.innerHeight()
// + ", scrollHeight: " + sp.scrollHeight
// + ", delta: " + delta
// );
if (delta > 0) {
sp.scrollTop = scrolled = scrollTop + speed;
}
} else if (scrollTop > 0 && event.pageY - spOfs.top < sensitivity) {
sp.scrollTop = scrolled = scrollTop - speed;
}
} else {
scrollTop = $(document).scrollTop();
if (scrollTop > 0 && event.pageY - scrollTop < sensitivity) {
scrolled = scrollTop - speed;
$(document).scrollTop(scrolled);
} else if (
$(window).height() - (event.pageY - scrollTop) <
sensitivity
) {
scrolled = scrollTop + speed;
$(document).scrollTop(scrolled);
}
}
if (scrolled) {
tree.debug("autoScroll: " + scrolled + "px");
}
return scrolled;
}
/* Guess dropEffect from modifier keys.
* Using rules suggested here:
* https://ux.stackexchange.com/a/83769
* @returns
* 'copy', 'link', 'move', or 'none'
*/
function evalEffectModifiers(tree, event, effectDefault) {
var res = effectDefault;
if (isMac) {
if (event.metaKey && event.altKey) {
// Mac: [Control] + [Option]
res = "link";
} else if (event.ctrlKey) {
// Chrome on Mac: [Control]
res = "link";
} else if (event.metaKey) {
// Mac: [Command]
res = "move";
} else if (event.altKey) {
// Mac: [Option]
res = "copy";
}
} else {
if (event.ctrlKey) {
// Windows: [Ctrl]
res = "copy";
} else if (event.shiftKey) {
// Windows: [Shift]
res = "move";
} else if (event.altKey) {
// Windows: [Alt]
res = "link";
}
}
if (res !== SUGGESTED_DROP_EFFECT) {
tree.info(
"evalEffectModifiers: " +
event.type +
" - evalEffectModifiers(): " +
SUGGESTED_DROP_EFFECT +
" -> " +
res
);
}
SUGGESTED_DROP_EFFECT = res;
// tree.debug("evalEffectModifiers: " + res);
return res;
}
/*
* Check if the previous callback (dragEnter, dragOver, ...) has changed
* the `data` object and apply those settings.
*
* Safari:
* It seems that `dataTransfer.dropEffect` can only be set on dragStart, and will remain
* even if the cursor changes when [Alt] or [Ctrl] are pressed (?)
* Using rules suggested here:
* https://ux.stackexchange.com/a/83769
* @returns
* 'copy', 'link', 'move', or 'none'
*/
function prepareDropEffectCallback(event, data) {
var tree = data.tree,
dataTransfer = data.dataTransfer;
if (event.type === "dragstart") {
data.effectAllowed = tree.options.dnd5.effectAllowed;
data.dropEffect = tree.options.dnd5.dropEffectDefault;
} else {
data.effectAllowed = REQUESTED_EFFECT_ALLOWED;
data.dropEffect = REQUESTED_DROP_EFFECT;
}
data.dropEffectSuggested = evalEffectModifiers(
tree,
event,
tree.options.dnd5.dropEffectDefault
);
data.isMove = data.dropEffect === "move";
data.files = dataTransfer.files || [];
// if (REQUESTED_EFFECT_ALLOWED !== dataTransfer.effectAllowed) {
// tree.warn(
// "prepareDropEffectCallback(" +
// event.type +
// "): dataTransfer.effectAllowed changed from " +
// REQUESTED_EFFECT_ALLOWED +
// " -> " +
// dataTransfer.effectAllowed
// );
// }
// if (REQUESTED_DROP_EFFECT !== dataTransfer.dropEffect) {
// tree.warn(
// "prepareDropEffectCallback(" +
// event.type +
// "): dataTransfer.dropEffect changed from requested " +
// REQUESTED_DROP_EFFECT +
// " to " +
// dataTransfer.dropEffect
// );
// }
}
function applyDropEffectCallback(event, data, allowDrop) {
var tree = data.tree,
dataTransfer = data.dataTransfer;
if (
event.type !== "dragstart" &&
REQUESTED_EFFECT_ALLOWED !== data.effectAllowed
) {
tree.warn(
"effectAllowed should only be changed in dragstart event: " +
event.type +
": data.effectAllowed changed from " +
REQUESTED_EFFECT_ALLOWED +
" -> " +
data.effectAllowed
);
}
if (allowDrop === false) {
tree.info("applyDropEffectCallback: allowDrop === false");
data.effectAllowed = "none";
data.dropEffect = "none";
}
// if (REQUESTED_DROP_EFFECT !== data.dropEffect) {
// tree.debug(
// "applyDropEffectCallback(" +
// event.type +
// "): data.dropEffect changed from previous " +
// REQUESTED_DROP_EFFECT +
// " to " +
// data.dropEffect
// );
// }
data.isMove = data.dropEffect === "move";
// data.isMove = data.dropEffectSuggested === "move";
// `effectAllowed` must only be defined in dragstart event, so we
// store it in a global variable for reference
if (event.type === "dragstart") {
REQUESTED_EFFECT_ALLOWED = data.effectAllowed;
REQUESTED_DROP_EFFECT = data.dropEffect;
}
// if (REQUESTED_DROP_EFFECT !== dataTransfer.dropEffect) {
// data.tree.info(
// "applyDropEffectCallback(" +
// event.type +
// "): dataTransfer.dropEffect changed from " +
// REQUESTED_DROP_EFFECT +
// " -> " +
// dataTransfer.dropEffect
// );
// }
dataTransfer.effectAllowed = REQUESTED_EFFECT_ALLOWED;
dataTransfer.dropEffect = REQUESTED_DROP_EFFECT;
// tree.debug(
// "applyDropEffectCallback(" +
// event.type +
// "): set " +
// dataTransfer.dropEffect +
// "/" +
// dataTransfer.effectAllowed
// );
// if (REQUESTED_DROP_EFFECT !== dataTransfer.dropEffect) {
// data.tree.warn(
// "applyDropEffectCallback(" +
// event.type +
// "): could not set dataTransfer.dropEffect to " +
// REQUESTED_DROP_EFFECT +
// ": got " +
// dataTransfer.dropEffect
// );
// }
return REQUESTED_DROP_EFFECT;
}
/* Handle dragover event (fired every x ms) on valid drop targets.
*
* - Auto-scroll when cursor is in border regions
* - Apply restrictioan like 'preventVoidMoves'
* - Calculate hit mode
* - Calculate drop effect
* - Trigger dragOver() callback to let user modify hit mode and drop effect
* - Adjust the drop marker accordingly
*
* @returns hitMode
*/
function handleDragOver(event, data) {
// Implement auto-scrolling
if (data.options.dnd5.scroll) {
autoScroll(data.tree, event);
}
// Bail out with previous response if we get an invalid dragover
if (!data.node) {
data.tree.warn("Ignored dragover for non-node"); //, event, data);
return LAST_HIT_MODE;
}
var markerOffsetX,
nodeOfs,
pos,
relPosY,
hitMode = null,
tree = data.tree,
options = tree.options,
dndOpts = options.dnd5,
targetNode = data.node,
sourceNode = data.otherNode,
markerAt = "center",
$target = $(targetNode.span),
$targetTitle = $target.find("span.fancytree-title");
if (DRAG_ENTER_RESPONSE === false) {
tree.debug("Ignored dragover, since dragenter returned false.");
return false;
} else if (typeof DRAG_ENTER_RESPONSE === "string") {
$.error("assert failed: dragenter returned string");
}
// Calculate hitMode from relative cursor position.
nodeOfs = $target.offset();
relPosY = (event.pageY - nodeOfs.top) / $target.height();
if (event.pageY === undefined) {
tree.warn("event.pageY is undefined: see issue #1013.");
}
if (DRAG_ENTER_RESPONSE.after && relPosY > 0.75) {
hitMode = "after";
} else if (
!DRAG_ENTER_RESPONSE.over &&
DRAG_ENTER_RESPONSE.after &&
relPosY > 0.5
) {
hitMode = "after";
} else if (DRAG_ENTER_RESPONSE.before && relPosY <= 0.25) {
hitMode = "before";
} else if (
!DRAG_ENTER_RESPONSE.over &&
DRAG_ENTER_RESPONSE.before &&
relPosY <= 0.5
) {
hitMode = "before";
} else if (DRAG_ENTER_RESPONSE.over) {
hitMode = "over";
}
// Prevent no-ops like 'before source node'
// TODO: these are no-ops when moving nodes, but not in copy mode
if (dndOpts.preventVoidMoves && data.dropEffect === "move") {
if (targetNode === sourceNode) {
targetNode.debug("Drop over source node prevented.");
hitMode = null;
} else if (
hitMode === "before" &&
sourceNode &&
targetNode === sourceNode.getNextSibling()
) {
targetNode.debug("Drop after source node prevented.");
hitMode = null;
} else if (
hitMode === "after" &&
sourceNode &&
targetNode === sourceNode.getPrevSibling()
) {
targetNode.debug("Drop before source node prevented.");
hitMode = null;
} else if (
hitMode === "over" &&
sourceNode &&
sourceNode.parent === targetNode &&
sourceNode.isLastSibling()
) {
targetNode.debug("Drop last child over own parent prevented.");
hitMode = null;
}
}
// Let callback modify the calculated hitMode
data.hitMode = hitMode;
if (hitMode && dndOpts.dragOver) {
prepareDropEffectCallback(event, data);
dndOpts.dragOver(targetNode, data);
var allowDrop = !!hitMode;
applyDropEffectCallback(event, data, allowDrop);
hitMode = data.hitMode;
}
LAST_HIT_MODE = hitMode;
//
if (hitMode === "after" || hitMode === "before" || hitMode === "over") {
markerOffsetX = dndOpts.dropMarkerOffsetX || 0;
switch (hitMode) {
case "before":
markerAt = "top";
markerOffsetX += dndOpts.dropMarkerInsertOffsetX || 0;
break;
case "after":
markerAt = "bottom";
markerOffsetX += dndOpts.dropMarkerInsertOffsetX || 0;
break;
}
pos = {
my: "left" + offsetString(markerOffsetX) + " center",
at: "left " + markerAt,
of: $targetTitle,
};
if (options.rtl) {
pos.my = "right" + offsetString(-markerOffsetX) + " center";
pos.at = "right " + markerAt;
// console.log("rtl", pos);
}
$dropMarker
.toggleClass(classDropAfter, hitMode === "after")
.toggleClass(classDropOver, hitMode === "over")
.toggleClass(classDropBefore, hitMode === "before")
.show()
.position(FT.fixPositionOptions(pos));
} else {
$dropMarker.hide();
// console.log("hide dropmarker")
}
$(targetNode.span)
.toggleClass(
classDropTarget,
hitMode === "after" ||
hitMode === "before" ||
hitMode === "over"
)
.toggleClass(classDropAfter, hitMode === "after")
.toggleClass(classDropBefore, hitMode === "before")
.toggleClass(classDropAccept, hitMode === "over")
.toggleClass(classDropReject, hitMode === false);
return hitMode;
}
/*
* Handle dragstart drag dragend events on the container
*/
function onDragEvent(event) {
var json,
tree = this,
dndOpts = tree.options.dnd5,
node = FT.getNode(event),
dataTransfer =
event.dataTransfer || event.originalEvent.dataTransfer,
data = {
tree: tree,
node: node,
options: tree.options,
originalEvent: event.originalEvent,
widget: tree.widget,
dataTransfer: dataTransfer,
useDefaultImage: true,
dropEffect: undefined,
dropEffectSuggested: undefined,
effectAllowed: undefined, // set by dragstart
files: undefined, // only for drop events
isCancelled: undefined, // set by dragend
isMove: undefined,
};
switch (event.type) {
case "dragstart":
if (!node) {
tree.info("Ignored dragstart on a non-node.");
return false;
}
// Store current source node in different formats
SOURCE_NODE = node;
// Also optionally store selected nodes
if (dndOpts.multiSource === false) {
SOURCE_NODE_LIST = [node];
} else if (dndOpts.multiSource === true) {
if (node.isSelected()) {
SOURCE_NODE_LIST = tree.getSelectedNodes();
} else {
SOURCE_NODE_LIST = [node];
}
} else {
SOURCE_NODE_LIST = dndOpts.multiSource(node, data);
}
// Cache as array of jQuery objects for faster access:
$sourceList = $(
$.map(SOURCE_NODE_LIST, function(n) {
return n.span;
})
);
// Set visual feedback
$sourceList.addClass(classDragSource);
// Set payload
// Note:
// Transfer data is only accessible on dragstart and drop!
// For all other events the formats and kinds in the drag
// data store list of items representing dragged data can be
// enumerated, but the data itself is unavailable and no new
// data can be added.
var nodeData = node.toDict();
nodeData.treeId = node.tree._id;
json = JSON.stringify(nodeData);
try {
dataTransfer.setData(nodeMimeType, json);
dataTransfer.setData("text/html", $(node.span).html());
dataTransfer.setData("text/plain", node.title);
} catch (ex) {
// IE only accepts 'text' type
tree.warn(
"Could not set data (IE only accepts 'text') - " + ex
);
}
// We always need to set the 'text' type if we want to drag
// Because IE 11 only accepts this single type.
// If we pass JSON here, IE can can access all node properties,
// even when the source lives in another window. (D'n'd inside
// the same window will always work.)
// The drawback is, that in this case ALL browsers will see
// the JSON representation as 'text', so dragging
// to a text field will insert the JSON string instead of
// the node title.
if (dndOpts.setTextTypeJson) {
dataTransfer.setData("text", json);
} else {
dataTransfer.setData("text", node.title);
}
// Set the allowed drag modes (combinations of move, copy, and link)
// (effectAllowed can only be set in the dragstart event.)
// This can be overridden in the dragStart() callback
prepareDropEffectCallback(event, data);
// Let user cancel or modify above settings
// Realize potential changes by previous callback
if (dndOpts.dragStart(node, data) === false) {
// Cancel dragging
// dataTransfer.dropEffect = "none";
_clearGlobals();
return false;
}
applyDropEffectCallback(event, data);
// Unless user set `data.useDefaultImage` to false in dragStart,
// generata a default drag image now:
$extraHelper = null;
if (data.useDefaultImage) {
// Set the title as drag image (otherwise it would contain the expander)
$dragImage = $(node.span).find(".fancytree-title");
if (SOURCE_NODE_LIST && SOURCE_NODE_LIST.length > 1) {
// Add a counter badge to node title if dragging more than one node.
// We want this, because the element that is used as drag image
// must be *visible* in the DOM, so we cannot create some hidden
// custom markup.
// See https://kryogenix.org/code/browser/custom-drag-image.html
// Also, since IE 11 and Edge don't support setDragImage() alltogether,
// it gives som feedback to the user.
// The badge will be removed later on drag end.
$extraHelper = $(
"<span class='fancytree-childcounter'/>"
)
.text("+" + (SOURCE_NODE_LIST.length - 1))
.appendTo($dragImage);
}
if (dataTransfer.setDragImage) {
// IE 11 and Edge do not support this
dataTransfer.setDragImage($dragImage[0], -10, -10);
}
}
return true;
case "drag":
// Called every few milliseconds (no matter if the
// cursor is over a valid drop target)
// data.tree.info("drag", SOURCE_NODE)
prepareDropEffectCallback(event, data);
dndOpts.dragDrag(node, data);
applyDropEffectCallback(event, data);
$sourceList.toggleClass(classDragRemove, data.isMove);
break;
case "dragend":
// Called at the end of a d'n'd process (after drop)
// Note caveat: If drop removed the dragged source element,
// we may not get this event, since the target does not exist
// anymore
prepareDropEffectCallback(event, data);
_clearGlobals();
data.isCancelled = !LAST_HIT_MODE;
dndOpts.dragEnd(node, data, !LAST_HIT_MODE);
// applyDropEffectCallback(event, data);
break;
}
}
/*
* Handle dragenter dragover dragleave drop events on the container
*/
function onDropEvent(event) {
var json,
allowAutoExpand,
nodeData,
isSourceFtNode,
r,
res,
tree = this,
dndOpts = tree.options.dnd5,
allowDrop = null,
node = FT.getNode(event),
dataTransfer =
event.dataTransfer || event.originalEvent.dataTransfer,
data = {
tree: tree,
node: node,
options: tree.options,
originalEvent: event.originalEvent,
widget: tree.widget,
hitMode: DRAG_ENTER_RESPONSE,
dataTransfer: dataTransfer,
otherNode: SOURCE_NODE || null,
otherNodeList: SOURCE_NODE_LIST || null,
otherNodeData: null, // set by drop event
useDefaultImage: true,
dropEffect: undefined,
dropEffectSuggested: undefined,
effectAllowed: undefined, // set by dragstart
files: null, // list of File objects (may be [])
isCancelled: undefined, // set by drop event
isMove: undefined,
};
// data.isMove = dropEffect === "move";
switch (event.type) {
case "dragenter":
// The dragenter event is fired when a dragged element or
// text selection enters a valid drop target.
DRAG_OVER_STAMP = null;
if (!node) {
// Sometimes we get dragenter for the container element
tree.debug(
"Ignore non-node " +
event.type +
": " +
event.target.tagName +
"." +
event.target.className
);
DRAG_ENTER_RESPONSE = false;
break;
}
$(node.span)
.addClass(classDropOver)
.removeClass(classDropAccept + " " + classDropReject);
// Data is only readable in the dragstart and drop event,
// but we can check for the type:
isSourceFtNode =
$.inArray(nodeMimeType, dataTransfer.types) >= 0;
if (dndOpts.preventNonNodes && !isSourceFtNode) {
node.debug("Reject dropping a non-node.");
DRAG_ENTER_RESPONSE = false;
break;
} else if (
dndOpts.preventForeignNodes &&
(!SOURCE_NODE || SOURCE_NODE.tree !== node.tree)
) {
node.debug("Reject dropping a foreign node.");
DRAG_ENTER_RESPONSE = false;
break;
} else if (
dndOpts.preventSameParent &&
data.otherNode &&
data.otherNode.tree === node.tree &&
node.parent === data.otherNode.parent
) {
node.debug("Reject dropping as sibling (same parent).");
DRAG_ENTER_RESPONSE = false;
break;
} else if (
dndOpts.preventRecursion &&
data.otherNode &&
data.otherNode.tree === node.tree &&
node.isDescendantOf(data.otherNode)
) {
node.debug("Reject dropping below own ancestor.");
DRAG_ENTER_RESPONSE = false;
break;
} else if (dndOpts.preventLazyParents && !node.isLoaded()) {
node.warn("Drop over unloaded target node prevented.");
DRAG_ENTER_RESPONSE = false;
break;
}
$dropMarker.show();
// Call dragEnter() to figure out if (and where) dropping is allowed
prepareDropEffectCallback(event, data);
r = dndOpts.dragEnter(node, data);
res = normalizeDragEnterResponse(r);
// alert("res:" + JSON.stringify(res))
DRAG_ENTER_RESPONSE = res;
allowDrop = res && (res.over || res.before || res.after);
applyDropEffectCallback(event, data, allowDrop);
break;
case "dragover":
if (!node) {
tree.debug(
"Ignore non-node " +
event.type +
": " +
event.target.tagName +
"." +
event.target.className
);
break;
}
// The dragover event is fired when an element or text
// selection is being dragged over a valid drop target
// (every few hundred milliseconds).
// tree.debug(
// event.type +
// ": dropEffect: " +
// dataTransfer.dropEffect
// );
prepareDropEffectCallback(event, data);
LAST_HIT_MODE = handleDragOver(event, data);
// The flag controls the preventDefault() below:
allowDrop = !!LAST_HIT_MODE;
allowAutoExpand =
LAST_HIT_MODE === "over" || LAST_HIT_MODE === false;
if (
allowAutoExpand &&
!node.expanded &&
node.hasChildren() !== false
) {
if (!DRAG_OVER_STAMP) {
DRAG_OVER_STAMP = Date.now();
} else if (
dndOpts.autoExpandMS &&
Date.now() - DRAG_OVER_STAMP > dndOpts.autoExpandMS &&
!node.isLoading() &&
(!dndOpts.dragExpand ||
dndOpts.dragExpand(node, data) !== false)
) {
node.setExpanded();
}
} else {
DRAG_OVER_STAMP = null;
}
break;
case "dragleave":
// NOTE: dragleave is fired AFTER the dragenter event of the
// FOLLOWING element.
if (!node) {
tree.debug(
"Ignore non-node " +
event.type +
": " +
event.target.tagName +
"." +
event.target.className
);
break;
}
if (!$(node.span).hasClass(classDropOver)) {
node.debug("Ignore dragleave (multi).");
break;
}
$(node.span).removeClass(
classDropOver +
" " +
classDropAccept +
" " +
classDropReject
);
node.scheduleAction("cancel");
dndOpts.dragLeave(node, data);
$dropMarker.hide();
break;
case "drop":
// Data is only readable in the (dragstart and) drop event:
if ($.inArray(nodeMimeType, dataTransfer.types) >= 0) {
nodeData = dataTransfer.getData(nodeMimeType);
tree.info(
event.type +
": getData('application/x-fancytree-node'): '" +
nodeData +
"'"
);
}
if (!nodeData) {
// 1. Source is not a Fancytree node, or
// 2. If the FT mime type was set, but returns '', this
// is probably IE 11 (which only supports 'text')
nodeData = dataTransfer.getData("text");
tree.info(
event.type + ": getData('text'): '" + nodeData + "'"
);
}
if (nodeData) {
try {
// 'text' type may contain JSON if IE is involved
// and setTextTypeJson option was set
json = JSON.parse(nodeData);
if (json.title !== undefined) {
data.otherNodeData = json;
}
} catch (ex) {
// assume 'text' type contains plain text, so `otherNodeData`
// should not be set
}
}
tree.debug(
event.type +
": nodeData: '" +
nodeData +
"', otherNodeData: ",
data.otherNodeData
);
$(node.span).removeClass(
classDropOver +
" " +
classDropAccept +
" " +
classDropReject
);
// Let user implement the actual drop operation
data.hitMode = LAST_HIT_MODE;
prepareDropEffectCallback(event, data, !LAST_HIT_MODE);
data.isCancelled = !LAST_HIT_MODE;
var orgSourceElem = SOURCE_NODE && SOURCE_NODE.span,
orgSourceTree = SOURCE_NODE && SOURCE_NODE.tree;
dndOpts.dragDrop(node, data);
// applyDropEffectCallback(event, data);
// Prevent browser's default drop handling, i.e. open as link, ...
event.preventDefault();
if (orgSourceElem && !document.body.contains(orgSourceElem)) {
// The drop handler removed the original drag source from
// the DOM, so the dragend event will probaly not fire.
if (orgSourceTree === tree) {
tree.debug(
"Drop handler removed source element: generating dragEnd."
);
dndOpts.dragEnd(SOURCE_NODE, data);
} else {
tree.warn(
"Drop handler removed source element: dragend event may be lost."
);
}
}
_clearGlobals();
break;
}
// Dnd API madness: we must PREVENT default handling to enable dropping
if (allowDrop) {
event.preventDefault();
return false;
}
}
/** [ext-dnd5] Return a Fancytree instance, from element, index, event, or jQueryObject.
*
* @returns {FancytreeNode[]} List of nodes (empty if no drag operation)
* @example
* $.ui.fancytree.getDragNodeList();
*
* @alias Fancytree_Static#getDragNodeList
* @requires jquery.fancytree.dnd5.js
* @since 2.31
*/
$.ui.fancytree.getDragNodeList = function() {
return SOURCE_NODE_LIST || [];
};
/** [ext-dnd5] Return the FancytreeNode that is currently being dragged.
*
* If multiple nodes are dragged, only the first is returned.
*
* @returns {FancytreeNode | null} dragged nodes or null if no drag operation
* @example
* $.ui.fancytree.getDragNode();
*
* @alias Fancytree_Static#getDragNode
* @requires jquery.fancytree.dnd5.js
* @since 2.31
*/
$.ui.fancytree.getDragNode = function() {
return SOURCE_NODE;
};
/******************************************************************************
*
*/
$.ui.fancytree.registerExtension({
name: "dnd5",
version: "2.37.0",
// Default options for this extension.
options: {
autoExpandMS: 1500, // Expand nodes after n milliseconds of hovering
dropMarkerInsertOffsetX: -16, // Additional offset for drop-marker with hitMode = "before"/"after"
dropMarkerOffsetX: -24, // Absolute position offset for .fancytree-drop-marker relatively to ..fancytree-title (icon/img near a node accepting drop)
// #1021 `document.body` is not available yet
dropMarkerParent: "body", // Root Container used for drop marker (could be a shadow root)
multiSource: false, // true: Drag multiple (i.e. selected) nodes. Also a callback() is allowed
effectAllowed: "all", // Restrict the possible cursor shapes and modifier operations (can also be set in the dragStart event)
// dropEffect: "auto", // 'copy'|'link'|'move'|'auto'(calculate from `effectAllowed`+modifier keys) or callback(node, data) that returns such string.
dropEffectDefault: "move", // Default dropEffect ('copy', 'link', or 'move') when no modifier is pressed (overide in dragDrag, dragOver).
preventForeignNodes: false, // Prevent dropping nodes from different Fancytrees
preventLazyParents: true, // Prevent dropping items on unloaded lazy Fancytree nodes
preventNonNodes: false, // Prevent dropping items other than Fancytree nodes
preventRecursion: true, // Prevent dropping nodes on own descendants
preventSameParent: false, // Prevent dropping nodes under same direct parent
preventVoidMoves: true, // Prevent dropping nodes 'before self', etc.
scroll: true, // Enable auto-scrolling while dragging
scrollSensitivity: 20, // Active top/bottom margin in pixel
scrollSpeed: 5, // Pixel per event
setTextTypeJson: false, // Allow dragging of nodes to different IE windows
// Events (drag support)
dragStart: null, // Callback(sourceNode, data), return true, to enable dnd drag
dragDrag: $.noop, // Callback(sourceNode, data)
dragEnd: $.noop, // Callback(sourceNode, data)
// Events (drop support)
dragEnter: null, // Callback(targetNode, data), return true, to enable dnd drop
dragOver: $.noop, // Callback(targetNode, data)
dragExpand: $.noop, // Callback(targetNode, data), return false to prevent autoExpand
dragDrop: $.noop, // Callback(targetNode, data)
dragLeave: $.noop, // Callback(targetNode, data)
},
treeInit: function(ctx) {
var $temp,
tree = ctx.tree,
opts = ctx.options,
glyph = opts.glyph || null,
dndOpts = opts.dnd5;
if ($.inArray("dnd", opts.extensions) >= 0) {
$.error("Extensions 'dnd' and 'dnd5' are mutually exclusive.");
}
if (dndOpts.dragStop) {
$.error(
"dragStop is not used by ext-dnd5. Use dragEnd instead."
);
}
if (dndOpts.preventRecursiveMoves != null) {
$.error(
"preventRecursiveMoves was renamed to preventRecursion."
);
}
// Implement `opts.createNode` event to add the 'draggable' attribute
// #680: this must happen before calling super.treeInit()
if (dndOpts.dragStart) {
FT.overrideMethod(ctx.options, "createNode", function(
event,
data
) {
// Default processing if any
this._super.apply(this, arguments);
if (data.node.span) {
data.node.span.draggable = true;
} else {
data.node.warn("Cannot add `draggable`: no span tag");
}
});
}
this._superApply(arguments);
this.$container.addClass("fancytree-ext-dnd5");
// Store the current scroll parent, which may be the tree
// container, any enclosing div, or the document.
// #761: scrollParent() always needs a container child
$temp = $("<span>").appendTo(this.$container);
this.$scrollParent = $temp.scrollParent();
$temp.remove();
$dropMarker = $("#fancytree-drop-marker");
if (!$dropMarker.length) {
$dropMarker = $("<div id='fancytree-drop-marker'></div>")
.hide()
.css({
"z-index": 1000,
// Drop marker should not steal dragenter/dragover events:
"pointer-events": "none",
})
.prependTo(dndOpts.dropMarkerParent);
if (glyph) {
FT.setSpanIcon(
$dropMarker[0],
glyph.map._addClass,
glyph.map.dropMarker
);
}
}
$dropMarker.toggleClass("fancytree-rtl", !!opts.rtl);
// Enable drag support if dragStart() is specified:
if (dndOpts.dragStart) {
// Bind drag event handlers
tree.$container.on(
"dragstart drag dragend",
onDragEvent.bind(tree)
);
}
// Enable drop support if dragEnter() is specified:
if (dndOpts.dragEnter) {
// Bind drop event handlers
tree.$container.on(
"dragenter dragover dragleave drop",
onDropEvent.bind(tree)
);
}
},
});
// Value returned by `require('jquery.fancytree..')`
return $.ui.fancytree;
}); // End of closure
/*!
* jquery.fancytree.edit.js
*
* Make node titles editable.
* (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
*
* Copyright (c) 2008-2020, Martin Wendt (https://wwWendt.de)
*
* Released under the MIT license
* https://github.com/mar10/fancytree/wiki/LicenseInfo
*
* @version 2.37.0
* @date 2020-09-11T18:58:08Z
*/
(function(factory) {
if (typeof define === "function" && define.amd) {
// AMD. Register as an anonymous module.
define(["jquery", "./jquery.fancytree"], factory);
} else if (typeof module === "object" && module.exports) {
// Node/CommonJS
require("./jquery.fancytree");
module.exports = factory(require("jquery"));
} else {
// Browser globals
factory(jQuery);
}
})(function($) {
"use strict";
/*******************************************************************************
* Private functions and variables
*/
var isMac = /Mac/.test(navigator.platform),
escapeHtml = $.ui.fancytree.escapeHtml,
unescapeHtml = $.ui.fancytree.unescapeHtml;
/**
* [ext-edit] Start inline editing of current node title.
*
* @alias FancytreeNode#editStart
* @requires Fancytree
*/
$.ui.fancytree._FancytreeNodeClass.prototype.editStart = function() {
var $input,
node = this,
tree = this.tree,
local = tree.ext.edit,
instOpts = tree.options.edit,
$title = $(".fancytree-title", node.span),
eventData = {
node: node,
tree: tree,
options: tree.options,
isNew: $(node[tree.statusClassPropName]).hasClass(
"fancytree-edit-new"
),
orgTitle: node.title,
input: null,
dirty: false,
};
// beforeEdit may want to modify the title before editing
if (
instOpts.beforeEdit.call(
node,
{ type: "beforeEdit" },
eventData
) === false
) {
return false;
}
$.ui.fancytree.assert(!local.currentNode, "recursive edit");
local.currentNode = this;
local.eventData = eventData;
// Disable standard Fancytree mouse- and key handling
tree.widget._unbind();
local.lastDraggableAttrValue = node.span.draggable;
if (local.lastDraggableAttrValue) {
node.span.draggable = false;
}
// #116: ext-dnd prevents the blur event, so we have to catch outer clicks
$(document).on("mousedown.fancytree-edit", function(event) {
if (!$(event.target).hasClass("fancytree-edit-input")) {
node.editEnd(true, event);
}
});
// Replace node with <input>
$input = $("<input />", {
class: "fancytree-edit-input",
type: "text",
value: tree.options.escapeTitles
? eventData.orgTitle
: unescapeHtml(eventData.orgTitle),
});
local.eventData.input = $input;
if (instOpts.adjustWidthOfs != null) {
$input.width($title.width() + instOpts.adjustWidthOfs);
}
if (instOpts.inputCss != null) {
$input.css(instOpts.inputCss);
}
$title.html($input);
// Focus <input> and bind keyboard handler
$input
.focus()
.change(function(event) {
$input.addClass("fancytree-edit-dirty");
})
.on("keydown", function(event) {
switch (event.which) {
case $.ui.keyCode.ESCAPE:
node.editEnd(false, event);
break;
case $.ui.keyCode.ENTER:
node.editEnd(true, event);
return false; // so we don't start editmode on Mac
}
event.stopPropagation();
})
.blur(function(event) {
return node.editEnd(true, event);
});
instOpts.edit.call(node, { type: "edit" }, eventData);
};
/**
* [ext-edit] Stop inline editing.
* @param {Boolean} [applyChanges=false] false: cancel edit, true: save (if modified)
* @alias FancytreeNode#editEnd
* @requires jquery.fancytree.edit.js
*/
$.ui.fancytree._FancytreeNodeClass.prototype.editEnd = function(
applyChanges,
_event
) {
var newVal,
node = this,
tree = this.tree,
local = tree.ext.edit,
eventData = local.eventData,
instOpts = tree.options.edit,
$title = $(".fancytree-title", node.span),
$input = $title.find("input.fancytree-edit-input");
if (instOpts.trim) {
$input.val($.trim($input.val()));
}
newVal = $input.val();
eventData.dirty = newVal !== node.title;
eventData.originalEvent = _event;
// Find out, if saving is required
if (applyChanges === false) {
// If true/false was passed, honor this (except in rename mode, if unchanged)
eventData.save = false;
} else if (eventData.isNew) {
// In create mode, we save everything, except for empty text
eventData.save = newVal !== "";
} else {
// In rename mode, we save everyting, except for empty or unchanged text
eventData.save = eventData.dirty && newVal !== "";
}
// Allow to break (keep editor open), modify input, or re-define data.save
if (
instOpts.beforeClose.call(
node,
{ type: "beforeClose" },
eventData
) === false
) {
return false;
}
if (
eventData.save &&
instOpts.save.call(node, { type: "save" }, eventData) === false
) {
return false;
}
$input.removeClass("fancytree-edit-dirty").off();
// Unbind outer-click handler
$(document).off(".fancytree-edit");
if (eventData.save) {
// # 171: escape user input (not required if global escaping is on)
node.setTitle(
tree.options.escapeTitles ? newVal : escapeHtml(newVal)
);
node.setFocus();
} else {
if (eventData.isNew) {
node.remove();
node = eventData.node = null;
local.relatedNode.setFocus();
} else {
node.renderTitle();
node.setFocus();
}
}
local.eventData = null;
local.currentNode = null;
local.relatedNode = null;
// Re-enable mouse and keyboard handling
tree.widget._bind();
if (node && local.lastDraggableAttrValue) {
node.span.draggable = true;
}
// Set keyboard focus, even if setFocus() claims 'nothing to do'
tree.$container.get(0).focus({ preventScroll: true });
eventData.input = null;
instOpts.close.call(node, { type: "close" }, eventData);
return true;
};
/**
* [ext-edit] Create a new child or sibling node and start edit mode.
*
* @param {String} [mode='child'] 'before', 'after', or 'child'
* @param {Object} [init] NodeData (or simple title string)
* @alias FancytreeNode#editCreateNode
* @requires jquery.fancytree.edit.js
* @since 2.4
*/
$.ui.fancytree._FancytreeNodeClass.prototype.editCreateNode = function(
mode,
init
) {
var newNode,
tree = this.tree,
self = this;
mode = mode || "child";
if (init == null) {
init = { title: "" };
} else if (typeof init === "string") {
init = { title: init };
} else {
$.ui.fancytree.assert($.isPlainObject(init));
}
// Make sure node is expanded (and loaded) in 'child' mode
if (
mode === "child" &&
!this.isExpanded() &&
this.hasChildren() !== false
) {
this.setExpanded().done(function() {
self.editCreateNode(mode, init);
});
return;
}
newNode = this.addNode(init, mode);
// #644: Don't filter new nodes.
newNode.match = true;
$(newNode[tree.statusClassPropName])
.removeClass("fancytree-hide")
.addClass("fancytree-match");
newNode.makeVisible(/*{noAnimation: true}*/).done(function() {
$(newNode[tree.statusClassPropName]).addClass("fancytree-edit-new");
self.tree.ext.edit.relatedNode = self;
newNode.editStart();
});
};
/**
* [ext-edit] Check if any node in this tree in edit mode.
*
* @returns {FancytreeNode | null}
* @alias Fancytree#isEditing
* @requires jquery.fancytree.edit.js
*/
$.ui.fancytree._FancytreeClass.prototype.isEditing = function() {
return this.ext.edit ? this.ext.edit.currentNode : null;
};
/**
* [ext-edit] Check if this node is in edit mode.
* @returns {Boolean} true if node is currently beeing edited
* @alias FancytreeNode#isEditing
* @requires jquery.fancytree.edit.js
*/
$.ui.fancytree._FancytreeNodeClass.prototype.isEditing = function() {
return this.tree.ext.edit
? this.tree.ext.edit.currentNode === this
: false;
};
/*******************************************************************************
* Extension code
*/
$.ui.fancytree.registerExtension({
name: "edit",
version: "2.37.0",
// Default options for this extension.
options: {
adjustWidthOfs: 4, // null: don't adjust input size to content
allowEmpty: false, // Prevent empty input
inputCss: { minWidth: "3em" },
// triggerCancel: ["esc", "tab", "click"],
triggerStart: ["f2", "mac+enter", "shift+click"],
trim: true, // Trim whitespace before save
// Events:
beforeClose: $.noop, // Return false to prevent cancel/save (data.input is available)
beforeEdit: $.noop, // Return false to prevent edit mode
close: $.noop, // Editor was removed
edit: $.noop, // Editor was opened (available as data.input)
// keypress: $.noop, // Not yet implemented
save: $.noop, // Save data.input.val() or return false to keep editor open
},
// Local attributes
currentNode: null,
treeInit: function(ctx) {
var tree = ctx.tree;
this._superApply(arguments);
this.$container
.addClass("fancytree-ext-edit")
.on("fancytreebeforeupdateviewport", function(event, data) {
var editNode = tree.isEditing();
// When scrolling, the TR may be re-used by another node, so the
// active cell marker an
if (editNode) {
editNode.info("Cancel edit due to scroll event.");
editNode.editEnd(false, event);
}
});
},
nodeClick: function(ctx) {
var eventStr = $.ui.fancytree.eventToString(ctx.originalEvent),
triggerStart = ctx.options.edit.triggerStart;
if (
eventStr === "shift+click" &&
$.inArray("shift+click", triggerStart) >= 0
) {
if (ctx.originalEvent.shiftKey) {
ctx.node.editStart();
return false;
}
}
if (
eventStr === "click" &&
$.inArray("clickActive", triggerStart) >= 0
) {
// Only when click was inside title text (not aynwhere else in the row)
if (
ctx.node.isActive() &&
!ctx.node.isEditing() &&
$(ctx.originalEvent.target).hasClass("fancytree-title")
) {
ctx.node.editStart();
return false;
}
}
return this._superApply(arguments);
},
nodeDblclick: function(ctx) {
if ($.inArray("dblclick", ctx.options.edit.triggerStart) >= 0) {
ctx.node.editStart();
return false;
}
return this._superApply(arguments);
},
nodeKeydown: function(ctx) {
switch (ctx.originalEvent.which) {
case 113: // [F2]
if ($.inArray("f2", ctx.options.edit.triggerStart) >= 0) {
ctx.node.editStart();
return false;
}
break;
case $.ui.keyCode.ENTER:
if (
$.inArray("mac+enter", ctx.options.edit.triggerStart) >=
0 &&
isMac
) {
ctx.node.editStart();
return false;
}
break;
}
return this._superApply(arguments);
},
});
// Value returned by `require('jquery.fancytree..')`
return $.ui.fancytree;
}); // End of closure
/*!
* jquery.fancytree.filter.js
*
* Remove or highlight tree nodes, based on a filter.
* (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
*
* Copyright (c) 2008-2020, Martin Wendt (https://wwWendt.de)
*
* Released under the MIT license
* https://github.com/mar10/fancytree/wiki/LicenseInfo
*
* @version 2.37.0
* @date 2020-09-11T18:58:08Z
*/
(function(factory) {
if (typeof define === "function" && define.amd) {
// AMD. Register as an anonymous module.
define(["jquery", "./jquery.fancytree"], factory);
} else if (typeof module === "object" && module.exports) {
// Node/CommonJS
require("./jquery.fancytree");
module.exports = factory(require("jquery"));
} else {
// Browser globals
factory(jQuery);
}
})(function($) {
"use strict";
/*******************************************************************************
* Private functions and variables
*/
var KeyNoData = "__not_found__",
escapeHtml = $.ui.fancytree.escapeHtml;
function _escapeRegex(str) {
return (str + "").replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
}
function extractHtmlText(s) {
if (s.indexOf(">") >= 0) {
return $("<div/>")
.html(s)
.text();
}
return s;
}
$.ui.fancytree._FancytreeClass.prototype._applyFilterImpl = function(
filter,
branchMode,
_opts
) {
var match,
statusNode,
re,
reHighlight,
temp,
prevEnableUpdate,
count = 0,
treeOpts = this.options,
escapeTitles = treeOpts.escapeTitles,
prevAutoCollapse = treeOpts.autoCollapse,
opts = $.extend({}, treeOpts.filter, _opts),
hideMode = opts.mode === "hide",
leavesOnly = !!opts.leavesOnly && !branchMode;
// Default to 'match title substring (not case sensitive)'
if (typeof filter === "string") {
if (filter === "") {
this.warn(
"Fancytree passing an empty string as a filter is handled as clearFilter()."
);
this.clearFilter();
return;
}
if (opts.fuzzy) {
// See https://codereview.stackexchange.com/questions/23899/faster-javascript-fuzzy-string-matching-function/23905#23905
// and http://www.quora.com/How-is-the-fuzzy-search-algorithm-in-Sublime-Text-designed
// and http://www.dustindiaz.com/autocomplete-fuzzy-matching
match = filter.split("").reduce(function(a, b) {
return a + "[^" + b + "]*" + b;
});
} else {
match = _escapeRegex(filter); // make sure a '.' is treated literally
}
re = new RegExp(".*" + match + ".*", "i");
reHighlight = new RegExp(_escapeRegex(filter), "gi");
filter = function(node) {
if (!node.title) {
return false;
}
var text = escapeTitles
? node.title
: extractHtmlText(node.title),
res = !!re.test(text);
if (res && opts.highlight) {
if (escapeTitles) {
// #740: we must not apply the marks to escaped entity names, e.g. `"`
// Use some exotic characters to mark matches:
temp = text.replace(reHighlight, function(s) {
return "\uFFF7" + s + "\uFFF8";
});
// now we can escape the title...
node.titleWithHighlight = escapeHtml(temp)
// ... and finally insert the desired `<mark>` tags
.replace(/\uFFF7/g, "<mark>")
.replace(/\uFFF8/g, "</mark>");
} else {
node.titleWithHighlight = text.replace(
reHighlight,
function(s) {
return "<mark>" + s + "</mark>";
}
);
}
// node.debug("filter", escapeTitles, text, node.titleWithHighlight);
}
return res;
};
}
this.enableFilter = true;
this.lastFilterArgs = arguments;
prevEnableUpdate = this.enableUpdate(false);
this.$div.addClass("fancytree-ext-filter");
if (hideMode) {
this.$div.addClass("fancytree-ext-filter-hide");
} else {
this.$div.addClass("fancytree-ext-filter-dimm");
}
this.$div.toggleClass(
"fancytree-ext-filter-hide-expanders",
!!opts.hideExpanders
);
// Reset current filter
this.rootNode.subMatchCount = 0;
this.visit(function(node) {
delete node.match;
delete node.titleWithHighlight;
node.subMatchCount = 0;
});
statusNode = this.getRootNode()._findDirectChild(KeyNoData);
if (statusNode) {
statusNode.remove();
}
// Adjust node.hide, .match, and .subMatchCount properties
treeOpts.autoCollapse = false; // #528
this.visit(function(node) {
if (leavesOnly && node.children != null) {
return;
}
var res = filter(node),
matchedByBranch = false;
if (res === "skip") {
node.visit(function(c) {
c.match = false;
}, true);
return "skip";
}
if (!res && (branchMode || res === "branch") && node.parent.match) {
res = true;
matchedByBranch = true;
}
if (res) {
count++;
node.match = true;
node.visitParents(function(p) {
if (p !== node) {
p.subMatchCount += 1;
}
// Expand match (unless this is no real match, but only a node in a matched branch)
if (opts.autoExpand && !matchedByBranch && !p.expanded) {
p.setExpanded(true, {
noAnimation: true,
noEvents: true,
scrollIntoView: false,
});
p._filterAutoExpanded = true;
}
}, true);
}
});
treeOpts.autoCollapse = prevAutoCollapse;
if (count === 0 && opts.nodata && hideMode) {
statusNode = opts.nodata;
if ($.isFunction(statusNode)) {
statusNode = statusNode();
}
if (statusNode === true) {
statusNode = {};
} else if (typeof statusNode === "string") {
statusNode = { title: statusNode };
}
statusNode = $.extend(
{
statusNodeType: "nodata",
key: KeyNoData,
title: this.options.strings.noData,
},
statusNode
);
this.getRootNode().addNode(statusNode).match = true;
}
// Redraw whole tree
this._callHook("treeStructureChanged", this, "applyFilter");
// this.render();
this.enableUpdate(prevEnableUpdate);
return count;
};
/**
* [ext-filter] Dimm or hide nodes.
*
* @param {function | string} filter
* @param {boolean} [opts={autoExpand: false, leavesOnly: false}]
* @returns {integer} count
* @alias Fancytree#filterNodes
* @requires jquery.fancytree.filter.js
*/
$.ui.fancytree._FancytreeClass.prototype.filterNodes = function(
filter,
opts
) {
if (typeof opts === "boolean") {
opts = { leavesOnly: opts };
this.warn(
"Fancytree.filterNodes() leavesOnly option is deprecated since 2.9.0 / 2015-04-19. Use opts.leavesOnly instead."
);
}
return this._applyFilterImpl(filter, false, opts);
};
/**
* [ext-filter] Dimm or hide whole branches.
*
* @param {function | string} filter
* @param {boolean} [opts={autoExpand: false}]
* @returns {integer} count
* @alias Fancytree#filterBranches
* @requires jquery.fancytree.filter.js
*/
$.ui.fancytree._FancytreeClass.prototype.filterBranches = function(
filter,
opts
) {
return this._applyFilterImpl(filter, true, opts);
};
/**
* [ext-filter] Reset the filter.
*
* @alias Fancytree#clearFilter
* @requires jquery.fancytree.filter.js
*/
$.ui.fancytree._FancytreeClass.prototype.clearFilter = function() {
var $title,
statusNode = this.getRootNode()._findDirectChild(KeyNoData),
escapeTitles = this.options.escapeTitles,
enhanceTitle = this.options.enhanceTitle,
prevEnableUpdate = this.enableUpdate(false);
if (statusNode) {
statusNode.remove();
}
// we also counted root node's subMatchCount
delete this.rootNode.match;
delete this.rootNode.subMatchCount;
this.visit(function(node) {
if (node.match && node.span) {
// #491, #601
$title = $(node.span).find(">span.fancytree-title");
if (escapeTitles) {
$title.text(node.title);
} else {
$title.html(node.title);
}
if (enhanceTitle) {
enhanceTitle(
{ type: "enhanceTitle" },
{ node: node, $title: $title }
);
}
}
delete node.match;
delete node.subMatchCount;
delete node.titleWithHighlight;
if (node.$subMatchBadge) {
node.$subMatchBadge.remove();
delete node.$subMatchBadge;
}
if (node._filterAutoExpanded && node.expanded) {
node.setExpanded(false, {
noAnimation: true,
noEvents: true,
scrollIntoView: false,
});
}
delete node._filterAutoExpanded;
});
this.enableFilter = false;
this.lastFilterArgs = null;
this.$div.removeClass(
"fancytree-ext-filter fancytree-ext-filter-dimm fancytree-ext-filter-hide"
);
this._callHook("treeStructureChanged", this, "clearFilter");
// this.render();
this.enableUpdate(prevEnableUpdate);
};
/**
* [ext-filter] Return true if a filter is currently applied.
*
* @returns {Boolean}
* @alias Fancytree#isFilterActive
* @requires jquery.fancytree.filter.js
* @since 2.13
*/
$.ui.fancytree._FancytreeClass.prototype.isFilterActive = function() {
return !!this.enableFilter;
};
/**
* [ext-filter] Return true if this node is matched by current filter (or no filter is active).
*
* @returns {Boolean}
* @alias FancytreeNode#isMatched
* @requires jquery.fancytree.filter.js
* @since 2.13
*/
$.ui.fancytree._FancytreeNodeClass.prototype.isMatched = function() {
return !(this.tree.enableFilter && !this.match);
};
/*******************************************************************************
* Extension code
*/
$.ui.fancytree.registerExtension({
name: "filter",
version: "2.37.0",
// Default options for this extension.
options: {
autoApply: true, // Re-apply last filter if lazy data is loaded
autoExpand: false, // Expand all branches that contain matches while filtered
counter: true, // Show a badge with number of matching child nodes near parent icons
fuzzy: false, // Match single characters in order, e.g. 'fb' will match 'FooBar'
hideExpandedCounter: true, // Hide counter badge if parent is expanded
hideExpanders: false, // Hide expanders if all child nodes are hidden by filter
highlight: true, // Highlight matches by wrapping inside <mark> tags
leavesOnly: false, // Match end nodes only
nodata: true, // Display a 'no data' status node if result is empty
mode: "dimm", // Grayout unmatched nodes (pass "hide" to remove unmatched node instead)
},
nodeLoadChildren: function(ctx, source) {
var tree = ctx.tree;
return this._superApply(arguments).done(function() {
if (
tree.enableFilter &&
tree.lastFilterArgs &&
ctx.options.filter.autoApply
) {
tree._applyFilterImpl.apply(tree, tree.lastFilterArgs);
}
});
},
nodeSetExpanded: function(ctx, flag, callOpts) {
var node = ctx.node;
delete node._filterAutoExpanded;
// Make sure counter badge is displayed again, when node is beeing collapsed
if (
!flag &&
ctx.options.filter.hideExpandedCounter &&
node.$subMatchBadge
) {
node.$subMatchBadge.show();
}
return this._superApply(arguments);
},
nodeRenderStatus: function(ctx) {
// Set classes for current status
var res,
node = ctx.node,
tree = ctx.tree,
opts = ctx.options.filter,
$title = $(node.span).find("span.fancytree-title"),
$span = $(node[tree.statusClassPropName]),
enhanceTitle = ctx.options.enhanceTitle,
escapeTitles = ctx.options.escapeTitles;
res = this._super(ctx);
// nothing to do, if node was not yet rendered
if (!$span.length || !tree.enableFilter) {
return res;
}
$span
.toggleClass("fancytree-match", !!node.match)
.toggleClass("fancytree-submatch", !!node.subMatchCount)
.toggleClass(
"fancytree-hide",
!(node.match || node.subMatchCount)
);
// Add/update counter badge
if (
opts.counter &&
node.subMatchCount &&
(!node.isExpanded() || !opts.hideExpandedCounter)
) {
if (!node.$subMatchBadge) {
node.$subMatchBadge = $(
"<span class='fancytree-childcounter'/>"
);
$(
"span.fancytree-icon, span.fancytree-custom-icon",
node.span
).append(node.$subMatchBadge);
}
node.$subMatchBadge.show().text(node.subMatchCount);
} else if (node.$subMatchBadge) {
node.$subMatchBadge.hide();
}
// node.debug("nodeRenderStatus", node.titleWithHighlight, node.title)
// #601: also check for $title.length, because we don't need to render
// if node.span is null (i.e. not rendered)
if (node.span && (!node.isEditing || !node.isEditing.call(node))) {
if (node.titleWithHighlight) {
$title.html(node.titleWithHighlight);
} else if (escapeTitles) {
$title.text(node.title);
} else {
$title.html(node.title);
}
if (enhanceTitle) {
enhanceTitle(
{ type: "enhanceTitle" },
{ node: node, $title: $title }
);
}
}
return res;
},
});
// Value returned by `require('jquery.fancytree..')`
return $.ui.fancytree;
}); // End of closure
/*!
* jquery.fancytree.glyph.js
*
* Use glyph-fonts, ligature-fonts, or SVG icons instead of icon sprites.
* (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
*
* Copyright (c) 2008-2020, Martin Wendt (https://wwWendt.de)
*
* Released under the MIT license
* https://github.com/mar10/fancytree/wiki/LicenseInfo
*
* @version 2.37.0
* @date 2020-09-11T18:58:08Z
*/
(function(factory) {
if (typeof define === "function" && define.amd) {
// AMD. Register as an anonymous module.
define(["jquery", "./jquery.fancytree"], factory);
} else if (typeof module === "object" && module.exports) {
// Node/CommonJS
require("./jquery.fancytree");
module.exports = factory(require("jquery"));
} else {
// Browser globals
factory(jQuery);
}
})(function($) {
"use strict";
/******************************************************************************
* Private functions and variables
*/
var FT = $.ui.fancytree,
PRESETS = {
awesome3: {
// Outdated!
_addClass: "",
checkbox: "icon-check-empty",
checkboxSelected: "icon-check",
checkboxUnknown: "icon-check icon-muted",
dragHelper: "icon-caret-right",
dropMarker: "icon-caret-right",
error: "icon-exclamation-sign",
expanderClosed: "icon-caret-right",
expanderLazy: "icon-angle-right",
expanderOpen: "icon-caret-down",
loading: "icon-refresh icon-spin",
nodata: "icon-meh",
noExpander: "",
radio: "icon-circle-blank",
radioSelected: "icon-circle",
// radioUnknown: "icon-circle icon-muted",
// Default node icons.
// (Use tree.options.icon callback to define custom icons based on node data)
doc: "icon-file-alt",
docOpen: "icon-file-alt",
folder: "icon-folder-close-alt",
folderOpen: "icon-folder-open-alt",
},
awesome4: {
_addClass: "fa",
checkbox: "fa-square-o",
checkboxSelected: "fa-check-square-o",
checkboxUnknown: "fa-square fancytree-helper-indeterminate-cb",
dragHelper: "fa-arrow-right",
dropMarker: "fa-long-arrow-right",
error: "fa-warning",
expanderClosed: "fa-caret-right",
expanderLazy: "fa-angle-right",
expanderOpen: "fa-caret-down",
// We may prevent wobbling rotations on FF by creating a separate sub element:
loading: { html: "<span class='fa fa-spinner fa-pulse' />" },
nodata: "fa-meh-o",
noExpander: "",
radio: "fa-circle-thin", // "fa-circle-o"
radioSelected: "fa-circle",
// radioUnknown: "fa-dot-circle-o",
// Default node icons.
// (Use tree.options.icon callback to define custom icons based on node data)
doc: "fa-file-o",
docOpen: "fa-file-o",
folder: "fa-folder-o",
folderOpen: "fa-folder-open-o",
},
awesome5: {
// fontawesome 5 have several different base classes
// "far, fas, fal and fab" The rendered svg puts that prefix
// in a different location so we have to keep them separate here
_addClass: "",
checkbox: "far fa-square",
checkboxSelected: "far fa-check-square",
// checkboxUnknown: "far fa-window-close",
checkboxUnknown:
"fas fa-square fancytree-helper-indeterminate-cb",
radio: "far fa-circle",
radioSelected: "fas fa-circle",
radioUnknown: "far fa-dot-circle",
dragHelper: "fas fa-arrow-right",
dropMarker: "fas fa-long-arrow-alt-right",
error: "fas fa-exclamation-triangle",
expanderClosed: "fas fa-caret-right",
expanderLazy: "fas fa-angle-right",
expanderOpen: "fas fa-caret-down",
loading: "fas fa-spinner fa-pulse",
nodata: "far fa-meh",
noExpander: "",
// Default node icons.
// (Use tree.options.icon callback to define custom icons based on node data)
doc: "far fa-file",
docOpen: "far fa-file",
folder: "far fa-folder",
folderOpen: "far fa-folder-open",
},
bootstrap3: {
_addClass: "glyphicon",
checkbox: "glyphicon-unchecked",
checkboxSelected: "glyphicon-check",
checkboxUnknown:
"glyphicon-expand fancytree-helper-indeterminate-cb", // "glyphicon-share",
dragHelper: "glyphicon-play",
dropMarker: "glyphicon-arrow-right",
error: "glyphicon-warning-sign",
expanderClosed: "glyphicon-menu-right", // glyphicon-plus-sign
expanderLazy: "glyphicon-menu-right", // glyphicon-plus-sign
expanderOpen: "glyphicon-menu-down", // glyphicon-minus-sign
loading: "glyphicon-refresh fancytree-helper-spin",
nodata: "glyphicon-info-sign",
noExpander: "",
radio: "glyphicon-remove-circle", // "glyphicon-unchecked",
radioSelected: "glyphicon-ok-circle", // "glyphicon-check",
// radioUnknown: "glyphicon-ban-circle",
// Default node icons.
// (Use tree.options.icon callback to define custom icons based on node data)
doc: "glyphicon-file",
docOpen: "glyphicon-file",
folder: "glyphicon-folder-close",
folderOpen: "glyphicon-folder-open",
},
material: {
_addClass: "material-icons",
checkbox: { text: "check_box_outline_blank" },
checkboxSelected: { text: "check_box" },
checkboxUnknown: { text: "indeterminate_check_box" },
dragHelper: { text: "play_arrow" },
dropMarker: { text: "arrow-forward" },
error: { text: "warning" },
expanderClosed: { text: "chevron_right" },
expanderLazy: { text: "last_page" },
expanderOpen: { text: "expand_more" },
loading: {
text: "autorenew",
addClass: "fancytree-helper-spin",
},
nodata: { text: "info" },
noExpander: { text: "" },
radio: { text: "radio_button_unchecked" },
radioSelected: { text: "radio_button_checked" },
// Default node icons.
// (Use tree.options.icon callback to define custom icons based on node data)
doc: { text: "insert_drive_file" },
docOpen: { text: "insert_drive_file" },
folder: { text: "folder" },
folderOpen: { text: "folder_open" },
},
};
function setIcon(node, span, baseClass, opts, type) {
var map = opts.map,
icon = map[type],
$span = $(span),
$counter = $span.find(".fancytree-childcounter"),
setClass = baseClass + " " + (map._addClass || "");
// #871 Allow a callback
if ($.isFunction(icon)) {
icon = icon.call(this, node, span, type);
}
// node.debug( "setIcon(" + baseClass + ", " + type + "): " + "oldIcon" + " -> " + icon );
// #871: propsed this, but I am not sure how robust this is, e.g.
// the prefix (fas, far) class changes are not considered?
// if (span.tagName === "svg" && opts.preset === "awesome5") {
// // fa5 script converts <i> to <svg> so call a specific handler.
// var oldIcon = "fa-" + $span.data("icon");
// // node.debug( "setIcon(" + baseClass + ", " + type + "): " + oldIcon + " -> " + icon );
// if (typeof oldIcon === "string") {
// $span.removeClass(oldIcon);
// }
// if (typeof icon === "string") {
// $span.addClass(icon);
// }
// return;
// }
if (typeof icon === "string") {
// #883: remove inner html that may be added by prev. mode
span.innerHTML = "";
$span.attr("class", setClass + " " + icon).append($counter);
} else if (icon) {
if (icon.text) {
span.textContent = "" + icon.text;
} else if (icon.html) {
span.innerHTML = icon.html;
} else {
span.innerHTML = "";
}
$span
.attr("class", setClass + " " + (icon.addClass || ""))
.append($counter);
}
}
$.ui.fancytree.registerExtension({
name: "glyph",
version: "2.37.0",
// Default options for this extension.
options: {
preset: null, // 'awesome3', 'awesome4', 'bootstrap3', 'material'
map: {},
},
treeInit: function(ctx) {
var tree = ctx.tree,
opts = ctx.options.glyph;
if (opts.preset) {
FT.assert(
!!PRESETS[opts.preset],
"Invalid value for `options.glyph.preset`: " + opts.preset
);
opts.map = $.extend({}, PRESETS[opts.preset], opts.map);
} else {
tree.warn("ext-glyph: missing `preset` option.");
}
this._superApply(arguments);
tree.$container.addClass("fancytree-ext-glyph");
},
nodeRenderStatus: function(ctx) {
var checkbox,
icon,
res,
span,
node = ctx.node,
$span = $(node.span),
opts = ctx.options.glyph;
res = this._super(ctx);
if (node.isRootNode()) {
return res;
}
span = $span.children(".fancytree-expander").get(0);
if (span) {
// if( node.isLoading() ){
// icon = "loading";
if (node.expanded && node.hasChildren()) {
icon = "expanderOpen";
} else if (node.isUndefined()) {
icon = "expanderLazy";
} else if (node.hasChildren()) {
icon = "expanderClosed";
} else {
icon = "noExpander";
}
// span.className = "fancytree-expander " + map[icon];
setIcon(node, span, "fancytree-expander", opts, icon);
}
if (node.tr) {
span = $("td", node.tr)
.find(".fancytree-checkbox")
.get(0);
} else {
span = $span.children(".fancytree-checkbox").get(0);
}
if (span) {
checkbox = FT.evalOption("checkbox", node, node, opts, false);
if (
(node.parent && node.parent.radiogroup) ||
checkbox === "radio"
) {
icon = node.selected ? "radioSelected" : "radio";
setIcon(
node,
span,
"fancytree-checkbox fancytree-radio",
opts,
icon
);
} else {
// eslint-disable-next-line no-nested-ternary
icon = node.selected
? "checkboxSelected"
: node.partsel
? "checkboxUnknown"
: "checkbox";
// span.className = "fancytree-checkbox " + map[icon];
setIcon(node, span, "fancytree-checkbox", opts, icon);
}
}
// Standard icon (note that this does not match .fancytree-custom-icon,
// that might be set by opts.icon callbacks)
span = $span.children(".fancytree-icon").get(0);
if (span) {
if (node.statusNodeType) {
icon = node.statusNodeType; // loading, error
} else if (node.folder) {
icon =
node.expanded && node.hasChildren()
? "folderOpen"
: "folder";
} else {
icon = node.expanded ? "docOpen" : "doc";
}
setIcon(node, span, "fancytree-icon", opts, icon);
}
return res;
},
nodeSetStatus: function(ctx, status, message, details) {
var res,
span,
opts = ctx.options.glyph,
node = ctx.node;
res = this._superApply(arguments);
if (
status === "error" ||
status === "loading" ||
status === "nodata"
) {
if (node.parent) {
span = $(".fancytree-expander", node.span).get(0);
if (span) {
setIcon(node, span, "fancytree-expander", opts, status);
}
} else {
//
span = $(
".fancytree-statusnode-" + status,
node[this.nodeContainerAttrName]
)
.find(".fancytree-icon")
.get(0);
if (span) {
setIcon(node, span, "fancytree-icon", opts, status);
}
}
}
return res;
},
});
// Value returned by `require('jquery.fancytree..')`
return $.ui.fancytree;
}); // End of closure
/*!
* jquery.fancytree.gridnav.js
*
* Support keyboard navigation for trees with embedded input controls.
* (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
*
* Copyright (c) 2008-2020, Martin Wendt (https://wwWendt.de)
*
* Released under the MIT license
* https://github.com/mar10/fancytree/wiki/LicenseInfo
*
* @version 2.37.0
* @date 2020-09-11T18:58:08Z
*/
(function(factory) {
if (typeof define === "function" && define.amd) {
// AMD. Register as an anonymous module.
define([
"jquery",
"./jquery.fancytree",
"./jquery.fancytree.table",
], factory);
} else if (typeof module === "object" && module.exports) {
// Node/CommonJS
require("./jquery.fancytree.table"); // core + table
module.exports = factory(require("jquery"));
} else {
// Browser globals
factory(jQuery);
}
})(function($) {
"use strict";
/*******************************************************************************
* Private functions and variables
*/
// Allow these navigation keys even when input controls are focused
var KC = $.ui.keyCode,
// which keys are *not* handled by embedded control, but passed to tree
// navigation handler:
NAV_KEYS = {
text: [KC.UP, KC.DOWN],
checkbox: [KC.UP, KC.DOWN, KC.LEFT, KC.RIGHT],
link: [KC.UP, KC.DOWN, KC.LEFT, KC.RIGHT],
radiobutton: [KC.UP, KC.DOWN, KC.LEFT, KC.RIGHT],
"select-one": [KC.LEFT, KC.RIGHT],
"select-multiple": [KC.LEFT, KC.RIGHT],
};
/* Calculate TD column index (considering colspans).*/
function getColIdx($tr, $td) {
var colspan,
td = $td.get(0),
idx = 0;
$tr.children().each(function() {
if (this === td) {
return false;
}
colspan = $(this).prop("colspan");
idx += colspan ? colspan : 1;
});
return idx;
}
/* Find TD at given column index (considering colspans).*/
function findTdAtColIdx($tr, colIdx) {
var colspan,
res = null,
idx = 0;
$tr.children().each(function() {
if (idx >= colIdx) {
res = $(this);
return false;
}
colspan = $(this).prop("colspan");
idx += colspan ? colspan : 1;
});
return res;
}
/* Find adjacent cell for a given direction. Skip empty cells and consider merged cells */
function findNeighbourTd($target, keyCode) {
var $tr,
colIdx,
$td = $target.closest("td"),
$tdNext = null;
switch (keyCode) {
case KC.LEFT:
$tdNext = $td.prev();
break;
case KC.RIGHT:
$tdNext = $td.next();
break;
case KC.UP:
case KC.DOWN:
$tr = $td.parent();
colIdx = getColIdx($tr, $td);
while (true) {
$tr = keyCode === KC.UP ? $tr.prev() : $tr.next();
if (!$tr.length) {
break;
}
// Skip hidden rows
if ($tr.is(":hidden")) {
continue;
}
// Find adjacent cell in the same column
$tdNext = findTdAtColIdx($tr, colIdx);
// Skip cells that don't conatain a focusable element
if ($tdNext && $tdNext.find(":input,a").length) {
break;
}
}
break;
}
return $tdNext;
}
/*******************************************************************************
* Extension code
*/
$.ui.fancytree.registerExtension({
name: "gridnav",
version: "2.37.0",
// Default options for this extension.
options: {
autofocusInput: false, // Focus first embedded input if node gets activated
handleCursorKeys: true, // Allow UP/DOWN in inputs to move to prev/next node
},
treeInit: function(ctx) {
// gridnav requires the table extension to be loaded before itself
this._requireExtension("table", true, true);
this._superApply(arguments);
this.$container.addClass("fancytree-ext-gridnav");
// Activate node if embedded input gets focus (due to a click)
this.$container.on("focusin", function(event) {
var ctx2,
node = $.ui.fancytree.getNode(event.target);
if (node && !node.isActive()) {
// Call node.setActive(), but also pass the event
ctx2 = ctx.tree._makeHookContext(node, event);
ctx.tree._callHook("nodeSetActive", ctx2, true);
}
});
},
nodeSetActive: function(ctx, flag, callOpts) {
var $outer,
opts = ctx.options.gridnav,
node = ctx.node,
event = ctx.originalEvent || {},
triggeredByInput = $(event.target).is(":input");
flag = flag !== false;
this._superApply(arguments);
if (flag) {
if (ctx.options.titlesTabbable) {
if (!triggeredByInput) {
$(node.span)
.find("span.fancytree-title")
.focus();
node.setFocus();
}
// If one node is tabbable, the container no longer needs to be
ctx.tree.$container.attr("tabindex", "-1");
// ctx.tree.$container.removeAttr("tabindex");
} else if (opts.autofocusInput && !triggeredByInput) {
// Set focus to input sub input (if node was clicked, but not
// when TAB was pressed )
$outer = $(node.tr || node.span);
$outer
.find(":input:enabled")
.first()
.focus();
}
}
},
nodeKeydown: function(ctx) {
var inputType,
handleKeys,
$td,
opts = ctx.options.gridnav,
event = ctx.originalEvent,
$target = $(event.target);
if ($target.is(":input:enabled")) {
inputType = $target.prop("type");
} else if ($target.is("a")) {
inputType = "link";
}
// ctx.tree.debug("ext-gridnav nodeKeydown", event, inputType);
if (inputType && opts.handleCursorKeys) {
handleKeys = NAV_KEYS[inputType];
if (handleKeys && $.inArray(event.which, handleKeys) >= 0) {
$td = findNeighbourTd($target, event.which);
if ($td && $td.length) {
// ctx.node.debug("ignore keydown in input", event.which, handleKeys);
$td.find(":input:enabled,a").focus();
// Prevent Fancytree default navigation
return false;
}
}
return true;
}
// ctx.tree.debug("ext-gridnav NOT HANDLED", event, inputType);
return this._superApply(arguments);
},
});
// Value returned by `require('jquery.fancytree..')`
return $.ui.fancytree;
}); // End of closure
/*!
* jquery.fancytree.multi.js
*
* Allow multiple selection of nodes by mouse or keyboard.
* (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
*
* Copyright (c) 2008-2020, Martin Wendt (https://wwWendt.de)
*
* Released under the MIT license
* https://github.com/mar10/fancytree/wiki/LicenseInfo
*
* @version 2.37.0
* @date 2020-09-11T18:58:08Z
*/
(function(factory) {
if (typeof define === "function" && define.amd) {
// AMD. Register as an anonymous module.
define(["jquery", "./jquery.fancytree"], factory);
} else if (typeof module === "object" && module.exports) {
// Node/CommonJS
require("./jquery.fancytree");
module.exports = factory(require("jquery"));
} else {
// Browser globals
factory(jQuery);
}
})(function($) {
"use strict";
/*******************************************************************************
* Private functions and variables
*/
// var isMac = /Mac/.test(navigator.platform);
/*******************************************************************************
* Extension code
*/
$.ui.fancytree.registerExtension({
name: "multi",
version: "2.37.0",
// Default options for this extension.
options: {
allowNoSelect: false, //
mode: "sameParent", //
// Events:
// beforeSelect: $.noop // Return false to prevent cancel/save (data.input is available)
},
treeInit: function(ctx) {
this._superApply(arguments);
this.$container.addClass("fancytree-ext-multi");
if (ctx.options.selectMode === 1) {
$.error(
"Fancytree ext-multi: selectMode: 1 (single) is not compatible."
);
}
},
nodeClick: function(ctx) {
var //pluginOpts = ctx.options.multi,
tree = ctx.tree,
node = ctx.node,
activeNode = tree.getActiveNode() || tree.getFirstChild(),
isCbClick = ctx.targetType === "checkbox",
isExpanderClick = ctx.targetType === "expander",
eventStr = $.ui.fancytree.eventToString(ctx.originalEvent);
switch (eventStr) {
case "click":
if (isExpanderClick) {
break;
} // Default handler will expand/collapse
if (!isCbClick) {
tree.selectAll(false);
// Select clicked node (radio-button mode)
node.setSelected();
}
// Default handler will toggle checkbox clicks and activate
break;
case "shift+click":
// node.debug("click")
tree.visitRows(
function(n) {
// n.debug("click2", n===node, node)
n.setSelected();
if (n === node) {
return false;
}
},
{
start: activeNode,
reverse: activeNode.isBelowOf(node),
}
);
break;
case "ctrl+click":
case "meta+click": // Mac: [Command]
node.toggleSelected();
return;
}
return this._superApply(arguments);
},
nodeKeydown: function(ctx) {
var tree = ctx.tree,
node = ctx.node,
event = ctx.originalEvent,
eventStr = $.ui.fancytree.eventToString(event);
switch (eventStr) {
case "up":
case "down":
tree.selectAll(false);
node.navigate(event.which, true);
tree.getActiveNode().setSelected();
break;
case "shift+up":
case "shift+down":
node.navigate(event.which, true);
tree.getActiveNode().setSelected();
break;
}
return this._superApply(arguments);
},
});
// Value returned by `require('jquery.fancytree..')`
return $.ui.fancytree;
}); // End of closure
/*!
* jquery.fancytree.persist.js
*
* Persist tree status in cookiesRemove or highlight tree nodes, based on a filter.
* (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
*
* @depends: js-cookie or jquery-cookie
*
* Copyright (c) 2008-2020, Martin Wendt (https://wwWendt.de)
*
* Released under the MIT license
* https://github.com/mar10/fancytree/wiki/LicenseInfo
*
* @version 2.37.0
* @date 2020-09-11T18:58:08Z
*/
(function(factory) {
if (typeof define === "function" && define.amd) {
// AMD. Register as an anonymous module.
define(["jquery", "./jquery.fancytree"], factory);
} else if (typeof module === "object" && module.exports) {
// Node/CommonJS
require("./jquery.fancytree");
module.exports = factory(require("jquery"));
} else {
// Browser globals
factory(jQuery);
}
})(function($) {
"use strict";
/* global Cookies:false */
/*******************************************************************************
* Private functions and variables
*/
var cookieStore = null,
localStorageStore = null,
sessionStorageStore = null,
_assert = $.ui.fancytree.assert,
ACTIVE = "active",
EXPANDED = "expanded",
FOCUS = "focus",
SELECTED = "selected";
// Accessing window.xxxStorage may raise security exceptions (see #1022)
try {
_assert(window.localStorage && window.localStorage.getItem);
localStorageStore = {
get: function(key) {
return window.localStorage.getItem(key);
},
set: function(key, value) {
window.localStorage.setItem(key, value);
},
remove: function(key) {
window.localStorage.removeItem(key);
},
};
} catch (e) {
$.ui.fancytree.warn("Could not access window.localStorage", e);
}
try {
_assert(window.sessionStorage && window.sessionStorage.getItem);
sessionStorageStore = {
get: function(key) {
return window.sessionStorage.getItem(key);
},
set: function(key, value) {
window.sessionStorage.setItem(key, value);
},
remove: function(key) {
window.sessionStorage.removeItem(key);
},
};
} catch (e) {
$.ui.fancytree.warn("Could not access window.sessionStorage", e);
}
if (typeof Cookies === "function") {
// Assume https://github.com/js-cookie/js-cookie
cookieStore = {
get: Cookies.get,
set: function(key, value) {
Cookies.set(key, value, this.options.persist.cookie);
},
remove: Cookies.remove,
};
} else if ($ && typeof $.cookie === "function") {
// Fall back to https://github.com/carhartl/jquery-cookie
cookieStore = {
get: $.cookie,
set: function(key, value) {
$.cookie.set(key, value, this.options.persist.cookie);
},
remove: $.removeCookie,
};
}
/* Recursively load lazy nodes
* @param {string} mode 'load', 'expand', false
*/
function _loadLazyNodes(tree, local, keyList, mode, dfd) {
var i,
key,
l,
node,
foundOne = false,
expandOpts = tree.options.persist.expandOpts,
deferredList = [],
missingKeyList = [];
keyList = keyList || [];
dfd = dfd || $.Deferred();
for (i = 0, l = keyList.length; i < l; i++) {
key = keyList[i];
node = tree.getNodeByKey(key);
if (node) {
if (mode && node.isUndefined()) {
foundOne = true;
tree.debug(
"_loadLazyNodes: " + node + " is lazy: loading..."
);
if (mode === "expand") {
deferredList.push(node.setExpanded(true, expandOpts));
} else {
deferredList.push(node.load());
}
} else {
tree.debug("_loadLazyNodes: " + node + " already loaded.");
node.setExpanded(true, expandOpts);
}
} else {
missingKeyList.push(key);
tree.debug("_loadLazyNodes: " + node + " was not yet found.");
}
}
$.when.apply($, deferredList).always(function() {
// All lazy-expands have finished
if (foundOne && missingKeyList.length > 0) {
// If we read new nodes from server, try to resolve yet-missing keys
_loadLazyNodes(tree, local, missingKeyList, mode, dfd);
} else {
if (missingKeyList.length) {
tree.warn(
"_loadLazyNodes: could not load those keys: ",
missingKeyList
);
for (i = 0, l = missingKeyList.length; i < l; i++) {
key = keyList[i];
local._appendKey(EXPANDED, keyList[i], false);
}
}
dfd.resolve();
}
});
return dfd;
}
/**
* [ext-persist] Remove persistence data of the given type(s).
* Called like
* $.ui.fancytree.getTree("#tree").clearCookies("active expanded focus selected");
*
* @alias Fancytree#clearPersistData
* @requires jquery.fancytree.persist.js
*/
$.ui.fancytree._FancytreeClass.prototype.clearPersistData = function(
types
) {
var local = this.ext.persist,
prefix = local.cookiePrefix;
types = types || "active expanded focus selected";
if (types.indexOf(ACTIVE) >= 0) {
local._data(prefix + ACTIVE, null);
}
if (types.indexOf(EXPANDED) >= 0) {
local._data(prefix + EXPANDED, null);
}
if (types.indexOf(FOCUS) >= 0) {
local._data(prefix + FOCUS, null);
}
if (types.indexOf(SELECTED) >= 0) {
local._data(prefix + SELECTED, null);
}
};
$.ui.fancytree._FancytreeClass.prototype.clearCookies = function(types) {
this.warn(
"'tree.clearCookies()' is deprecated since v2.27.0: use 'clearPersistData()' instead."
);
return this.clearPersistData(types);
};
/**
* [ext-persist] Return persistence information from cookies
*
* Called like
* $.ui.fancytree.getTree("#tree").getPersistData();
*
* @alias Fancytree#getPersistData
* @requires jquery.fancytree.persist.js
*/
$.ui.fancytree._FancytreeClass.prototype.getPersistData = function() {
var local = this.ext.persist,
prefix = local.cookiePrefix,
delim = local.cookieDelimiter,
res = {};
res[ACTIVE] = local._data(prefix + ACTIVE);
res[EXPANDED] = (local._data(prefix + EXPANDED) || "").split(delim);
res[SELECTED] = (local._data(prefix + SELECTED) || "").split(delim);
res[FOCUS] = local._data(prefix + FOCUS);
return res;
};
/******************************************************************************
* Extension code
*/
$.ui.fancytree.registerExtension({
name: "persist",
version: "2.37.0",
// Default options for this extension.
options: {
cookieDelimiter: "~",
cookiePrefix: undefined, // 'fancytree-<treeId>-' by default
cookie: {
raw: false,
expires: "",
path: "",
domain: "",
secure: false,
},
expandLazy: false, // true: recursively expand and load lazy nodes
expandOpts: undefined, // optional `opts` argument passed to setExpanded()
fireActivate: true, // false: suppress `activate` event after active node was restored
overrideSource: true, // true: cookie takes precedence over `source` data attributes.
store: "auto", // 'cookie': force cookie, 'local': force localStore, 'session': force sessionStore
types: "active expanded focus selected",
},
/* Generic read/write string data to cookie, sessionStorage or localStorage. */
_data: function(key, value) {
var store = this._local.store;
if (value === undefined) {
return store.get.call(this, key);
} else if (value === null) {
store.remove.call(this, key);
} else {
store.set.call(this, key, value);
}
},
/* Append `key` to a cookie. */
_appendKey: function(type, key, flag) {
key = "" + key; // #90
var local = this._local,
instOpts = this.options.persist,
delim = instOpts.cookieDelimiter,
cookieName = local.cookiePrefix + type,
data = local._data(cookieName),
keyList = data ? data.split(delim) : [],
idx = $.inArray(key, keyList);
// Remove, even if we add a key, so the key is always the last entry
if (idx >= 0) {
keyList.splice(idx, 1);
}
// Append key to cookie
if (flag) {
keyList.push(key);
}
local._data(cookieName, keyList.join(delim));
},
treeInit: function(ctx) {
var tree = ctx.tree,
opts = ctx.options,
local = this._local,
instOpts = this.options.persist;
// // For 'auto' or 'cookie' mode, the cookie plugin must be available
// _assert((instOpts.store !== "auto" && instOpts.store !== "cookie") || cookieStore,
// "Missing required plugin for 'persist' extension: js.cookie.js or jquery.cookie.js");
local.cookiePrefix =
instOpts.cookiePrefix || "fancytree-" + tree._id + "-";
local.storeActive = instOpts.types.indexOf(ACTIVE) >= 0;
local.storeExpanded = instOpts.types.indexOf(EXPANDED) >= 0;
local.storeSelected = instOpts.types.indexOf(SELECTED) >= 0;
local.storeFocus = instOpts.types.indexOf(FOCUS) >= 0;
local.store = null;
if (instOpts.store === "auto") {
instOpts.store = localStorageStore ? "local" : "cookie";
}
if ($.isPlainObject(instOpts.store)) {
local.store = instOpts.store;
} else if (instOpts.store === "cookie") {
local.store = cookieStore;
} else if (instOpts.store === "local") {
local.store =
instOpts.store === "local"
? localStorageStore
: sessionStorageStore;
} else if (instOpts.store === "session") {
local.store =
instOpts.store === "local"
? localStorageStore
: sessionStorageStore;
}
_assert(local.store, "Need a valid store.");
// Bind init-handler to apply cookie state
tree.$div.on("fancytreeinit", function(event) {
if (
tree._triggerTreeEvent("beforeRestore", null, {}) === false
) {
return;
}
var cookie,
dfd,
i,
keyList,
node,
prevFocus = local._data(local.cookiePrefix + FOCUS), // record this before node.setActive() overrides it;
noEvents = instOpts.fireActivate === false;
// tree.debug("document.cookie:", document.cookie);
cookie = local._data(local.cookiePrefix + EXPANDED);
keyList = cookie && cookie.split(instOpts.cookieDelimiter);
if (local.storeExpanded) {
// Recursively load nested lazy nodes if expandLazy is 'expand' or 'load'
// Also remove expand-cookies for unmatched nodes
dfd = _loadLazyNodes(
tree,
local,
keyList,
instOpts.expandLazy ? "expand" : false,
null
);
} else {
// nothing to do
dfd = new $.Deferred().resolve();
}
dfd.done(function() {
if (local.storeSelected) {
cookie = local._data(local.cookiePrefix + SELECTED);
if (cookie) {
keyList = cookie.split(instOpts.cookieDelimiter);
for (i = 0; i < keyList.length; i++) {
node = tree.getNodeByKey(keyList[i]);
if (node) {
if (
node.selected === undefined ||
(instOpts.overrideSource &&
node.selected === false)
) {
// node.setSelected();
node.selected = true;
node.renderStatus();
}
} else {
// node is no longer member of the tree: remove from cookie also
local._appendKey(
SELECTED,
keyList[i],
false
);
}
}
}
// In selectMode 3 we have to fix the child nodes, since we
// only stored the selected *top* nodes
if (tree.options.selectMode === 3) {
tree.visit(function(n) {
if (n.selected) {
n.fixSelection3AfterClick();
return "skip";
}
});
}
}
if (local.storeActive) {
cookie = local._data(local.cookiePrefix + ACTIVE);
if (
cookie &&
(opts.persist.overrideSource || !tree.activeNode)
) {
node = tree.getNodeByKey(cookie);
if (node) {
node.debug("persist: set active", cookie);
// We only want to set the focus if the container
// had the keyboard focus before
node.setActive(true, {
noFocus: true,
noEvents: noEvents,
});
}
}
}
if (local.storeFocus && prevFocus) {
node = tree.getNodeByKey(prevFocus);
if (node) {
// node.debug("persist: set focus", cookie);
if (tree.options.titlesTabbable) {
$(node.span)
.find(".fancytree-title")
.focus();
} else {
$(tree.$container).focus();
}
// node.setFocus();
}
}
tree._triggerTreeEvent("restore", null, {});
});
});
// Init the tree
return this._superApply(arguments);
},
nodeSetActive: function(ctx, flag, callOpts) {
var res,
local = this._local;
flag = flag !== false;
res = this._superApply(arguments);
if (local.storeActive) {
local._data(
local.cookiePrefix + ACTIVE,
this.activeNode ? this.activeNode.key : null
);
}
return res;
},
nodeSetExpanded: function(ctx, flag, callOpts) {
var res,
node = ctx.node,
local = this._local;
flag = flag !== false;
res = this._superApply(arguments);
if (local.storeExpanded) {
local._appendKey(EXPANDED, node.key, flag);
}
return res;
},
nodeSetFocus: function(ctx, flag) {
var res,
local = this._local;
flag = flag !== false;
res = this._superApply(arguments);
if (local.storeFocus) {
local._data(
local.cookiePrefix + FOCUS,
this.focusNode ? this.focusNode.key : null
);
}
return res;
},
nodeSetSelected: function(ctx, flag, callOpts) {
var res,
selNodes,
tree = ctx.tree,
node = ctx.node,
local = this._local;
flag = flag !== false;
res = this._superApply(arguments);
if (local.storeSelected) {
if (tree.options.selectMode === 3) {
// In selectMode 3 we only store the the selected *top* nodes.
// De-selecting a node may also de-select some parents, so we
// calculate the current status again
selNodes = $.map(tree.getSelectedNodes(true), function(n) {
return n.key;
});
selNodes = selNodes.join(
ctx.options.persist.cookieDelimiter
);
local._data(local.cookiePrefix + SELECTED, selNodes);
} else {
// beforeSelect can prevent the change - flag doesn't reflect the node.selected state
local._appendKey(SELECTED, node.key, node.selected);
}
}
return res;
},
});
// Value returned by `require('jquery.fancytree..')`
return $.ui.fancytree;
}); // End of closure
/*!
* jquery.fancytree.table.js
*
* Render tree as table (aka 'tree grid', 'table tree').
* (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
*
* Copyright (c) 2008-2020, Martin Wendt (https://wwWendt.de)
*
* Released under the MIT license
* https://github.com/mar10/fancytree/wiki/LicenseInfo
*
* @version 2.37.0
* @date 2020-09-11T18:58:08Z
*/
(function(factory) {
if (typeof define === "function" && define.amd) {
// AMD. Register as an anonymous module.
define(["jquery", "./jquery.fancytree"], factory);
} else if (typeof module === "object" && module.exports) {
// Node/CommonJS
require("./jquery.fancytree");
module.exports = factory(require("jquery"));
} else {
// Browser globals
factory(jQuery);
}
})(function($) {
"use strict";
/******************************************************************************
* Private functions and variables
*/
function _assert(cond, msg) {
msg = msg || "";
if (!cond) {
$.error("Assertion failed " + msg);
}
}
function insertFirstChild(referenceNode, newNode) {
referenceNode.insertBefore(newNode, referenceNode.firstChild);
}
function insertSiblingAfter(referenceNode, newNode) {
referenceNode.parentNode.insertBefore(
newNode,
referenceNode.nextSibling
);
}
/* Show/hide all rows that are structural descendants of `parent`. */
function setChildRowVisibility(parent, flag) {
parent.visit(function(node) {
var tr = node.tr;
// currentFlag = node.hide ? false : flag; // fix for ext-filter
if (tr) {
tr.style.display = node.hide || !flag ? "none" : "";
}
if (!node.expanded) {
return "skip";
}
});
}
/* Find node that is rendered in previous row. */
function findPrevRowNode(node) {
var i,
last,
prev,
parent = node.parent,
siblings = parent ? parent.children : null;
if (siblings && siblings.length > 1 && siblings[0] !== node) {
// use the lowest descendant of the preceeding sibling
i = $.inArray(node, siblings);
prev = siblings[i - 1];
_assert(prev.tr);
// descend to lowest child (with a <tr> tag)
while (prev.children && prev.children.length) {
last = prev.children[prev.children.length - 1];
if (!last.tr) {
break;
}
prev = last;
}
} else {
// if there is no preceding sibling, use the direct parent
prev = parent;
}
return prev;
}
$.ui.fancytree.registerExtension({
name: "table",
version: "2.37.0",
// Default options for this extension.
options: {
checkboxColumnIdx: null, // render the checkboxes into the this column index (default: nodeColumnIdx)
indentation: 16, // indent every node level by 16px
mergeStatusColumns: true, // display 'nodata', 'loading', 'error' centered in a single, merged TR
nodeColumnIdx: 0, // render node expander, icon, and title to this column (default: #0)
},
// Overide virtual methods for this extension.
// `this` : is this extension object
// `this._super`: the virtual function that was overriden (member of prev. extension or Fancytree)
treeInit: function(ctx) {
var i,
n,
$row,
$tbody,
tree = ctx.tree,
opts = ctx.options,
tableOpts = opts.table,
$table = tree.widget.element;
if (tableOpts.customStatus != null) {
if (opts.renderStatusColumns == null) {
tree.warn(
"The 'customStatus' option is deprecated since v2.15.0. Use 'renderStatusColumns' instead."
);
opts.renderStatusColumns = tableOpts.customStatus;
} else {
$.error(
"The 'customStatus' option is deprecated since v2.15.0. Use 'renderStatusColumns' only instead."
);
}
}
if (opts.renderStatusColumns) {
if (opts.renderStatusColumns === true) {
opts.renderStatusColumns = opts.renderColumns;
// } else if( opts.renderStatusColumns === "wide" ) {
// opts.renderStatusColumns = _renderStatusNodeWide;
}
}
$table.addClass("fancytree-container fancytree-ext-table");
$tbody = $table.find(">tbody");
if (!$tbody.length) {
// TODO: not sure if we can rely on browsers to insert missing <tbody> before <tr>s:
if ($table.find(">tr").length) {
$.error(
"Expected table > tbody > tr. If you see this please open an issue."
);
}
$tbody = $("<tbody>").appendTo($table);
}
tree.tbody = $tbody[0];
// Prepare row templates:
// Determine column count from table header if any
tree.columnCount = $("thead >tr", $table)
.last()
.find(">th", $table).length;
// Read TR templates from tbody if any
$row = $tbody.children("tr").first();
if ($row.length) {
n = $row.children("td").length;
if (tree.columnCount && n !== tree.columnCount) {
tree.warn(
"Column count mismatch between thead (" +
tree.columnCount +
") and tbody (" +
n +
"): using tbody."
);
tree.columnCount = n;
}
$row = $row.clone();
} else {
// Only thead is defined: create default row markup
_assert(
tree.columnCount >= 1,
"Need either <thead> or <tbody> with <td> elements to determine column count."
);
$row = $("<tr />");
for (i = 0; i < tree.columnCount; i++) {
$row.append("<td />");
}
}
$row.find(">td")
.eq(tableOpts.nodeColumnIdx)
.html("<span class='fancytree-node' />");
if (opts.aria) {
$row.attr("role", "row");
$row.find("td").attr("role", "gridcell");
}
tree.rowFragment = document.createDocumentFragment();
tree.rowFragment.appendChild($row.get(0));
// // If tbody contains a second row, use this as status node template
// $row = $tbody.children("tr").eq(1);
// if( $row.length === 0 ) {
// tree.statusRowFragment = tree.rowFragment;
// } else {
// $row = $row.clone();
// tree.statusRowFragment = document.createDocumentFragment();
// tree.statusRowFragment.appendChild($row.get(0));
// }
//
$tbody.empty();
// Make sure that status classes are set on the node's <tr> elements
tree.statusClassPropName = "tr";
tree.ariaPropName = "tr";
this.nodeContainerAttrName = "tr";
// #489: make sure $container is set to <table>, even if ext-dnd is listed before ext-table
tree.$container = $table;
this._superApply(arguments);
// standard Fancytree created a root UL
$(tree.rootNode.ul).remove();
tree.rootNode.ul = null;
// Add container to the TAB chain
// #577: Allow to set tabindex to "0", "-1" and ""
this.$container.attr("tabindex", opts.tabindex);
// this.$container.attr("tabindex", opts.tabbable ? "0" : "-1");
if (opts.aria) {
tree.$container
.attr("role", "treegrid")
.attr("aria-readonly", true);
}
},
nodeRemoveChildMarkup: function(ctx) {
var node = ctx.node;
// node.debug("nodeRemoveChildMarkup()");
node.visit(function(n) {
if (n.tr) {
$(n.tr).remove();
n.tr = null;
}
});
},
nodeRemoveMarkup: function(ctx) {
var node = ctx.node;
// node.debug("nodeRemoveMarkup()");
if (node.tr) {
$(node.tr).remove();
node.tr = null;
}
this.nodeRemoveChildMarkup(ctx);
},
/* Override standard render. */
nodeRender: function(ctx, force, deep, collapsed, _recursive) {
var children,
firstTr,
i,
l,
newRow,
prevNode,
prevTr,
subCtx,
tree = ctx.tree,
node = ctx.node,
opts = ctx.options,
isRootNode = !node.parent;
if (tree._enableUpdate === false) {
// $.ui.fancytree.debug("*** nodeRender _enableUpdate: false");
return;
}
if (!_recursive) {
ctx.hasCollapsedParents = node.parent && !node.parent.expanded;
}
// $.ui.fancytree.debug("*** nodeRender " + node + ", isRoot=" + isRootNode, "tr=" + node.tr, "hcp=" + ctx.hasCollapsedParents, "parent.tr=" + (node.parent && node.parent.tr));
if (!isRootNode) {
if (node.tr && force) {
this.nodeRemoveMarkup(ctx);
}
if (node.tr) {
if (force) {
// Set icon, link, and title (normally this is only required on initial render)
this.nodeRenderTitle(ctx); // triggers renderColumns()
} else {
// Update element classes according to node state
this.nodeRenderStatus(ctx);
}
} else {
if (ctx.hasCollapsedParents && !deep) {
// #166: we assume that the parent will be (recursively) rendered
// later anyway.
// node.debug("nodeRender ignored due to unrendered parent");
return;
}
// Create new <tr> after previous row
// if( node.isStatusNode() ) {
// newRow = tree.statusRowFragment.firstChild.cloneNode(true);
// } else {
newRow = tree.rowFragment.firstChild.cloneNode(true);
// }
prevNode = findPrevRowNode(node);
// $.ui.fancytree.debug("*** nodeRender " + node + ": prev: " + prevNode.key);
_assert(prevNode);
if (collapsed === true && _recursive) {
// hide all child rows, so we can use an animation to show it later
newRow.style.display = "none";
} else if (deep && ctx.hasCollapsedParents) {
// also hide this row if deep === true but any parent is collapsed
newRow.style.display = "none";
// newRow.style.color = "red";
}
if (prevNode.tr) {
insertSiblingAfter(prevNode.tr, newRow);
} else {
_assert(
!prevNode.parent,
"prev. row must have a tr, or be system root"
);
// tree.tbody.appendChild(newRow);
insertFirstChild(tree.tbody, newRow); // #675
}
node.tr = newRow;
if (node.key && opts.generateIds) {
node.tr.id = opts.idPrefix + node.key;
}
node.tr.ftnode = node;
// if(opts.aria){
// $(node.tr).attr("aria-labelledby", "ftal_" + opts.idPrefix + node.key);
// }
node.span = $("span.fancytree-node", node.tr).get(0);
// Set icon, link, and title (normally this is only required on initial render)
this.nodeRenderTitle(ctx);
// Allow tweaking, binding, after node was created for the first time
// tree._triggerNodeEvent("createNode", ctx);
if (opts.createNode) {
opts.createNode.call(tree, { type: "createNode" }, ctx);
}
}
}
// Allow tweaking after node state was rendered
// tree._triggerNodeEvent("renderNode", ctx);
if (opts.renderNode) {
opts.renderNode.call(tree, { type: "renderNode" }, ctx);
}
// Visit child nodes
// Add child markup
children = node.children;
if (children && (isRootNode || deep || node.expanded)) {
for (i = 0, l = children.length; i < l; i++) {
subCtx = $.extend({}, ctx, { node: children[i] });
subCtx.hasCollapsedParents =
subCtx.hasCollapsedParents || !node.expanded;
this.nodeRender(subCtx, force, deep, collapsed, true);
}
}
// Make sure, that <tr> order matches node.children order.
if (children && !_recursive) {
// we only have to do it once, for the root branch
prevTr = node.tr || null;
firstTr = tree.tbody.firstChild;
// Iterate over all descendants
node.visit(function(n) {
if (n.tr) {
if (
!n.parent.expanded &&
n.tr.style.display !== "none"
) {
// fix after a node was dropped over a collapsed
n.tr.style.display = "none";
setChildRowVisibility(n, false);
}
if (n.tr.previousSibling !== prevTr) {
node.debug("_fixOrder: mismatch at node: " + n);
var nextTr = prevTr ? prevTr.nextSibling : firstTr;
tree.tbody.insertBefore(n.tr, nextTr);
}
prevTr = n.tr;
}
});
}
// Update element classes according to node state
// if(!isRootNode){
// this.nodeRenderStatus(ctx);
// }
},
nodeRenderTitle: function(ctx, title) {
var $cb,
res,
tree = ctx.tree,
node = ctx.node,
opts = ctx.options,
isStatusNode = node.isStatusNode();
res = this._super(ctx, title);
if (node.isRootNode()) {
return res;
}
// Move checkbox to custom column
if (
opts.checkbox &&
!isStatusNode &&
opts.table.checkboxColumnIdx != null
) {
$cb = $("span.fancytree-checkbox", node.span); //.detach();
$(node.tr)
.find("td")
.eq(+opts.table.checkboxColumnIdx)
.html($cb);
}
// Update element classes according to node state
this.nodeRenderStatus(ctx);
if (isStatusNode) {
if (opts.renderStatusColumns) {
// Let user code write column content
opts.renderStatusColumns.call(
tree,
{ type: "renderStatusColumns" },
ctx
);
} else if (opts.table.mergeStatusColumns && node.isTopLevel()) {
$(node.tr)
.find(">td")
.eq(0)
.prop("colspan", tree.columnCount)
.text(node.title)
.addClass("fancytree-status-merged")
.nextAll()
.remove();
} // else: default rendering for status node: leave other cells empty
} else if (opts.renderColumns) {
opts.renderColumns.call(tree, { type: "renderColumns" }, ctx);
}
return res;
},
nodeRenderStatus: function(ctx) {
var indent,
node = ctx.node,
opts = ctx.options;
this._super(ctx);
$(node.tr).removeClass("fancytree-node");
// indent
indent = (node.getLevel() - 1) * opts.table.indentation;
if (opts.rtl) {
$(node.span).css({ paddingRight: indent + "px" });
} else {
$(node.span).css({ paddingLeft: indent + "px" });
}
},
/* Expand node, return Deferred.promise. */
nodeSetExpanded: function(ctx, flag, callOpts) {
// flag defaults to true
flag = flag !== false;
if ((ctx.node.expanded && flag) || (!ctx.node.expanded && !flag)) {
// Expanded state isn't changed - just call base implementation
return this._superApply(arguments);
}
var dfd = new $.Deferred(),
subOpts = $.extend({}, callOpts, {
noEvents: true,
noAnimation: true,
});
callOpts = callOpts || {};
function _afterExpand(ok) {
setChildRowVisibility(ctx.node, flag);
if (ok) {
if (
flag &&
ctx.options.autoScroll &&
!callOpts.noAnimation &&
ctx.node.hasChildren()
) {
// Scroll down to last child, but keep current node visible
ctx.node
.getLastChild()
.scrollIntoView(true, { topNode: ctx.node })
.always(function() {
if (!callOpts.noEvents) {
ctx.tree._triggerNodeEvent(
flag ? "expand" : "collapse",
ctx
);
}
dfd.resolveWith(ctx.node);
});
} else {
if (!callOpts.noEvents) {
ctx.tree._triggerNodeEvent(
flag ? "expand" : "collapse",
ctx
);
}
dfd.resolveWith(ctx.node);
}
} else {
if (!callOpts.noEvents) {
ctx.tree._triggerNodeEvent(
flag ? "expand" : "collapse",
ctx
);
}
dfd.rejectWith(ctx.node);
}
}
// Call base-expand with disabled events and animation
this._super(ctx, flag, subOpts)
.done(function() {
_afterExpand(true);
})
.fail(function() {
_afterExpand(false);
});
return dfd.promise();
},
nodeSetStatus: function(ctx, status, message, details) {
if (status === "ok") {
var node = ctx.node,
firstChild = node.children ? node.children[0] : null;
if (firstChild && firstChild.isStatusNode()) {
$(firstChild.tr).remove();
}
}
return this._superApply(arguments);
},
treeClear: function(ctx) {
this.nodeRemoveChildMarkup(this._makeHookContext(this.rootNode));
return this._superApply(arguments);
},
treeDestroy: function(ctx) {
this.$container.find("tbody").empty();
if (this.$source) {
this.$source.removeClass("fancytree-helper-hidden");
}
return this._superApply(arguments);
},
/*,
treeSetFocus: function(ctx, flag) {
// alert("treeSetFocus" + ctx.tree.$container);
ctx.tree.$container.focus();
$.ui.fancytree.focusTree = ctx.tree;
}*/
});
// Value returned by `require('jquery.fancytree..')`
return $.ui.fancytree;
}); // End of closure
/*!
* jquery.fancytree.themeroller.js
*
* Enable jQuery UI ThemeRoller styles.
* (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
*
* @see http://jqueryui.com/themeroller/
*
* Copyright (c) 2008-2020, Martin Wendt (https://wwWendt.de)
*
* Released under the MIT license
* https://github.com/mar10/fancytree/wiki/LicenseInfo
*
* @version 2.37.0
* @date 2020-09-11T18:58:08Z
*/
(function(factory) {
if (typeof define === "function" && define.amd) {
// AMD. Register as an anonymous module.
define(["jquery", "./jquery.fancytree"], factory);
} else if (typeof module === "object" && module.exports) {
// Node/CommonJS
require("./jquery.fancytree");
module.exports = factory(require("jquery"));
} else {
// Browser globals
factory(jQuery);
}
})(function($) {
"use strict";
/*******************************************************************************
* Extension code
*/
$.ui.fancytree.registerExtension({
name: "themeroller",
version: "2.37.0",
// Default options for this extension.
options: {
activeClass: "ui-state-active", // Class added to active node
// activeClass: "ui-state-highlight",
addClass: "ui-corner-all", // Class added to all nodes
focusClass: "ui-state-focus", // Class added to focused node
hoverClass: "ui-state-hover", // Class added to hovered node
selectedClass: "ui-state-highlight", // Class added to selected nodes
// selectedClass: "ui-state-active"
},
treeInit: function(ctx) {
var $el = ctx.widget.element,
opts = ctx.options.themeroller;
this._superApply(arguments);
if ($el[0].nodeName === "TABLE") {
$el.addClass("ui-widget ui-corner-all");
$el.find(">thead tr").addClass("ui-widget-header");
$el.find(">tbody").addClass("ui-widget-conent");
} else {
$el.addClass("ui-widget ui-widget-content ui-corner-all");
}
$el.on("mouseenter mouseleave", ".fancytree-node", function(event) {
var node = $.ui.fancytree.getNode(event.target),
flag = event.type === "mouseenter";
$(node.tr ? node.tr : node.span).toggleClass(
opts.hoverClass + " " + opts.addClass,
flag
);
});
},
treeDestroy: function(ctx) {
this._superApply(arguments);
ctx.widget.element.removeClass(
"ui-widget ui-widget-content ui-corner-all"
);
},
nodeRenderStatus: function(ctx) {
var classes = {},
node = ctx.node,
$el = $(node.tr ? node.tr : node.span),
opts = ctx.options.themeroller;
this._super(ctx);
/*
.ui-state-highlight: Class to be applied to highlighted or selected elements. Applies "highlight" container styles to an element and its child text, links, and icons.
.ui-state-error: Class to be applied to error messaging container elements. Applies "error" container styles to an element and its child text, links, and icons.
.ui-state-error-text: An additional class that applies just the error text color without background. Can be used on form labels for instance. Also applies error icon color to child icons.
.ui-state-default: Class to be applied to clickable button-like elements. Applies "clickable default" container styles to an element and its child text, links, and icons.
.ui-state-hover: Class to be applied on mouseover to clickable button-like elements. Applies "clickable hover" container styles to an element and its child text, links, and icons.
.ui-state-focus: Class to be applied on keyboard focus to clickable button-like elements. Applies "clickable hover" container styles to an element and its child text, links, and icons.
.ui-state-active: Class to be applied on mousedown to clickable button-like elements. Applies "clickable active" container styles to an element and its child text, links, and icons.
*/
// Set ui-state-* class (handle the case that the same class is assigned
// to different states)
classes[opts.activeClass] = false;
classes[opts.focusClass] = false;
classes[opts.selectedClass] = false;
if (node.isActive()) {
classes[opts.activeClass] = true;
}
if (node.hasFocus()) {
classes[opts.focusClass] = true;
}
// activeClass takes precedence before selectedClass:
if (node.isSelected() && !node.isActive()) {
classes[opts.selectedClass] = true;
}
$el.toggleClass(opts.activeClass, classes[opts.activeClass]);
$el.toggleClass(opts.focusClass, classes[opts.focusClass]);
$el.toggleClass(opts.selectedClass, classes[opts.selectedClass]);
// Additional classes (e.g. 'ui-corner-all')
$el.addClass(opts.addClass);
},
});
// Value returned by `require('jquery.fancytree..')`
return $.ui.fancytree;
}); // End of closure
/*!
* jquery.fancytree.wide.js
* Support for 100% wide selection bars.
* (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
*
* Copyright (c) 2008-2020, Martin Wendt (https://wwWendt.de)
*
* Released under the MIT license
* https://github.com/mar10/fancytree/wiki/LicenseInfo
*
* @version 2.37.0
* @date 2020-09-11T18:58:08Z
*/
(function(factory) {
if (typeof define === "function" && define.amd) {
// AMD. Register as an anonymous module.
define(["jquery", "./jquery.fancytree"], factory);
} else if (typeof module === "object" && module.exports) {
// Node/CommonJS
require("./jquery.fancytree");
module.exports = factory(require("jquery"));
} else {
// Browser globals
factory(jQuery);
}
})(function($) {
"use strict";
var reNumUnit = /^([+-]?(?:\d+|\d*\.\d+))([a-z]*|%)$/; // split "1.5em" to ["1.5", "em"]
/*******************************************************************************
* Private functions and variables
*/
// var _assert = $.ui.fancytree.assert;
/* Calculate inner width without scrollbar */
// function realInnerWidth($el) {
// // http://blog.jquery.com/2012/08/16/jquery-1-8-box-sizing-width-csswidth-and-outerwidth/
// // inst.contWidth = parseFloat(this.$container.css("width"), 10);
// // 'Client width without scrollbar' - 'padding'
// return $el[0].clientWidth - ($el.innerWidth() - parseFloat($el.css("width"), 10));
// }
/* Create a global embedded CSS style for the tree. */
function defineHeadStyleElement(id, cssText) {
id = "fancytree-style-" + id;
var $headStyle = $("#" + id);
if (!cssText) {
$headStyle.remove();
return null;
}
if (!$headStyle.length) {
$headStyle = $("<style />")
.attr("id", id)
.addClass("fancytree-style")
.prop("type", "text/css")
.appendTo("head");
}
try {
$headStyle.html(cssText);
} catch (e) {
// fix for IE 6-8
$headStyle[0].styleSheet.cssText = cssText;
}
return $headStyle;
}
/* Calculate the CSS rules that indent title spans. */
function renderLevelCss(
containerId,
depth,
levelOfs,
lineOfs,
labelOfs,
measureUnit
) {
var i,
prefix = "#" + containerId + " span.fancytree-level-",
rules = [];
for (i = 0; i < depth; i++) {
rules.push(
prefix +
(i + 1) +
" span.fancytree-title { padding-left: " +
(i * levelOfs + lineOfs) +
measureUnit +
"; }"
);
}
// Some UI animations wrap the UL inside a DIV and set position:relative on both.
// This breaks the left:0 and padding-left:nn settings of the title
rules.push(
"#" +
containerId +
" div.ui-effects-wrapper ul li span.fancytree-title, " +
"#" +
containerId +
" li.fancytree-animating span.fancytree-title " + // #716
"{ padding-left: " +
labelOfs +
measureUnit +
"; position: static; width: auto; }"
);
return rules.join("\n");
}
// /**
// * [ext-wide] Recalculate the width of the selection bar after the tree container
// * was resized.<br>
// * May be called explicitly on container resize, since there is no resize event
// * for DIV tags.
// *
// * @alias Fancytree#wideUpdate
// * @requires jquery.fancytree.wide.js
// */
// $.ui.fancytree._FancytreeClass.prototype.wideUpdate = function(){
// var inst = this.ext.wide,
// prevCw = inst.contWidth,
// prevLo = inst.lineOfs;
// inst.contWidth = realInnerWidth(this.$container);
// // Each title is precceeded by 2 or 3 icons (16px + 3 margin)
// // + 1px title border and 3px title padding
// // TODO: use code from treeInit() below
// inst.lineOfs = (this.options.checkbox ? 3 : 2) * 19;
// if( prevCw !== inst.contWidth || prevLo !== inst.lineOfs ) {
// this.debug("wideUpdate: " + inst.contWidth);
// this.visit(function(node){
// node.tree._callHook("nodeRenderTitle", node);
// });
// }
// };
/*******************************************************************************
* Extension code
*/
$.ui.fancytree.registerExtension({
name: "wide",
version: "2.37.0",
// Default options for this extension.
options: {
iconWidth: null, // Adjust this if @fancy-icon-width != "16px"
iconSpacing: null, // Adjust this if @fancy-icon-spacing != "3px"
labelSpacing: null, // Adjust this if padding between icon and label != "3px"
levelOfs: null, // Adjust this if ul padding != "16px"
},
treeCreate: function(ctx) {
this._superApply(arguments);
this.$container.addClass("fancytree-ext-wide");
var containerId,
cssText,
iconSpacingUnit,
labelSpacingUnit,
iconWidthUnit,
levelOfsUnit,
instOpts = ctx.options.wide,
// css sniffing
$dummyLI = $(
"<li id='fancytreeTemp'><span class='fancytree-node'><span class='fancytree-icon' /><span class='fancytree-title' /></span><ul />"
).appendTo(ctx.tree.$container),
$dummyIcon = $dummyLI.find(".fancytree-icon"),
$dummyUL = $dummyLI.find("ul"),
// $dummyTitle = $dummyLI.find(".fancytree-title"),
iconSpacing =
instOpts.iconSpacing || $dummyIcon.css("margin-left"),
iconWidth = instOpts.iconWidth || $dummyIcon.css("width"),
labelSpacing = instOpts.labelSpacing || "3px",
levelOfs = instOpts.levelOfs || $dummyUL.css("padding-left");
$dummyLI.remove();
iconSpacingUnit = iconSpacing.match(reNumUnit)[2];
iconSpacing = parseFloat(iconSpacing, 10);
labelSpacingUnit = labelSpacing.match(reNumUnit)[2];
labelSpacing = parseFloat(labelSpacing, 10);
iconWidthUnit = iconWidth.match(reNumUnit)[2];
iconWidth = parseFloat(iconWidth, 10);
levelOfsUnit = levelOfs.match(reNumUnit)[2];
if (
iconSpacingUnit !== iconWidthUnit ||
levelOfsUnit !== iconWidthUnit ||
labelSpacingUnit !== iconWidthUnit
) {
$.error(
"iconWidth, iconSpacing, and levelOfs must have the same css measure unit"
);
}
this._local.measureUnit = iconWidthUnit;
this._local.levelOfs = parseFloat(levelOfs);
this._local.lineOfs =
(1 +
(ctx.options.checkbox ? 1 : 0) +
(ctx.options.icon === false ? 0 : 1)) *
(iconWidth + iconSpacing) +
iconSpacing;
this._local.labelOfs = labelSpacing;
this._local.maxDepth = 10;
// Get/Set a unique Id on the container (if not already exists)
containerId = this.$container.uniqueId().attr("id");
// Generated css rules for some levels (extended on demand)
cssText = renderLevelCss(
containerId,
this._local.maxDepth,
this._local.levelOfs,
this._local.lineOfs,
this._local.labelOfs,
this._local.measureUnit
);
defineHeadStyleElement(containerId, cssText);
},
treeDestroy: function(ctx) {
// Remove generated css rules
defineHeadStyleElement(this.$container.attr("id"), null);
return this._superApply(arguments);
},
nodeRenderStatus: function(ctx) {
var containerId,
cssText,
res,
node = ctx.node,
level = node.getLevel();
res = this._super(ctx);
// Generate some more level-n rules if required
if (level > this._local.maxDepth) {
containerId = this.$container.attr("id");
this._local.maxDepth *= 2;
node.debug(
"Define global ext-wide css up to level " +
this._local.maxDepth
);
cssText = renderLevelCss(
containerId,
this._local.maxDepth,
this._local.levelOfs,
this._local.lineOfs,
this._local.labelSpacing,
this._local.measureUnit
);
defineHeadStyleElement(containerId, cssText);
}
// Add level-n class to apply indentation padding.
// (Setting element style would not work, since it cannot easily be
// overriden while animations run)
$(node.span).addClass("fancytree-level-" + level);
return res;
},
});
// Value returned by `require('jquery.fancytree..')`
return $.ui.fancytree;
}); // End of closure
|
require('fs').readdirSync(__dirname + '/').forEach(function(file) {
if (file.match(/.+\.js/g) !== null && file !== 'index.js') {
var name = file.replace(/\.js$/, '');
module.exports[name] = require('./' + file);
}
}) |
import React, { Component } from 'react';
import PropTypes from "prop-types";
import {Form ,Button, Message} from "semantic-ui-react";
import Validator from "validator" ;
import InlineError from "../message/InlineError";
class SignupForm extends Component {
state = {
data :{
email : "",
password : ""
},
loading :false ,
errors : {}
}
onchange = (e) => {
this.setState({
data : { ...this.state.data , [e.target.name] : e.target.value}
})
};
onSubmit = () => {
const errors = this.validate(this.state.data);
this.setState({errors});
if (Object.keys(errors).length === 0 ){
this.setState({loading:true});
this.props
.submit(this.state.data)
.catch(err =>
this.setState({errors : err.response.data.errors ,loading: false})
);
}
};
validate = (data) => {
const errors = {};
if (!Validator.isEmail(data.email)) errors.email = "Invalid Email";
if (!data.password) errors.password = "Can't be blank";
return errors;
};
render() {
const { data, errors, loading} = this.state ;
return (
<Form onSubmit={this.onSubmit} loading={loading}>
{errors.global && (
<Message negative>
<Message.Header>{ errors.global }</Message.Header>
</Message>
)}
<Form.Field error={!!errors.email}>
<label htmlFor="email">Email</label>
<input
type="email"
id="email"
name="email"
placeholder="example@mail.com"
value={data.email}
onChange={this.onchange}
/>
{errors.email && <InlineError text={errors.email} />}
</Form.Field>
<Form.Field error={!!errors.password}>
<label htmlFor="password">Password</label>
<input
type="password"
id="password"
name="password"
placeholder="password"
value={data.password}
onChange={this.onchange}
/>
{errors.password && <InlineError text={errors.password} />}
</Form.Field>
<Button primary>Sign Up</Button>
</Form>
);
}
}
SignupForm.propTypes = {
submit: PropTypes.func.isRequired
};
export default SignupForm; |
/**
* @license Highcharts JS v9.0.0 (2021-02-02)
*
* (c) 2009-2019 Highsoft AS
*
* License: www.highcharts.com/license
*/
'use strict';
(function (factory) {
if (typeof module === 'object' && module.exports) {
factory['default'] = factory;
module.exports = factory;
} else if (typeof define === 'function' && define.amd) {
define('highcharts/themes/high-contrast-light', ['highcharts'], function (Highcharts) {
factory(Highcharts);
factory.Highcharts = Highcharts;
return factory;
});
} else {
factory(typeof Highcharts !== 'undefined' ? Highcharts : undefined);
}
}(function (Highcharts) {
var _modules = Highcharts ? Highcharts._modules : {};
function _registerModule(obj, path, args, fn) {
if (!obj.hasOwnProperty(path)) {
obj[path] = fn.apply(null, args);
}
}
_registerModule(_modules, 'Extensions/Themes/HighContrastLight.js', [_modules['Core/Globals.js'], _modules['Core/Utilities.js']], function (Highcharts, U) {
/* *
*
* (c) 2010-2021 Highsoft AS
*
* Author: Øystein Moseng
*
* License: www.highcharts.com/license
*
* Accessible high-contrast theme for Highcharts. Specifically tailored
* towards 3:1 contrast against white/off-white backgrounds. Neighboring
* colors are tested for color blindness.
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
var setOptions = U.setOptions;
Highcharts.theme = {
colors: [
'#5f98cf',
'#434348',
'#49a65e',
'#f45b5b',
'#708090',
'#b68c51',
'#397550',
'#c0493d',
'#4f4a7a',
'#b381b3'
],
navigator: {
series: {
color: '#5f98cf',
lineColor: '#5f98cf'
}
}
};
// Apply the theme
setOptions(Highcharts.theme);
});
_registerModule(_modules, 'masters/themes/high-contrast-light.src.js', [], function () {
});
})); |
describe('PhoneListCtrl', function() {
beforeEach(module('phonecatApp'));
it('should create "phones" model with 3 phones' , inject(function($controller){
var scope = {},
ctrl = $controller('PhoneListCtrl', {$scope:scope});
expect(scope.phones.length).toBe(3);
}));
}); |
/**
* Created by jiangli on 15/1/6.
*/
"use strict";
var request = require('request');
var crypto = require('crypto');
/**
* [_parseIqiyi 解析爱奇艺视频]
* @param [type] $url [description]
* @return [type] [description]
*/
module.exports = function($url,callback){
$url = $url.replace(/www/,'m'); //这里把地址转换成手机请求的地址,讲www替换成m
var return_data = "";
var options = {
url: $url,
headers: {
'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3'
}
};
request(options, function(er, response,body) {
if (er){
throw er;
}
var body = body;
var result = body.match(/"vid":"(.*?)".*?"vn":(.*?),/g);
if(result.length>0){
var r1 = result[0];
r1 = '{'+r1+'\"blank\"\:0}';
r1 = JSON.parse(r1);
var $vid = r1.vid?r1.vid:'';
var $tvid = r1.tvid?r1.tvid:'';
var $tvname = r1.vn?r1.vn:'';
if($vid!==''&&$tvid!==''){
iqiyiParseFlv2($tvid,$vid,$tvname,callback);
}else{
return_data = "";
}
}
});
return return_data;
}
function md5(str){
var shasum = crypto.createHash('md5');
shasum.update(str);
return shasum.digest('hex');
}
function utf8_encode(argString) {
if (argString === null || typeof argString === 'undefined') {
return '';
}
var string = (argString + ''); // .replace(/\r\n/g, "\n").replace(/\r/g, "\n");
var utftext = '',
start, end, stringl = 0;
start = end = 0;
stringl = string.length;
for (var n = 0; n < stringl; n++) {
var c1 = string.charCodeAt(n);
var enc = null;
if (c1 < 128) {
end++;
} else if (c1 > 127 && c1 < 2048) {
enc = String.fromCharCode(
(c1 >> 6) | 192, (c1 & 63) | 128
);
} else if ((c1 & 0xF800) != 0xD800) {
enc = String.fromCharCode(
(c1 >> 12) | 224, ((c1 >> 6) & 63) | 128, (c1 & 63) | 128
);
} else { // surrogate pairs
if ((c1 & 0xFC00) != 0xD800) {
throw new RangeError('Unmatched trail surrogate at ' + n);
}
var c2 = string.charCodeAt(++n);
if ((c2 & 0xFC00) != 0xDC00) {
throw new RangeError('Unmatched lead surrogate at ' + (n - 1));
}
c1 = ((c1 & 0x3FF) << 10) + (c2 & 0x3FF) + 0x10000;
enc = String.fromCharCode(
(c1 >> 18) | 240, ((c1 >> 12) & 63) | 128, ((c1 >> 6) & 63) | 128, (c1 & 63) | 128
);
}
if (enc !== null) {
if (end > start) {
utftext += string.slice(start, end);
}
utftext += enc;
start = end = n + 1;
}
}
if (end > start) {
utftext += string.slice(start, stringl);
}
return utftext;
};
function calenc($tvId,$enc_key,$deadpara){
return md5($enc_key+$deadpara+$tvId);
}
function calauthKey($tvId,$deadpara){
return md5(""+$deadpara+$tvId);
}
function calmd($t,$fileId){
var $local3 = ")(*&^flash@#$%a";
var $local4 = Math.floor(($t / (600)));
return md5($local4+$local3+$fileId);
}
function getVrsEncodeCode($_arg1){
var $_local6;
var $_local2 = "";
var $_local3 = $_arg1.split('-');
var $_local4 = $_local3.length;
var $_local5 = ($_local4 - 1);
while ($_local5 >= 0) {
$_local6 = getVRSXORCode(parseInt($_local3[(($_local4 - $_local5) - 1)], 16), $_local5);
$_local2 = String.fromCharCode($_local6)+$_local2;
$_local5--;
};
return $_local2;
}
function getVRSXORCode($_arg1, $_arg2){
var $_local3 = ($_arg2 % 3);
if ($_local3 == 1){
return (($_arg1 ^ 121));
};
if ($_local3 == 2){
return (($_arg1 ^ 72));
};
return (($_arg1 ^ 103));
}
/**
* [parseFlv2 解析网站flv格式的视频,第二种方法]
* @param [type] $tvid [description]
* @param [type] $vid [description]
* @return [type] [description]
*/
function iqiyiParseFlv2($tvid,$vid,$tvname,callback){
var $deadpara = 1000;
var $enc_key = "ts56gh";
var $api_url = "http://cache.video.qiyi.com/vms?key=fvip&src=1702633101b340d8917a69cf8a4b8c7c";
$api_url = $api_url+"&tvId="+$tvid+"&vid="+$vid+"&vinfo=1&tm="+$deadpara+"&enc="+calenc($tvid,$enc_key,$deadpara)+"&qyid=08ca8cb480c0384cb5d3db068161f44f&&puid=&authKey="+calauthKey($tvid,$deadpara)+"&tn="+Math.random();
var return_data = "";
request($api_url, function(er, response,body) {
if (er)
return callback(er);
var body = response.body;
var $video_datas = JSON.parse(body);
var $vs = $video_datas.data.vp.tkl[0].vs; //.data.vp.tkl[0].vs
var $time_url = "http://data.video.qiyi.com/t?tn="+Math.random();
request($time_url, function(er, response,body) {
if (er)
return callback(er);
var $time_datas = JSON.parse(body);
var $server_time = $time_datas.t;
var $urls_data = {
'极速':[],
'流畅':[],
'高清':[],
'超清':[],
'720P':[],
'1080P':[],
'4K':[]
},$data = {};
if($vs.length>0){
for(var i=0;i<$vs.length;i++){
var $vsi = $vs[i];
var $fs = $vsi.fs;
$urls_data['seconds'] = $vsi.duration;
for(var j=0;j<$fs.length;j++){
var $val = $fs[j];
var $this_link = $val.l;
var $bid = $vsi.bid;
if($bid == 4 || $bid == 5 || $bid == 10){
$this_link = getVrsEncodeCode($this_link);
}
var $sp = $this_link.split('/');
var $sp_length = $sp.length;
var $fileId = $sp[$sp_length-1].split('.')[0];
var $this_key = calmd($server_time,$fileId);
$this_link = $this_link+'?ran='+$deadpara+'&qyid=08ca8cb480c0384cb5d3db068161f44f&qypid='+$tvid+'_11&retry=1';
var $final_url = "http://data.video.qiyi.com/"+$this_key+"/videos"+$this_link;
if($bid == 96)$urls_data['极速'].push($final_url);
if($bid == 1)$urls_data['流畅'].push($final_url);
if($bid == 2)$urls_data['高清'].push($final_url);
if($bid == 3)$urls_data['超清'].push($final_url);
if($bid == 4)$urls_data['720P'].push($final_url);
if($bid == 5)$urls_data['1080P'].push($final_url);
if($bid == 10)$urls_data['4K'].push($final_url);
}
}
$urls_data['title'] = $tvname;
return callback(null,$urls_data);
}else{
return callback(null,null);
}
});
});
} |
var breadcrumbs=[['-1',"",""],['2',"SOLUTION-WIDE PROPERTIES Reference","topic_0000000000000C16.html"],['2267',"Tlece.Recruitment.Models.RecruitmentPlanning Namespace","topic_0000000000000692.html"],['2680',"UserDto Class","topic_000000000000090A.html"],['2681',"Properties","topic_000000000000090A_props--.html"],['2685',"FirstName Property","topic_000000000000090C.html"]]; |
/*
* Copyright (c) 2015 by Rafael Angel Aznar Aparici (rafaaznar at gmail dot com)
*
* openAUSIAS: The stunning micro-library that helps you to develop easily
* AJAX web applications by using Java and jQuery
* openAUSIAS is distributed under the MIT License (MIT)
* Sources at https://github.com/rafaelaznar/
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
'use strict';
moduloIlustradorJuego.controller('IlustradorJuegoPListController', ['$scope', '$routeParams', 'serverService', '$location',
function ($scope, $routeParams, serverService, $location) {
$scope.visibles = {};
$scope.visibles.id = true;
$scope.visibles.nombre = true;
$scope.visibles.fechaPublicacion = true;
$scope.visibles.numJugadores = true;
$scope.visibles.edad = true;
$scope.visibles.duracion = true;
$scope.visibles.imagen = true;
$scope.ob = "ilustradorJuego";
$scope.op = "plist";
$scope.title = "Listado de Juegos por Ilustrador";
$scope.icon = "/images/I.png";
$scope.neighbourhood = 2;
$scope.id = $routeParams.id_ilustrador;
if (!$routeParams.page) {
$routeParams.page = 1;
}
if (!$routeParams.rpp) {
$routeParams.rpp = 10;
}
$scope.numpage = $routeParams.page;
$scope.rpp = $routeParams.rpp;
$scope.order = "";
$scope.ordervalue = "";
$scope.filter = "id";
$scope.filteroperator = "like";
$scope.filtervalue = "";
$scope.systemfilter = "";
$scope.systemfilteroperator = "";
$scope.systemfiltervalue = "";
$scope.params = "";
$scope.paramsWithoutOrder = "";
$scope.paramsWithoutFilter = "";
$scope.paramsWithoutSystemFilter = "";
if ($routeParams.order && $routeParams.ordervalue) {
$scope.order = $routeParams.order;
$scope.ordervalue = $routeParams.ordervalue;
$scope.orderParams = "&order=" + $routeParams.order + "&ordervalue=" + $routeParams.ordervalue;
$scope.paramsWithoutFilter += $scope.orderParams;
$scope.paramsWithoutSystemFilter += $scope.orderParams;
} else {
$scope.orderParams = "";
}
if ($routeParams.filter && $routeParams.filteroperator && $routeParams.filtervalue) {
$scope.filter = $routeParams.filter;
$scope.filteroperator = $routeParams.filteroperator;
$scope.filtervalue = $routeParams.filtervalue;
$scope.filterParams = "&filter=" + $routeParams.filter + "&filteroperator=" + $routeParams.filteroperator + "&filtervalue=" + $routeParams.filtervalue;
$scope.paramsWithoutOrder += $scope.filterParams;
$scope.paramsWithoutSystemFilter += $scope.filterParams;
} else {
$scope.filterParams = "";
}
if ($routeParams.systemfilter && $routeParams.systemfilteroperator && $routeParams.systemfiltervalue) {
$scope.systemFilterParams = "&systemfilter=" + $routeParams.systemfilter + "&systemfilteroperator=" + $routeParams.systemfilteroperator + "&systemfiltervalue=" + $routeParams.systemfiltervalue;
$scope.paramsWithoutOrder += $scope.systemFilterParams;
$scope.paramsWithoutFilter += $scope.systemFilterParams;
} else {
$scope.systemFilterParams = "";
}
$scope.params = ($scope.orderParams + $scope.filterParams + $scope.systemFilterParams);
$scope.params = $scope.params.replace('&', '?');
serverService.getDataFromPromise(serverService.promise_getSomeIlustrador($scope.ob, $scope.rpp, $scope.numpage, $scope.id, $scope.filterParams, $scope.orderParams, $scope.systemFilterParams)).then(function (data) {
if (data.status != 200) {
$scope.status = "Error en la recepción de datos del servidor";
} else {
$scope.pages = data.message.pages.message;
if (parseInt($scope.numpage) > parseInt($scope.pages))
$scope.numpage = $scope.pages;
$scope.page = data.message.page.message;
//$scope.registers = data.message.registers.message;
// $scope.status = "";
}
});
$scope.getRangeArray = function (lowEnd, highEnd) {
var rangeArray = [];
for (var i = lowEnd; i <= highEnd; i++) {
rangeArray.push(i);
}
return rangeArray;
};
$scope.evaluateMin = function (lowEnd, highEnd) {
return Math.min(lowEnd, highEnd);
};
$scope.evaluateMax = function (lowEnd, highEnd) {
return Math.max(lowEnd, highEnd);
};
$scope.dofilter = function () {
if ($scope.filter != "" && $scope.filteroperator != "" && $scope.filtervalue != "") {
if ($routeParams.order && $routeParams.ordervalue) {
if ($routeParams.systemfilter && $routeParams.systemfilteroperator) {
$location.path($scope.ob + '/' + $scope.op + '/' + $scope.numpage + '/' + $scope.rpp).search('filter', $scope.filter).search('filteroperator', $scope.filteroperator).search('filtervalue', $scope.filtervalue).search('order', $routeParams.order).search('ordervalue', $routeParams.ordervalue).search('systemfilter', $routeParams.systemfilter).search('systemfilteroperator', $routeParams.systemfilteroperator).search('systemfiltervalue', $routeParams.systemfiltervalue);
} else {
$location.path($scope.ob + '/' + $scope.op + '/' + $scope.numpage + '/' + $scope.rpp).search('filter', $scope.filter).search('filteroperator', $scope.filteroperator).search('filtervalue', $scope.filtervalue).search('order', $routeParams.order).search('ordervalue', $routeParams.ordervalue);
}
} else {
$location.path($scope.ob + '/' + $scope.op + '/' + $scope.numpage + '/' + $scope.rpp).search('filter', $scope.filter).search('filteroperator', $scope.filteroperator).search('filtervalue', $scope.filtervalue);
}
}
return false;
};
}]); |
$(document).ready(function () {
//ko.applyBindings($ca.user, $("#divLoginOnPanel-j")[0]);
amplify.subscribe($ca.notification.serverUserAuthenticatedEvent, function () {
$.post("/account/loginonpanel", function (data) {
$('#divMenuLoginOnPanelHolder-j').html(data);
$("#layoutSignOutMenu-j").click(function () {
$ca.user.signOut();
});
});
});
$("#layoutSignInMenu-j, #layoutRegisterMenu-j").click(function () {
$cs.auth.requireAuthentication();
});
$("#layoutSignOutMenu-j").click(function () {
$ca.user.signOut();
});
(function () {
var progressBarDiv = $('<div class="progressbar-centered" style="display:none"><img src="/Content/chesapeakebay/images/progress_indicator.gif" /></div>')
$('body').append(progressBarDiv);
amplify.subscribe($ca.notification.progressOperationBeginEvent, function () {
progressBarDiv.show();
});
amplify.subscribe($ca.notification.progressOperationEndEvent, function () {
progressBarDiv.hide();
});
})();
}); |
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*
* Version: 5.8.0 (2021-05-06)
*/
(function () {
'use strict';
var typeOf = function (x) {
var t = typeof x;
if (x === null) {
return 'null';
} else if (t === 'object' && (Array.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'Array')) {
return 'array';
} else if (t === 'object' && (String.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'String')) {
return 'string';
} else {
return t;
}
};
var isType = function (type) {
return function (value) {
return typeOf(value) === type;
};
};
var isSimpleType = function (type) {
return function (value) {
return typeof value === type;
};
};
var eq = function (t) {
return function (a) {
return t === a;
};
};
var isString = isType('string');
var isObject = isType('object');
var isArray = isType('array');
var isBoolean = isSimpleType('boolean');
var isUndefined = eq(undefined);
var isNullable = function (a) {
return a === null || a === undefined;
};
var isNonNullable = function (a) {
return !isNullable(a);
};
var isFunction = isSimpleType('function');
var isNumber = isSimpleType('number');
var noop = function () {
};
var compose = function (fa, fb) {
return function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return fa(fb.apply(null, args));
};
};
var compose1 = function (fbc, fab) {
return function (a) {
return fbc(fab(a));
};
};
var constant = function (value) {
return function () {
return value;
};
};
var identity = function (x) {
return x;
};
function curry(fn) {
var initialArgs = [];
for (var _i = 1; _i < arguments.length; _i++) {
initialArgs[_i - 1] = arguments[_i];
}
return function () {
var restArgs = [];
for (var _i = 0; _i < arguments.length; _i++) {
restArgs[_i] = arguments[_i];
}
var all = initialArgs.concat(restArgs);
return fn.apply(null, all);
};
}
var not = function (f) {
return function (t) {
return !f(t);
};
};
var die = function (msg) {
return function () {
throw new Error(msg);
};
};
var never = constant(false);
var always = constant(true);
var none = function () {
return NONE;
};
var NONE = function () {
var eq = function (o) {
return o.isNone();
};
var call = function (thunk) {
return thunk();
};
var id = function (n) {
return n;
};
var me = {
fold: function (n, _s) {
return n();
},
is: never,
isSome: never,
isNone: always,
getOr: id,
getOrThunk: call,
getOrDie: function (msg) {
throw new Error(msg || 'error: getOrDie called on none.');
},
getOrNull: constant(null),
getOrUndefined: constant(undefined),
or: id,
orThunk: call,
map: none,
each: noop,
bind: none,
exists: never,
forall: always,
filter: none,
equals: eq,
equals_: eq,
toArray: function () {
return [];
},
toString: constant('none()')
};
return me;
}();
var some = function (a) {
var constant_a = constant(a);
var self = function () {
return me;
};
var bind = function (f) {
return f(a);
};
var me = {
fold: function (n, s) {
return s(a);
},
is: function (v) {
return a === v;
},
isSome: always,
isNone: never,
getOr: constant_a,
getOrThunk: constant_a,
getOrDie: constant_a,
getOrNull: constant_a,
getOrUndefined: constant_a,
or: self,
orThunk: self,
map: function (f) {
return some(f(a));
},
each: function (f) {
f(a);
},
bind: bind,
exists: bind,
forall: bind,
filter: function (f) {
return f(a) ? me : NONE;
},
toArray: function () {
return [a];
},
toString: function () {
return 'some(' + a + ')';
},
equals: function (o) {
return o.is(a);
},
equals_: function (o, elementEq) {
return o.fold(never, function (b) {
return elementEq(a, b);
});
}
};
return me;
};
var from = function (value) {
return value === null || value === undefined ? NONE : some(value);
};
var Optional = {
some: some,
none: none,
from: from
};
var nativeSlice = Array.prototype.slice;
var nativeIndexOf = Array.prototype.indexOf;
var nativePush = Array.prototype.push;
var rawIndexOf = function (ts, t) {
return nativeIndexOf.call(ts, t);
};
var contains = function (xs, x) {
return rawIndexOf(xs, x) > -1;
};
var exists = function (xs, pred) {
for (var i = 0, len = xs.length; i < len; i++) {
var x = xs[i];
if (pred(x, i)) {
return true;
}
}
return false;
};
var range = function (num, f) {
var r = [];
for (var i = 0; i < num; i++) {
r.push(f(i));
}
return r;
};
var map = function (xs, f) {
var len = xs.length;
var r = new Array(len);
for (var i = 0; i < len; i++) {
var x = xs[i];
r[i] = f(x, i);
}
return r;
};
var each = function (xs, f) {
for (var i = 0, len = xs.length; i < len; i++) {
var x = xs[i];
f(x, i);
}
};
var eachr = function (xs, f) {
for (var i = xs.length - 1; i >= 0; i--) {
var x = xs[i];
f(x, i);
}
};
var partition = function (xs, pred) {
var pass = [];
var fail = [];
for (var i = 0, len = xs.length; i < len; i++) {
var x = xs[i];
var arr = pred(x, i) ? pass : fail;
arr.push(x);
}
return {
pass: pass,
fail: fail
};
};
var filter = function (xs, pred) {
var r = [];
for (var i = 0, len = xs.length; i < len; i++) {
var x = xs[i];
if (pred(x, i)) {
r.push(x);
}
}
return r;
};
var foldr = function (xs, f, acc) {
eachr(xs, function (x) {
acc = f(acc, x);
});
return acc;
};
var foldl = function (xs, f, acc) {
each(xs, function (x) {
acc = f(acc, x);
});
return acc;
};
var findUntil = function (xs, pred, until) {
for (var i = 0, len = xs.length; i < len; i++) {
var x = xs[i];
if (pred(x, i)) {
return Optional.some(x);
} else if (until(x, i)) {
break;
}
}
return Optional.none();
};
var find = function (xs, pred) {
return findUntil(xs, pred, never);
};
var findIndex = function (xs, pred) {
for (var i = 0, len = xs.length; i < len; i++) {
var x = xs[i];
if (pred(x, i)) {
return Optional.some(i);
}
}
return Optional.none();
};
var flatten = function (xs) {
var r = [];
for (var 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;
};
var bind = function (xs, f) {
return flatten(map(xs, f));
};
var forall = function (xs, pred) {
for (var i = 0, len = xs.length; i < len; ++i) {
var x = xs[i];
if (pred(x, i) !== true) {
return false;
}
}
return true;
};
var reverse = function (xs) {
var r = nativeSlice.call(xs, 0);
r.reverse();
return r;
};
var mapToObject = function (xs, f) {
var r = {};
for (var i = 0, len = xs.length; i < len; i++) {
var x = xs[i];
r[String(x)] = f(x, i);
}
return r;
};
var pure = function (x) {
return [x];
};
var sort = function (xs, comparator) {
var copy = nativeSlice.call(xs, 0);
copy.sort(comparator);
return copy;
};
var get = function (xs, i) {
return i >= 0 && i < xs.length ? Optional.some(xs[i]) : Optional.none();
};
var head = function (xs) {
return get(xs, 0);
};
var last = function (xs) {
return get(xs, xs.length - 1);
};
var findMap = function (arr, f) {
for (var i = 0; i < arr.length; i++) {
var r = f(arr[i], i);
if (r.isSome()) {
return r;
}
}
return Optional.none();
};
var __assign = function () {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s)
if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
function __spreadArrays() {
for (var s = 0, i = 0, il = arguments.length; i < il; i++)
s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
}
var cached = function (f) {
var called = false;
var r;
return function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
if (!called) {
called = true;
r = f.apply(null, args);
}
return r;
};
};
var DeviceType = function (os, browser, userAgent, mediaMatch) {
var isiPad = os.isiOS() && /ipad/i.test(userAgent) === true;
var isiPhone = os.isiOS() && !isiPad;
var isMobile = os.isiOS() || os.isAndroid();
var isTouch = isMobile || mediaMatch('(pointer:coarse)');
var isTablet = isiPad || !isiPhone && isMobile && mediaMatch('(min-device-width:768px)');
var isPhone = isiPhone || isMobile && !isTablet;
var iOSwebview = browser.isSafari() && os.isiOS() && /safari/i.test(userAgent) === false;
var isDesktop = !isPhone && !isTablet && !iOSwebview;
return {
isiPad: constant(isiPad),
isiPhone: constant(isiPhone),
isTablet: constant(isTablet),
isPhone: constant(isPhone),
isTouch: constant(isTouch),
isAndroid: os.isAndroid,
isiOS: os.isiOS,
isWebView: constant(iOSwebview),
isDesktop: constant(isDesktop)
};
};
var firstMatch = function (regexes, s) {
for (var i = 0; i < regexes.length; i++) {
var x = regexes[i];
if (x.test(s)) {
return x;
}
}
return undefined;
};
var find$1 = function (regexes, agent) {
var r = firstMatch(regexes, agent);
if (!r) {
return {
major: 0,
minor: 0
};
}
var group = function (i) {
return Number(agent.replace(r, '$' + i));
};
return nu(group(1), group(2));
};
var detect = function (versionRegexes, agent) {
var cleanedAgent = String(agent).toLowerCase();
if (versionRegexes.length === 0) {
return unknown();
}
return find$1(versionRegexes, cleanedAgent);
};
var unknown = function () {
return nu(0, 0);
};
var nu = function (major, minor) {
return {
major: major,
minor: minor
};
};
var Version = {
nu: nu,
detect: detect,
unknown: unknown
};
var detect$1 = function (candidates, userAgent) {
var agent = String(userAgent).toLowerCase();
return find(candidates, function (candidate) {
return candidate.search(agent);
});
};
var detectBrowser = function (browsers, userAgent) {
return detect$1(browsers, userAgent).map(function (browser) {
var version = Version.detect(browser.versionRegexes, userAgent);
return {
current: browser.name,
version: version
};
});
};
var detectOs = function (oses, userAgent) {
return detect$1(oses, userAgent).map(function (os) {
var version = Version.detect(os.versionRegexes, userAgent);
return {
current: os.name,
version: version
};
});
};
var UaString = {
detectBrowser: detectBrowser,
detectOs: detectOs
};
var checkRange = function (str, substr, start) {
return substr === '' || str.length >= substr.length && str.substr(start, start + substr.length) === substr;
};
var contains$1 = function (str, substr) {
return str.indexOf(substr) !== -1;
};
var startsWith = function (str, prefix) {
return checkRange(str, prefix, 0);
};
var endsWith = function (str, suffix) {
return checkRange(str, suffix, str.length - suffix.length);
};
var blank = function (r) {
return function (s) {
return s.replace(r, '');
};
};
var trim = blank(/^\s+|\s+$/g);
var isNotEmpty = function (s) {
return s.length > 0;
};
var normalVersionRegex = /.*?version\/\ ?([0-9]+)\.([0-9]+).*/;
var checkContains = function (target) {
return function (uastring) {
return contains$1(uastring, target);
};
};
var browsers = [
{
name: 'Edge',
versionRegexes: [/.*?edge\/ ?([0-9]+)\.([0-9]+)$/],
search: function (uastring) {
return contains$1(uastring, 'edge/') && contains$1(uastring, 'chrome') && contains$1(uastring, 'safari') && contains$1(uastring, 'applewebkit');
}
},
{
name: 'Chrome',
versionRegexes: [
/.*?chrome\/([0-9]+)\.([0-9]+).*/,
normalVersionRegex
],
search: function (uastring) {
return contains$1(uastring, 'chrome') && !contains$1(uastring, 'chromeframe');
}
},
{
name: 'IE',
versionRegexes: [
/.*?msie\ ?([0-9]+)\.([0-9]+).*/,
/.*?rv:([0-9]+)\.([0-9]+).*/
],
search: function (uastring) {
return contains$1(uastring, 'msie') || contains$1(uastring, 'trident');
}
},
{
name: 'Opera',
versionRegexes: [
normalVersionRegex,
/.*?opera\/([0-9]+)\.([0-9]+).*/
],
search: checkContains('opera')
},
{
name: 'Firefox',
versionRegexes: [/.*?firefox\/\ ?([0-9]+)\.([0-9]+).*/],
search: checkContains('firefox')
},
{
name: 'Safari',
versionRegexes: [
normalVersionRegex,
/.*?cpu os ([0-9]+)_([0-9]+).*/
],
search: function (uastring) {
return (contains$1(uastring, 'safari') || contains$1(uastring, 'mobile/')) && contains$1(uastring, 'applewebkit');
}
}
];
var oses = [
{
name: 'Windows',
search: checkContains('win'),
versionRegexes: [/.*?windows\ nt\ ?([0-9]+)\.([0-9]+).*/]
},
{
name: 'iOS',
search: function (uastring) {
return contains$1(uastring, 'iphone') || contains$1(uastring, 'ipad');
},
versionRegexes: [
/.*?version\/\ ?([0-9]+)\.([0-9]+).*/,
/.*cpu os ([0-9]+)_([0-9]+).*/,
/.*cpu iphone os ([0-9]+)_([0-9]+).*/
]
},
{
name: 'Android',
search: checkContains('android'),
versionRegexes: [/.*?android\ ?([0-9]+)\.([0-9]+).*/]
},
{
name: 'OSX',
search: checkContains('mac os x'),
versionRegexes: [/.*?mac\ os\ x\ ?([0-9]+)_([0-9]+).*/]
},
{
name: 'Linux',
search: checkContains('linux'),
versionRegexes: []
},
{
name: 'Solaris',
search: checkContains('sunos'),
versionRegexes: []
},
{
name: 'FreeBSD',
search: checkContains('freebsd'),
versionRegexes: []
},
{
name: 'ChromeOS',
search: checkContains('cros'),
versionRegexes: [/.*?chrome\/([0-9]+)\.([0-9]+).*/]
}
];
var PlatformInfo = {
browsers: constant(browsers),
oses: constant(oses)
};
var edge = 'Edge';
var chrome = 'Chrome';
var ie = 'IE';
var opera = 'Opera';
var firefox = 'Firefox';
var safari = 'Safari';
var unknown$1 = function () {
return nu$1({
current: undefined,
version: Version.unknown()
});
};
var nu$1 = function (info) {
var current = info.current;
var version = info.version;
var isBrowser = function (name) {
return function () {
return current === name;
};
};
return {
current: current,
version: version,
isEdge: isBrowser(edge),
isChrome: isBrowser(chrome),
isIE: isBrowser(ie),
isOpera: isBrowser(opera),
isFirefox: isBrowser(firefox),
isSafari: isBrowser(safari)
};
};
var Browser = {
unknown: unknown$1,
nu: nu$1,
edge: constant(edge),
chrome: constant(chrome),
ie: constant(ie),
opera: constant(opera),
firefox: constant(firefox),
safari: constant(safari)
};
var windows = 'Windows';
var ios = 'iOS';
var android = 'Android';
var linux = 'Linux';
var osx = 'OSX';
var solaris = 'Solaris';
var freebsd = 'FreeBSD';
var chromeos = 'ChromeOS';
var unknown$2 = function () {
return nu$2({
current: undefined,
version: Version.unknown()
});
};
var nu$2 = function (info) {
var current = info.current;
var version = info.version;
var isOS = function (name) {
return function () {
return current === name;
};
};
return {
current: current,
version: version,
isWindows: isOS(windows),
isiOS: isOS(ios),
isAndroid: isOS(android),
isOSX: isOS(osx),
isLinux: isOS(linux),
isSolaris: isOS(solaris),
isFreeBSD: isOS(freebsd),
isChromeOS: isOS(chromeos)
};
};
var OperatingSystem = {
unknown: unknown$2,
nu: nu$2,
windows: constant(windows),
ios: constant(ios),
android: constant(android),
linux: constant(linux),
osx: constant(osx),
solaris: constant(solaris),
freebsd: constant(freebsd),
chromeos: constant(chromeos)
};
var detect$2 = function (userAgent, mediaMatch) {
var browsers = PlatformInfo.browsers();
var oses = PlatformInfo.oses();
var browser = UaString.detectBrowser(browsers, userAgent).fold(Browser.unknown, Browser.nu);
var os = UaString.detectOs(oses, userAgent).fold(OperatingSystem.unknown, OperatingSystem.nu);
var deviceType = DeviceType(os, browser, userAgent, mediaMatch);
return {
browser: browser,
os: os,
deviceType: deviceType
};
};
var PlatformDetection = { detect: detect$2 };
var mediaMatch = function (query) {
return window.matchMedia(query).matches;
};
var platform = cached(function () {
return PlatformDetection.detect(navigator.userAgent, mediaMatch);
});
var detect$3 = function () {
return platform();
};
var compareDocumentPosition = function (a, b, match) {
return (a.compareDocumentPosition(b) & match) !== 0;
};
var documentPositionContainedBy = function (a, b) {
return compareDocumentPosition(a, b, Node.DOCUMENT_POSITION_CONTAINED_BY);
};
var COMMENT = 8;
var DOCUMENT = 9;
var DOCUMENT_FRAGMENT = 11;
var ELEMENT = 1;
var TEXT = 3;
var fromHtml = function (html, scope) {
var doc = scope || document;
var div = doc.createElement('div');
div.innerHTML = html;
if (!div.hasChildNodes() || div.childNodes.length > 1) {
console.error('HTML does not have a single root node', html);
throw new Error('HTML must have a single root node');
}
return fromDom(div.childNodes[0]);
};
var fromTag = function (tag, scope) {
var doc = scope || document;
var node = doc.createElement(tag);
return fromDom(node);
};
var fromText = function (text, scope) {
var doc = scope || document;
var node = doc.createTextNode(text);
return fromDom(node);
};
var fromDom = function (node) {
if (node === null || node === undefined) {
throw new Error('Node cannot be null or undefined');
}
return { dom: node };
};
var fromPoint = function (docElm, x, y) {
return Optional.from(docElm.dom.elementFromPoint(x, y)).map(fromDom);
};
var SugarElement = {
fromHtml: fromHtml,
fromTag: fromTag,
fromText: fromText,
fromDom: fromDom,
fromPoint: fromPoint
};
var is = function (element, selector) {
var dom = element.dom;
if (dom.nodeType !== ELEMENT) {
return false;
} else {
var 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');
}
}
};
var bypassSelector = function (dom) {
return dom.nodeType !== ELEMENT && dom.nodeType !== DOCUMENT && dom.nodeType !== DOCUMENT_FRAGMENT || dom.childElementCount === 0;
};
var all = function (selector, scope) {
var base = scope === undefined ? document : scope.dom;
return bypassSelector(base) ? [] : map(base.querySelectorAll(selector), SugarElement.fromDom);
};
var one = function (selector, scope) {
var base = scope === undefined ? document : scope.dom;
return bypassSelector(base) ? Optional.none() : Optional.from(base.querySelector(selector)).map(SugarElement.fromDom);
};
var eq$1 = function (e1, e2) {
return e1.dom === e2.dom;
};
var regularContains = function (e1, e2) {
var d1 = e1.dom;
var d2 = e2.dom;
return d1 === d2 ? false : d1.contains(d2);
};
var ieContains = function (e1, e2) {
return documentPositionContainedBy(e1.dom, e2.dom);
};
var contains$2 = function (e1, e2) {
return detect$3().browser.isIE() ? ieContains(e1, e2) : regularContains(e1, e2);
};
var is$1 = is;
var keys = Object.keys;
var hasOwnProperty = Object.hasOwnProperty;
var each$1 = function (obj, f) {
var props = keys(obj);
for (var k = 0, len = props.length; k < len; k++) {
var i = props[k];
var x = obj[i];
f(x, i);
}
};
var map$1 = function (obj, f) {
return tupleMap(obj, function (x, i) {
return {
k: i,
v: f(x, i)
};
});
};
var tupleMap = function (obj, f) {
var r = {};
each$1(obj, function (x, i) {
var tuple = f(x, i);
r[tuple.k] = tuple.v;
});
return r;
};
var objAcc = function (r) {
return function (x, i) {
r[i] = x;
};
};
var internalFilter = function (obj, pred, onTrue, onFalse) {
var r = {};
each$1(obj, function (x, i) {
(pred(x, i) ? onTrue : onFalse)(x, i);
});
return r;
};
var filter$1 = function (obj, pred) {
var t = {};
internalFilter(obj, pred, objAcc(t), noop);
return t;
};
var mapToArray = function (obj, f) {
var r = [];
each$1(obj, function (value, name) {
r.push(f(value, name));
});
return r;
};
var values = function (obj) {
return mapToArray(obj, function (v) {
return v;
});
};
var size = function (obj) {
return keys(obj).length;
};
var get$1 = function (obj, key) {
return has(obj, key) ? Optional.from(obj[key]) : Optional.none();
};
var has = function (obj, key) {
return hasOwnProperty.call(obj, key);
};
var hasNonNullableKey = function (obj, key) {
return has(obj, key) && obj[key] !== undefined && obj[key] !== null;
};
var isEmpty = function (r) {
for (var x in r) {
if (hasOwnProperty.call(r, x)) {
return false;
}
}
return true;
};
var validSectionList = [
'tfoot',
'thead',
'tbody',
'colgroup'
];
var isValidSection = function (parentName) {
return contains(validSectionList, parentName);
};
var grid = function (rows, columns) {
return {
rows: rows,
columns: columns
};
};
var address = function (row, column) {
return {
row: row,
column: column
};
};
var detail = function (element, rowspan, colspan) {
return {
element: element,
rowspan: rowspan,
colspan: colspan
};
};
var detailnew = function (element, rowspan, colspan, isNew) {
return {
element: element,
rowspan: rowspan,
colspan: colspan,
isNew: isNew
};
};
var extended = function (element, rowspan, colspan, row, column, isLocked) {
return {
element: element,
rowspan: rowspan,
colspan: colspan,
row: row,
column: column,
isLocked: isLocked
};
};
var rowdata = function (element, cells, section) {
return {
element: element,
cells: cells,
section: section
};
};
var elementnew = function (element, isNew, isLocked) {
return {
element: element,
isNew: isNew,
isLocked: isLocked
};
};
var rowdatanew = function (element, cells, section, isNew) {
return {
element: element,
cells: cells,
section: section,
isNew: isNew
};
};
var rowcells = function (cells, section) {
return {
cells: cells,
section: section
};
};
var rowdetails = function (details, section) {
return {
details: details,
section: section
};
};
var bounds = function (startRow, startCol, finishRow, finishCol) {
return {
startRow: startRow,
startCol: startCol,
finishRow: finishRow,
finishCol: finishCol
};
};
var columnext = function (element, colspan, column) {
return {
element: element,
colspan: colspan,
column: column
};
};
var Global = typeof window !== 'undefined' ? window : Function('return this;')();
var name = function (element) {
var r = element.dom.nodeName;
return r.toLowerCase();
};
var type = function (element) {
return element.dom.nodeType;
};
var isType$1 = function (t) {
return function (element) {
return type(element) === t;
};
};
var isComment = function (element) {
return type(element) === COMMENT || name(element) === '#comment';
};
var isElement = isType$1(ELEMENT);
var isText = isType$1(TEXT);
var isDocument = isType$1(DOCUMENT);
var isDocumentFragment = isType$1(DOCUMENT_FRAGMENT);
var isTag = function (tag) {
return function (e) {
return isElement(e) && name(e) === tag;
};
};
var owner = function (element) {
return SugarElement.fromDom(element.dom.ownerDocument);
};
var documentOrOwner = function (dos) {
return isDocument(dos) ? dos : owner(dos);
};
var defaultView = function (element) {
return SugarElement.fromDom(documentOrOwner(element).dom.defaultView);
};
var parent = function (element) {
return Optional.from(element.dom.parentNode).map(SugarElement.fromDom);
};
var parents = function (element, isRoot) {
var stop = isFunction(isRoot) ? isRoot : never;
var dom = element.dom;
var ret = [];
while (dom.parentNode !== null && dom.parentNode !== undefined) {
var rawParent = dom.parentNode;
var p = SugarElement.fromDom(rawParent);
ret.push(p);
if (stop(p) === true) {
break;
} else {
dom = rawParent;
}
}
return ret;
};
var offsetParent = function (element) {
return Optional.from(element.dom.offsetParent).map(SugarElement.fromDom);
};
var prevSibling = function (element) {
return Optional.from(element.dom.previousSibling).map(SugarElement.fromDom);
};
var nextSibling = function (element) {
return Optional.from(element.dom.nextSibling).map(SugarElement.fromDom);
};
var children = function (element) {
return map(element.dom.childNodes, SugarElement.fromDom);
};
var child = function (element, index) {
var cs = element.dom.childNodes;
return Optional.from(cs[index]).map(SugarElement.fromDom);
};
var firstChild = function (element) {
return child(element, 0);
};
var isShadowRoot = function (dos) {
return isDocumentFragment(dos) && isNonNullable(dos.dom.host);
};
var supported = isFunction(Element.prototype.attachShadow) && isFunction(Node.prototype.getRootNode);
var isSupported = constant(supported);
var getRootNode = supported ? function (e) {
return SugarElement.fromDom(e.dom.getRootNode());
} : documentOrOwner;
var getShadowRoot = function (e) {
var r = getRootNode(e);
return isShadowRoot(r) ? Optional.some(r) : Optional.none();
};
var getShadowHost = function (e) {
return SugarElement.fromDom(e.dom.host);
};
var getOriginalEventTarget = function (event) {
if (isSupported() && isNonNullable(event.target)) {
var el = SugarElement.fromDom(event.target);
if (isElement(el) && isOpenShadowHost(el)) {
if (event.composed && event.composedPath) {
var composedPath = event.composedPath();
if (composedPath) {
return head(composedPath);
}
}
}
}
return Optional.from(event.target);
};
var isOpenShadowHost = function (element) {
return isNonNullable(element.dom.shadowRoot);
};
var inBody = function (element) {
var dom = isText(element) ? element.dom.parentNode : element.dom;
if (dom === undefined || dom === null || dom.ownerDocument === null) {
return false;
}
var doc = dom.ownerDocument;
return getShadowRoot(SugarElement.fromDom(dom)).fold(function () {
return doc.body.contains(dom);
}, compose1(inBody, getShadowHost));
};
var body = function () {
return getBody(SugarElement.fromDom(document));
};
var getBody = function (doc) {
var b = doc.dom.body;
if (b === null || b === undefined) {
throw new Error('Body is not available yet');
}
return SugarElement.fromDom(b);
};
var ancestors = function (scope, predicate, isRoot) {
return filter(parents(scope, isRoot), predicate);
};
var children$1 = function (scope, predicate) {
return filter(children(scope), predicate);
};
var descendants = function (scope, predicate) {
var result = [];
each(children(scope), function (x) {
if (predicate(x)) {
result = result.concat([x]);
}
result = result.concat(descendants(x, predicate));
});
return result;
};
var ancestors$1 = function (scope, selector, isRoot) {
return ancestors(scope, function (e) {
return is(e, selector);
}, isRoot);
};
var children$2 = function (scope, selector) {
return children$1(scope, function (e) {
return is(e, selector);
});
};
var descendants$1 = function (scope, selector) {
return all(selector, scope);
};
function 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);
}
}
var ancestor = function (scope, predicate, isRoot) {
var element = scope.dom;
var stop = isFunction(isRoot) ? isRoot : never;
while (element.parentNode) {
element = element.parentNode;
var el = SugarElement.fromDom(element);
if (predicate(el)) {
return Optional.some(el);
} else if (stop(el)) {
break;
}
}
return Optional.none();
};
var closest = function (scope, predicate, isRoot) {
var is = function (s, test) {
return test(s);
};
return ClosestOrAncestor(is, ancestor, scope, predicate, isRoot);
};
var child$1 = function (scope, predicate) {
var pred = function (node) {
return predicate(SugarElement.fromDom(node));
};
var result = find(scope.dom.childNodes, pred);
return result.map(SugarElement.fromDom);
};
var descendant = function (scope, predicate) {
var descend = function (node) {
for (var i = 0; i < node.childNodes.length; i++) {
var child_1 = SugarElement.fromDom(node.childNodes[i]);
if (predicate(child_1)) {
return Optional.some(child_1);
}
var res = descend(node.childNodes[i]);
if (res.isSome()) {
return res;
}
}
return Optional.none();
};
return descend(scope.dom);
};
var ancestor$1 = function (scope, selector, isRoot) {
return ancestor(scope, function (e) {
return is(e, selector);
}, isRoot);
};
var child$2 = function (scope, selector) {
return child$1(scope, function (e) {
return is(e, selector);
});
};
var descendant$1 = function (scope, selector) {
return one(selector, scope);
};
var closest$1 = function (scope, selector, isRoot) {
var is$1 = function (element, selector) {
return is(element, selector);
};
return ClosestOrAncestor(is$1, ancestor$1, scope, selector, isRoot);
};
var rawSet = function (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');
}
};
var set = function (element, key, value) {
rawSet(element.dom, key, value);
};
var setAll = function (element, attrs) {
var dom = element.dom;
each$1(attrs, function (v, k) {
rawSet(dom, k, v);
});
};
var get$2 = function (element, key) {
var v = element.dom.getAttribute(key);
return v === null ? undefined : v;
};
var getOpt = function (element, key) {
return Optional.from(get$2(element, key));
};
var remove = function (element, key) {
element.dom.removeAttribute(key);
};
var clone = function (element) {
return foldl(element.dom.attributes, function (acc, attr) {
acc[attr.name] = attr.value;
return acc;
}, {});
};
var isSupported$1 = function (dom) {
return dom.style !== undefined && isFunction(dom.style.getPropertyValue);
};
var internalSet = function (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$1(dom)) {
dom.style.setProperty(property, value);
}
};
var internalRemove = function (dom, property) {
if (isSupported$1(dom)) {
dom.style.removeProperty(property);
}
};
var set$1 = function (element, property, value) {
var dom = element.dom;
internalSet(dom, property, value);
};
var setAll$1 = function (element, css) {
var dom = element.dom;
each$1(css, function (v, k) {
internalSet(dom, k, v);
});
};
var get$3 = function (element, property) {
var dom = element.dom;
var styles = window.getComputedStyle(dom);
var r = styles.getPropertyValue(property);
return r === '' && !inBody(element) ? getUnsafeProperty(dom, property) : r;
};
var getUnsafeProperty = function (dom, property) {
return isSupported$1(dom) ? dom.style.getPropertyValue(property) : '';
};
var getRaw = function (element, property) {
var dom = element.dom;
var raw = getUnsafeProperty(dom, property);
return Optional.from(raw).filter(function (r) {
return r.length > 0;
});
};
var remove$1 = function (element, property) {
var dom = element.dom;
internalRemove(dom, property);
if (getOpt(element, 'style').map(trim).is('')) {
remove(element, 'style');
}
};
var copy = function (source, target) {
var sourceDom = source.dom;
var targetDom = target.dom;
if (isSupported$1(sourceDom) && isSupported$1(targetDom)) {
targetDom.style.cssText = sourceDom.style.cssText;
}
};
var getAttrValue = function (cell, name, fallback) {
if (fallback === void 0) {
fallback = 0;
}
return getOpt(cell, name).map(function (value) {
return parseInt(value, 10);
}).getOr(fallback);
};
var getSpan = function (cell, type) {
return getAttrValue(cell, type, 1);
};
var hasColspan = function (cell) {
return getSpan(cell, 'colspan') > 1;
};
var hasRowspan = function (cell) {
return getSpan(cell, 'rowspan') > 1;
};
var getCssValue = function (element, property) {
return parseInt(get$3(element, property), 10);
};
var minWidth = constant(10);
var minHeight = constant(10);
var firstLayer = function (scope, selector) {
return filterFirstLayer(scope, selector, always);
};
var filterFirstLayer = function (scope, selector, predicate) {
return bind(children(scope), function (x) {
if (is(x, selector)) {
return predicate(x) ? [x] : [];
} else {
return filterFirstLayer(x, selector, predicate);
}
});
};
var lookup = function (tags, element, isRoot) {
if (isRoot === void 0) {
isRoot = never;
}
if (isRoot(element)) {
return Optional.none();
}
if (contains(tags, name(element))) {
return Optional.some(element);
}
var isRootOrUpperTable = function (elm) {
return is(elm, 'table') || isRoot(elm);
};
return ancestor$1(element, tags.join(','), isRootOrUpperTable);
};
var cell = function (element, isRoot) {
return lookup([
'td',
'th'
], element, isRoot);
};
var cells = function (ancestor) {
return firstLayer(ancestor, 'th,td');
};
var columns = function (ancestor) {
if (is(ancestor, 'colgroup')) {
return children$2(ancestor, 'col');
} else {
return bind(columnGroups(ancestor), function (columnGroup) {
return children$2(columnGroup, 'col');
});
}
};
var table = function (element, isRoot) {
return closest$1(element, 'table', isRoot);
};
var rows = function (ancestor) {
return firstLayer(ancestor, 'tr');
};
var columnGroups = function (ancestor) {
return table(ancestor).fold(constant([]), function (table) {
return children$2(table, 'colgroup');
});
};
var fromRowsOrColGroups = function (elems, getSection) {
return map(elems, function (row) {
if (name(row) === 'colgroup') {
var cells$1 = map(columns(row), function (column) {
var colspan = getAttrValue(column, 'span', 1);
return detail(column, 1, colspan);
});
return rowdata(row, cells$1, 'colgroup');
} else {
var cells$1 = map(cells(row), function (cell) {
var rowspan = getAttrValue(cell, 'rowspan', 1);
var colspan = getAttrValue(cell, 'colspan', 1);
return detail(cell, rowspan, colspan);
});
return rowdata(row, cells$1, getSection(row));
}
});
};
var getParentSection = function (group) {
return parent(group).map(function (parent) {
var parentName = name(parent);
return isValidSection(parentName) ? parentName : 'tbody';
}).getOr('tbody');
};
var fromTable = function (table) {
var rows$1 = rows(table);
var columnGroups$1 = columnGroups(table);
var elems = __spreadArrays(columnGroups$1, rows$1);
return fromRowsOrColGroups(elems, getParentSection);
};
var fromPastedRows = function (elems, section) {
return fromRowsOrColGroups(elems, function () {
return section;
});
};
var addCells = function (gridRow, index, cells) {
var existingCells = gridRow.cells;
var before = existingCells.slice(0, index);
var after = existingCells.slice(index);
var newCells = before.concat(cells).concat(after);
return setCells(gridRow, newCells);
};
var addCell = function (gridRow, index, cell) {
return addCells(gridRow, index, [cell]);
};
var mutateCell = function (gridRow, index, cell) {
var cells = gridRow.cells;
cells[index] = cell;
};
var setCells = function (gridRow, cells) {
return rowcells(cells, gridRow.section);
};
var mapCells = function (gridRow, f) {
var cells = gridRow.cells;
var r = map(cells, f);
return rowcells(r, gridRow.section);
};
var getCell = function (gridRow, index) {
return gridRow.cells[index];
};
var getCellElement = function (gridRow, index) {
return getCell(gridRow, index).element;
};
var cellLength = function (gridRow) {
return gridRow.cells.length;
};
var extractGridDetails = function (grid) {
var result = partition(grid, function (row) {
return row.section === 'colgroup';
});
return {
rows: result.fail,
cols: result.pass
};
};
var LOCKED_COL_ATTR = 'data-snooker-locked-cols';
var getLockedColumnsFromTable = function (table) {
return getOpt(table, LOCKED_COL_ATTR).bind(function (lockedColStr) {
return Optional.from(lockedColStr.match(/\d+/g));
}).map(function (lockedCols) {
return mapToObject(lockedCols, always);
});
};
var getLockedColumnsFromGrid = function (grid) {
var locked = foldl(extractGridDetails(grid).rows, function (acc, row) {
each(row.cells, function (cell, idx) {
if (cell.isLocked) {
acc[idx] = true;
}
});
return acc;
}, {});
var lockedArr = mapToArray(locked, function (_val, key) {
return parseInt(key, 10);
});
return sort(lockedArr);
};
var key = function (row, column) {
return row + ',' + column;
};
var getAt = function (warehouse, row, column) {
var raw = warehouse.access[key(row, column)];
return raw !== undefined ? Optional.some(raw) : Optional.none();
};
var findItem = function (warehouse, item, comparator) {
var filtered = filterItems(warehouse, function (detail) {
return comparator(item, detail.element);
});
return filtered.length > 0 ? Optional.some(filtered[0]) : Optional.none();
};
var filterItems = function (warehouse, predicate) {
var all = bind(warehouse.all, function (r) {
return r.cells;
});
return filter(all, predicate);
};
var generateColumns = function (rowData) {
var columnsGroup = {};
var index = 0;
each(rowData.cells, function (column) {
var colspan = column.colspan;
range(colspan, function (columnIndex) {
var colIndex = index + columnIndex;
columnsGroup[colIndex] = columnext(column.element, colspan, colIndex);
});
index += colspan;
});
return columnsGroup;
};
var generate = function (list) {
var access = {};
var cells = [];
var columns = {};
var tableOpt = head(list).map(function (rowData) {
return rowData.element;
}).bind(table);
var lockedColumns = tableOpt.bind(getLockedColumnsFromTable).getOr({});
var maxRows = 0;
var maxColumns = 0;
var rowCount = 0;
each(list, function (rowData) {
if (rowData.section === 'colgroup') {
columns = generateColumns(rowData);
} else {
var currentRow_1 = [];
each(rowData.cells, function (rowCell) {
var start = 0;
while (access[key(rowCount, start)] !== undefined) {
start++;
}
var isLocked = hasNonNullableKey(lockedColumns, start.toString());
var current = extended(rowCell.element, rowCell.rowspan, rowCell.colspan, rowCount, start, isLocked);
for (var occupiedColumnPosition = 0; occupiedColumnPosition < rowCell.colspan; occupiedColumnPosition++) {
for (var occupiedRowPosition = 0; occupiedRowPosition < rowCell.rowspan; occupiedRowPosition++) {
var rowPosition = rowCount + occupiedRowPosition;
var columnPosition = start + occupiedColumnPosition;
var newpos = key(rowPosition, columnPosition);
access[newpos] = current;
maxColumns = Math.max(maxColumns, columnPosition + 1);
}
}
currentRow_1.push(current);
});
maxRows++;
cells.push(rowdata(rowData.element, currentRow_1, rowData.section));
rowCount++;
}
});
var grid$1 = grid(maxRows, maxColumns);
return {
grid: grid$1,
access: access,
all: cells,
columns: columns
};
};
var fromTable$1 = function (table) {
var list = fromTable(table);
return generate(list);
};
var justCells = function (warehouse) {
return bind(warehouse.all, function (w) {
return w.cells;
});
};
var justColumns = function (warehouse) {
return values(warehouse.columns);
};
var hasColumns = function (warehouse) {
return keys(warehouse.columns).length > 0;
};
var getColumnAt = function (warehouse, columnIndex) {
return Optional.from(warehouse.columns[columnIndex]);
};
var Warehouse = {
fromTable: fromTable$1,
generate: generate,
getAt: getAt,
findItem: findItem,
filterItems: filterItems,
justCells: justCells,
justColumns: justColumns,
hasColumns: hasColumns,
getColumnAt: getColumnAt
};
var inSelection = function (bounds, detail) {
var leftEdge = detail.column;
var rightEdge = detail.column + detail.colspan - 1;
var topEdge = detail.row;
var bottomEdge = detail.row + detail.rowspan - 1;
return leftEdge <= bounds.finishCol && rightEdge >= bounds.startCol && (topEdge <= bounds.finishRow && bottomEdge >= bounds.startRow);
};
var isWithin = function (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;
};
var isRectangular = function (warehouse, bounds) {
var isRect = true;
var detailIsWithin = curry(isWithin, bounds);
for (var i = bounds.startRow; i <= bounds.finishRow; i++) {
for (var j = bounds.startCol; j <= bounds.finishCol; j++) {
isRect = isRect && Warehouse.getAt(warehouse, i, j).exists(detailIsWithin);
}
}
return isRect ? Optional.some(bounds) : Optional.none();
};
var getBounds = function (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));
};
var getAnyBox = function (warehouse, startCell, finishCell) {
var startCoords = Warehouse.findItem(warehouse, startCell, eq$1);
var finishCoords = Warehouse.findItem(warehouse, finishCell, eq$1);
return startCoords.bind(function (sc) {
return finishCoords.map(function (fc) {
return getBounds(sc, fc);
});
});
};
var getBox = function (warehouse, startCell, finishCell) {
return getAnyBox(warehouse, startCell, finishCell).bind(function (bounds) {
return isRectangular(warehouse, bounds);
});
};
var moveBy = function (warehouse, cell, row, column) {
return Warehouse.findItem(warehouse, cell, eq$1).bind(function (detail) {
var startRow = row > 0 ? detail.row + detail.rowspan - 1 : detail.row;
var startCol = column > 0 ? detail.column + detail.colspan - 1 : detail.column;
var dest = Warehouse.getAt(warehouse, startRow + row, startCol + column);
return dest.map(function (d) {
return d.element;
});
});
};
var intercepts = function (warehouse, start, finish) {
return getAnyBox(warehouse, start, finish).map(function (bounds) {
var inside = Warehouse.filterItems(warehouse, curry(inSelection, bounds));
return map(inside, function (detail) {
return detail.element;
});
});
};
var parentCell = function (warehouse, innerCell) {
var isContainedBy = function (c1, c2) {
return contains$2(c2, c1);
};
return Warehouse.findItem(warehouse, innerCell, isContainedBy).map(function (detail) {
return detail.element;
});
};
var moveBy$1 = function (cell, deltaRow, deltaColumn) {
return table(cell).bind(function (table) {
var warehouse = getWarehouse(table);
return moveBy(warehouse, cell, deltaRow, deltaColumn);
});
};
var intercepts$1 = function (table, first, last) {
var warehouse = getWarehouse(table);
return intercepts(warehouse, first, last);
};
var nestedIntercepts = function (table, first, firstTable, last, lastTable) {
var warehouse = getWarehouse(table);
var optStartCell = eq$1(table, firstTable) ? Optional.some(first) : parentCell(warehouse, first);
var optLastCell = eq$1(table, lastTable) ? Optional.some(last) : parentCell(warehouse, last);
return optStartCell.bind(function (startCell) {
return optLastCell.bind(function (lastCell) {
return intercepts(warehouse, startCell, lastCell);
});
});
};
var getBox$1 = function (table, first, last) {
var warehouse = getWarehouse(table);
return getBox(warehouse, first, last);
};
var getWarehouse = Warehouse.fromTable;
var before = function (marker, element) {
var parent$1 = parent(marker);
parent$1.each(function (v) {
v.dom.insertBefore(element.dom, marker.dom);
});
};
var after = function (marker, element) {
var sibling = nextSibling(marker);
sibling.fold(function () {
var parent$1 = parent(marker);
parent$1.each(function (v) {
append(v, element);
});
}, function (v) {
before(v, element);
});
};
var prepend = function (parent, element) {
var firstChild$1 = firstChild(parent);
firstChild$1.fold(function () {
append(parent, element);
}, function (v) {
parent.dom.insertBefore(element.dom, v.dom);
});
};
var append = function (parent, element) {
parent.dom.appendChild(element.dom);
};
var wrap = function (element, wrapper) {
before(element, wrapper);
append(wrapper, element);
};
var before$1 = function (marker, elements) {
each(elements, function (x) {
before(marker, x);
});
};
var after$1 = function (marker, elements) {
each(elements, function (x, i) {
var e = i === 0 ? marker : elements[i - 1];
after(e, x);
});
};
var append$1 = function (parent, elements) {
each(elements, function (x) {
append(parent, x);
});
};
var empty = function (element) {
element.dom.textContent = '';
each(children(element), function (rogue) {
remove$2(rogue);
});
};
var remove$2 = function (element) {
var dom = element.dom;
if (dom.parentNode !== null) {
dom.parentNode.removeChild(dom);
}
};
var unwrap = function (wrapper) {
var children$1 = children(wrapper);
if (children$1.length > 0) {
before$1(wrapper, children$1);
}
remove$2(wrapper);
};
var NodeValue = function (is, name) {
var get = function (element) {
if (!is(element)) {
throw new Error('Can only get ' + name + ' value of a ' + name + ' node');
}
return getOption(element).getOr('');
};
var getOption = function (element) {
return is(element) ? Optional.from(element.dom.nodeValue) : Optional.none();
};
var set = function (element, value) {
if (!is(element)) {
throw new Error('Can only set raw ' + name + ' value of a ' + name + ' node');
}
element.dom.nodeValue = value;
};
return {
get: get,
getOption: getOption,
set: set
};
};
var api = NodeValue(isText, 'text');
var get$4 = function (element) {
return api.get(element);
};
var getOption = function (element) {
return api.getOption(element);
};
var set$2 = function (element, value) {
return 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'
];
function DomUniverse () {
var clone$1 = function (element) {
return SugarElement.fromDom(element.dom.cloneNode(false));
};
var document = function (element) {
return documentOrOwner(element).dom;
};
var isBoundary = function (element) {
if (!isElement(element)) {
return false;
}
if (name(element) === 'body') {
return true;
}
return contains(TagBoundaries, name(element));
};
var isEmptyTag = function (element) {
if (!isElement(element)) {
return false;
}
return contains([
'br',
'img',
'hr',
'input'
], name(element));
};
var isNonEditable = function (element) {
return isElement(element) && get$2(element, 'contenteditable') === 'false';
};
var comparePosition = function (element, other) {
return element.dom.compareDocumentPosition(other.dom);
};
var copyAttributesTo = function (source, destination) {
var as = clone(source);
setAll(destination, as);
};
var isSpecial = function (element) {
var tag = name(element);
return contains([
'script',
'noscript',
'iframe',
'noframes',
'noembed',
'title',
'style',
'textarea',
'xmp'
], tag);
};
return {
up: constant({
selector: ancestor$1,
closest: closest$1,
predicate: ancestor,
all: parents
}),
down: constant({
selector: descendants$1,
predicate: descendants
}),
styles: constant({
get: get$3,
getRaw: getRaw,
set: set$1,
remove: remove$1
}),
attrs: constant({
get: get$2,
set: set,
remove: remove,
copyTo: copyAttributesTo
}),
insert: constant({
before: before,
after: after,
afterAll: after$1,
append: append,
appendAll: append$1,
prepend: prepend,
wrap: wrap
}),
remove: constant({
unwrap: unwrap,
remove: remove$2
}),
create: constant({
nu: SugarElement.fromTag,
clone: clone$1,
text: SugarElement.fromText
}),
query: constant({
comparePosition: comparePosition,
prevSibling: prevSibling,
nextSibling: nextSibling
}),
property: constant({
children: children,
name: name,
parent: parent,
document: document,
isText: isText,
isComment: isComment,
isElement: isElement,
isSpecial: isSpecial,
getText: get$4,
setText: set$2,
isBoundary: isBoundary,
isEmptyTag: isEmptyTag,
isNonEditable: isNonEditable
}),
eq: eq$1,
is: is$1
};
}
var all$1 = function (universe, look, elements, f) {
var head = elements[0];
var tail = elements.slice(1);
return f(universe, look, head, tail);
};
var oneAll = function (universe, look, elements) {
return elements.length > 0 ? all$1(universe, look, elements, unsafeOne) : Optional.none();
};
var unsafeOne = function (universe, look, head, tail) {
var start = look(universe, head);
return foldr(tail, function (b, a) {
var current = look(universe, a);
return commonElement(universe, b, current);
}, start);
};
var commonElement = function (universe, start, end) {
return start.bind(function (s) {
return end.filter(curry(universe.eq, s));
});
};
var eq$2 = function (universe, item) {
return curry(universe.eq, item);
};
var ancestors$2 = function (universe, start, end, isRoot) {
if (isRoot === void 0) {
isRoot = never;
}
var ps1 = [start].concat(universe.up().all(start));
var ps2 = [end].concat(universe.up().all(end));
var prune = function (path) {
var index = findIndex(path, isRoot);
return index.fold(function () {
return path;
}, function (ind) {
return path.slice(0, ind + 1);
});
};
var pruned1 = prune(ps1);
var pruned2 = prune(ps2);
var shared = find(pruned1, function (x) {
return exists(pruned2, eq$2(universe, x));
});
return {
firstpath: pruned1,
secondpath: pruned2,
shared: shared
};
};
var sharedOne = oneAll;
var ancestors$3 = ancestors$2;
var universe = DomUniverse();
var sharedOne$1 = function (look, elements) {
return sharedOne(universe, function (_universe, element) {
return look(element);
}, elements);
};
var ancestors$4 = function (start, finish, isRoot) {
return ancestors$3(universe, start, finish, isRoot);
};
var lookupTable = function (container) {
return ancestor$1(container, 'table');
};
var identify = function (start, finish, isRoot) {
var getIsRoot = function (rootTable) {
return function (element) {
return isRoot !== undefined && isRoot(element) || eq$1(element, rootTable);
};
};
if (eq$1(start, finish)) {
return Optional.some({
boxes: Optional.some([start]),
start: start,
finish: finish
});
} else {
return lookupTable(start).bind(function (startTable) {
return lookupTable(finish).bind(function (finishTable) {
if (eq$1(startTable, finishTable)) {
return Optional.some({
boxes: intercepts$1(startTable, start, finish),
start: start,
finish: finish
});
} else if (contains$2(startTable, finishTable)) {
var ancestorCells = ancestors$1(finish, 'td,th', getIsRoot(startTable));
var finishCell = ancestorCells.length > 0 ? ancestorCells[ancestorCells.length - 1] : finish;
return Optional.some({
boxes: nestedIntercepts(startTable, start, startTable, finish, finishTable),
start: start,
finish: finishCell
});
} else if (contains$2(finishTable, startTable)) {
var ancestorCells = ancestors$1(start, 'td,th', getIsRoot(finishTable));
var startCell = ancestorCells.length > 0 ? ancestorCells[ancestorCells.length - 1] : start;
return Optional.some({
boxes: nestedIntercepts(finishTable, start, startTable, finish, finishTable),
start: start,
finish: startCell
});
} else {
return ancestors$4(start, finish).shared.bind(function (lca) {
return closest$1(lca, 'table', isRoot).bind(function (lcaTable) {
var finishAncestorCells = ancestors$1(finish, 'td,th', getIsRoot(lcaTable));
var finishCell = finishAncestorCells.length > 0 ? finishAncestorCells[finishAncestorCells.length - 1] : finish;
var startAncestorCells = ancestors$1(start, 'td,th', getIsRoot(lcaTable));
var startCell = startAncestorCells.length > 0 ? startAncestorCells[startAncestorCells.length - 1] : start;
return Optional.some({
boxes: nestedIntercepts(lcaTable, start, startTable, finish, finishTable),
start: startCell,
finish: finishCell
});
});
});
}
});
});
}
};
var retrieve = function (container, selector) {
var sels = descendants$1(container, selector);
return sels.length > 0 ? Optional.some(sels) : Optional.none();
};
var getLast = function (boxes, lastSelectedSelector) {
return find(boxes, function (box) {
return is(box, lastSelectedSelector);
});
};
var getEdges = function (container, firstSelectedSelector, lastSelectedSelector) {
return descendant$1(container, firstSelectedSelector).bind(function (first) {
return descendant$1(container, lastSelectedSelector).bind(function (last) {
return sharedOne$1(lookupTable, [
first,
last
]).map(function (table) {
return {
first: first,
last: last,
table: table
};
});
});
});
};
var expandTo = function (finish, firstSelectedSelector) {
return ancestor$1(finish, 'table').bind(function (table) {
return descendant$1(table, firstSelectedSelector).bind(function (start) {
return identify(start, finish).bind(function (identified) {
return identified.boxes.map(function (boxes) {
return {
boxes: boxes,
start: identified.start,
finish: identified.finish
};
});
});
});
});
};
var shiftSelection = function (boxes, deltaRow, deltaColumn, firstSelectedSelector, lastSelectedSelector) {
return getLast(boxes, lastSelectedSelector).bind(function (last) {
return moveBy$1(last, deltaRow, deltaColumn).bind(function (finish) {
return expandTo(finish, firstSelectedSelector);
});
});
};
var retrieve$1 = function (container, selector) {
return retrieve(container, selector);
};
var retrieveBox = function (container, firstSelectedSelector, lastSelectedSelector) {
return getEdges(container, firstSelectedSelector, lastSelectedSelector).bind(function (edges) {
var isRoot = function (ancestor) {
return eq$1(container, ancestor);
};
var sectionSelector = 'thead,tfoot,tbody,table';
var firstAncestor = ancestor$1(edges.first, sectionSelector, isRoot);
var lastAncestor = ancestor$1(edges.last, sectionSelector, isRoot);
return firstAncestor.bind(function (fA) {
return lastAncestor.bind(function (lA) {
return eq$1(fA, lA) ? getBox$1(edges.table, edges.first, edges.last) : Optional.none();
});
});
});
};
var generate$1 = function (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');
}
var constructors = [];
var adt = {};
each(cases, function (acase, count) {
var keys$1 = keys(acase);
if (keys$1.length !== 1) {
throw new Error('one and only one name per case');
}
var key = keys$1[0];
var 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] = function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
var argLength = args.length;
if (argLength !== value.length) {
throw new Error('Wrong number of arguments to case ' + key + '. Expected ' + value.length + ' (' + value + '), got ' + argLength);
}
var match = function (branches) {
var branchKeys = keys(branches);
if (constructors.length !== branchKeys.length) {
throw new Error('Wrong number of arguments to match. Expected: ' + constructors.join(',') + '\nActual: ' + branchKeys.join(','));
}
var allReqd = forall(constructors, function (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: function () {
var foldArgs = [];
for (var _i = 0; _i < arguments.length; _i++) {
foldArgs[_i] = arguments[_i];
}
if (foldArgs.length !== cases.length) {
throw new Error('Wrong number of arguments to fold. Expected ' + cases.length + ', got ' + foldArgs.length);
}
var target = foldArgs[count];
return target.apply(null, args);
},
match: match,
log: function (label) {
console.log(label, {
constructors: constructors,
constructor: key,
params: args
});
}
};
};
});
return adt;
};
var Adt = { generate: generate$1 };
var type$1 = Adt.generate([
{ none: [] },
{ multiple: ['elements'] },
{ single: ['element'] }
]);
var cata = function (subject, onNone, onMultiple, onSingle) {
return subject.fold(onNone, onMultiple, onSingle);
};
var none$1 = type$1.none;
var multiple = type$1.multiple;
var single = type$1.single;
var Selections = function (lazyRoot, getStart, selectedSelector) {
var get = function () {
return retrieve$1(lazyRoot(), selectedSelector).fold(function () {
return getStart().map(single).getOrThunk(none$1);
}, function (cells) {
return multiple(cells);
});
};
return { get: get };
};
var global = tinymce.util.Tools.resolve('tinymce.PluginManager');
var clone$1 = function (original, isDeep) {
return SugarElement.fromDom(original.dom.cloneNode(isDeep));
};
var shallow = function (original) {
return clone$1(original, false);
};
var deep = function (original) {
return clone$1(original, true);
};
var shallowAs = function (original, tag) {
var nu = SugarElement.fromTag(tag);
var attributes = clone(original);
setAll(nu, attributes);
return nu;
};
var copy$1 = function (original, tag) {
var nu = shallowAs(original, tag);
var cloneChildren = children(deep(original));
append$1(nu, cloneChildren);
return nu;
};
var cat = function (arr) {
var r = [];
var push = function (x) {
r.push(x);
};
for (var i = 0; i < arr.length; i++) {
arr[i].each(push);
}
return r;
};
var lift2 = function (oa, ob, f) {
return oa.isSome() && ob.isSome() ? Optional.some(f(oa.getOrDie(), ob.getOrDie())) : Optional.none();
};
var bindFrom = function (a, f) {
return a !== undefined && a !== null ? f(a) : Optional.none();
};
var someIf = function (b, a) {
return b ? Optional.some(a) : Optional.none();
};
var Dimension = function (name, getOffset) {
var set = function (element, h) {
if (!isNumber(h) && !h.match(/^[0-9]+$/)) {
throw new Error(name + '.set accepts only positive integer values. Value was ' + h);
}
var dom = element.dom;
if (isSupported$1(dom)) {
dom.style[name] = h + 'px';
}
};
var get = function (element) {
var r = getOffset(element);
if (r <= 0 || r === null) {
var css = get$3(element, name);
return parseFloat(css) || 0;
}
return r;
};
var getOuter = get;
var aggregate = function (element, properties) {
return foldl(properties, function (acc, property) {
var val = get$3(element, property);
var value = val === undefined ? 0 : parseInt(val, 10);
return isNaN(value) ? acc : acc + value;
}, 0);
};
var max = function (element, value, properties) {
var cumulativeInclusions = aggregate(element, properties);
var absoluteMax = value > cumulativeInclusions ? value - cumulativeInclusions : 0;
return absoluteMax;
};
return {
set: set,
get: get,
getOuter: getOuter,
aggregate: aggregate,
max: max
};
};
var api$1 = Dimension('width', function (element) {
return element.dom.offsetWidth;
});
var get$5 = function (element) {
return api$1.get(element);
};
var getOuter = function (element) {
return api$1.getOuter(element);
};
var columns$1 = function (warehouse, isValidCell) {
if (isValidCell === void 0) {
isValidCell = always;
}
var grid = warehouse.grid;
var cols = range(grid.columns, identity);
var rowsArr = range(grid.rows, identity);
return map(cols, function (col) {
var getBlock = function () {
return bind(rowsArr, function (r) {
return Warehouse.getAt(warehouse, r, col).filter(function (detail) {
return detail.column === col;
}).toArray();
});
};
var isValid = function (detail) {
return detail.colspan === 1 && isValidCell(detail.element);
};
var getFallback = function () {
return Warehouse.getAt(warehouse, 0, col);
};
return decide(getBlock, isValid, getFallback);
});
};
var decide = function (getBlock, isValid, getFallback) {
var inBlock = getBlock();
var validInBlock = find(inBlock, isValid);
var detailOption = validInBlock.orThunk(function () {
return Optional.from(inBlock[0]).orThunk(getFallback);
});
return detailOption.map(function (detail) {
return detail.element;
});
};
var rows$1 = function (warehouse) {
var grid = warehouse.grid;
var rowsArr = range(grid.rows, identity);
var cols = range(grid.columns, identity);
return map(rowsArr, function (row) {
var getBlock = function () {
return bind(cols, function (c) {
return Warehouse.getAt(warehouse, row, c).filter(function (detail) {
return detail.row === row;
}).fold(constant([]), function (detail) {
return [detail];
});
});
};
var isSingle = function (detail) {
return detail.rowspan === 1;
};
var getFallback = function () {
return Warehouse.getAt(warehouse, row, 0);
};
return decide(getBlock, isSingle, getFallback);
});
};
var deduce = function (xs, index) {
if (index < 0 || index >= xs.length - 1) {
return Optional.none();
}
var current = xs[index].fold(function () {
var rest = reverse(xs.slice(0, index));
return findMap(rest, function (a, i) {
return a.map(function (aa) {
return {
value: aa,
delta: i + 1
};
});
});
}, function (c) {
return Optional.some({
value: c,
delta: 0
});
});
var next = xs[index + 1].fold(function () {
var rest = xs.slice(index + 1);
return findMap(rest, function (a, i) {
return a.map(function (aa) {
return {
value: aa,
delta: i + 1
};
});
});
}, function (n) {
return Optional.some({
value: n,
delta: 1
});
});
return current.bind(function (c) {
return next.map(function (n) {
var extras = n.delta + c.delta;
return Math.abs(n.value - c.value) / extras;
});
});
};
var onDirection = function (isLtr, isRtl) {
return function (element) {
return getDirection(element) === 'rtl' ? isRtl : isLtr;
};
};
var getDirection = function (element) {
return get$3(element, 'direction') === 'rtl' ? 'rtl' : 'ltr';
};
var api$2 = Dimension('height', function (element) {
var dom = element.dom;
return inBody(element) ? dom.getBoundingClientRect().height : dom.offsetHeight;
});
var get$6 = function (element) {
return api$2.get(element);
};
var getOuter$1 = function (element) {
return api$2.getOuter(element);
};
var r = function (left, top) {
var translate = function (x, y) {
return r(left + x, top + y);
};
return {
left: left,
top: top,
translate: translate
};
};
var SugarPosition = r;
var boxPosition = function (dom) {
var box = dom.getBoundingClientRect();
return SugarPosition(box.left, box.top);
};
var firstDefinedOrZero = function (a, b) {
if (a !== undefined) {
return a;
} else {
return b !== undefined ? b : 0;
}
};
var absolute = function (element) {
var doc = element.dom.ownerDocument;
var body = doc.body;
var win = doc.defaultView;
var html = doc.documentElement;
if (body === element.dom) {
return SugarPosition(body.offsetLeft, body.offsetTop);
}
var scrollTop = firstDefinedOrZero(win === null || win === void 0 ? void 0 : win.pageYOffset, html.scrollTop);
var scrollLeft = firstDefinedOrZero(win === null || win === void 0 ? void 0 : win.pageXOffset, html.scrollLeft);
var clientTop = firstDefinedOrZero(html.clientTop, body.clientTop);
var clientLeft = firstDefinedOrZero(html.clientLeft, body.clientLeft);
return viewport(element).translate(scrollLeft - clientLeft, scrollTop - clientTop);
};
var viewport = function (element) {
var dom = element.dom;
var doc = dom.ownerDocument;
var body = doc.body;
if (body === dom) {
return SugarPosition(body.offsetLeft, body.offsetTop);
}
if (!inBody(element)) {
return SugarPosition(0, 0);
}
return boxPosition(dom);
};
var rowInfo = function (row, y) {
return {
row: row,
y: y
};
};
var colInfo = function (col, x) {
return {
col: col,
x: x
};
};
var rtlEdge = function (cell) {
var pos = absolute(cell);
return pos.left + getOuter(cell);
};
var ltrEdge = function (cell) {
return absolute(cell).left;
};
var getLeftEdge = function (index, cell) {
return colInfo(index, ltrEdge(cell));
};
var getRightEdge = function (index, cell) {
return colInfo(index, rtlEdge(cell));
};
var getTop = function (cell) {
return absolute(cell).top;
};
var getTopEdge = function (index, cell) {
return rowInfo(index, getTop(cell));
};
var getBottomEdge = function (index, cell) {
return rowInfo(index, getTop(cell) + getOuter$1(cell));
};
var findPositions = function (getInnerEdge, getOuterEdge, array) {
if (array.length === 0) {
return [];
}
var lines = map(array.slice(1), function (cellOption, index) {
return cellOption.map(function (cell) {
return getInnerEdge(index, cell);
});
});
var lastLine = array[array.length - 1].map(function (cell) {
return getOuterEdge(array.length - 1, cell);
});
return lines.concat([lastLine]);
};
var negate = function (step) {
return -step;
};
var height = {
delta: identity,
positions: function (optElements) {
return findPositions(getTopEdge, getBottomEdge, optElements);
},
edge: getTop
};
var ltr = {
delta: identity,
edge: ltrEdge,
positions: function (optElements) {
return findPositions(getLeftEdge, getRightEdge, optElements);
}
};
var rtl = {
delta: negate,
edge: rtlEdge,
positions: function (optElements) {
return findPositions(getRightEdge, getLeftEdge, optElements);
}
};
var detect$4 = onDirection(ltr, rtl);
var width = {
delta: function (amount, table) {
return detect$4(table).delta(amount, table);
},
positions: function (cols, table) {
return detect$4(table).positions(cols, table);
},
edge: function (cell) {
return detect$4(cell).edge(cell);
}
};
var units = {
unsupportedLength: [
'em',
'ex',
'cap',
'ch',
'ic',
'rem',
'lh',
'rlh',
'vw',
'vh',
'vi',
'vb',
'vmin',
'vmax',
'cm',
'mm',
'Q',
'in',
'pc',
'pt',
'px'
],
fixed: [
'px',
'pt'
],
relative: ['%'],
empty: ['']
};
var pattern = function () {
var decimalDigits = '[0-9]+';
var signedInteger = '[+-]?' + decimalDigits;
var exponentPart = '[eE]' + signedInteger;
var dot = '\\.';
var opt = function (input) {
return '(?:' + input + ')?';
};
var unsignedDecimalLiteral = [
'Infinity',
decimalDigits + dot + opt(decimalDigits) + opt(exponentPart),
dot + decimalDigits + opt(exponentPart),
decimalDigits + opt(exponentPart)
].join('|');
var float = '[+-]?(?:' + unsignedDecimalLiteral + ')';
return new RegExp('^(' + float + ')(.*)$');
}();
var isUnit = function (unit, accepted) {
return exists(accepted, function (acc) {
return exists(units[acc], function (check) {
return unit === check;
});
});
};
var parse = function (input, accepted) {
var match = Optional.from(pattern.exec(input));
return match.bind(function (array) {
var value = Number(array[1]);
var unitRaw = array[2];
if (isUnit(unitRaw, accepted)) {
return Optional.some({
value: value,
unit: unitRaw
});
} else {
return Optional.none();
}
});
};
var needManualCalc = function () {
var browser = detect$3().browser;
return browser.isIE() || browser.isEdge();
};
var toNumber = function (px, fallback) {
var num = parseFloat(px);
return isNaN(num) ? fallback : num;
};
var getProp = function (elm, name, fallback) {
return toNumber(get$3(elm, name), fallback);
};
var getCalculatedHeight = function (cell) {
var height = cell.dom.getBoundingClientRect().height;
var boxSizing = get$3(cell, 'box-sizing');
if (boxSizing === 'border-box') {
return height;
} else {
var paddingTop = getProp(cell, 'padding-top', 0);
var paddingBottom = getProp(cell, 'padding-bottom', 0);
var borderTop = getProp(cell, 'border-top-width', 0);
var borderBottom = getProp(cell, 'border-bottom-width', 0);
var borders = borderTop + borderBottom;
return height - paddingTop - paddingBottom - borders;
}
};
var getCalculatedWidth = function (cell) {
var width = cell.dom.getBoundingClientRect().width;
var boxSizing = get$3(cell, 'box-sizing');
if (boxSizing === 'border-box') {
return width;
} else {
var paddingLeft = getProp(cell, 'padding-left', 0);
var paddingRight = getProp(cell, 'padding-right', 0);
var borderLeft = getProp(cell, 'border-left-width', 0);
var borderRight = getProp(cell, 'border-right-width', 0);
var borders = borderLeft + borderRight;
return width - paddingLeft - paddingRight - borders;
}
};
var getHeight = function (cell) {
return needManualCalc() ? getCalculatedHeight(cell) : getProp(cell, 'height', get$6(cell));
};
var getWidth = function (cell) {
return needManualCalc() ? getCalculatedWidth(cell) : getProp(cell, 'width', get$5(cell));
};
var rPercentageBasedSizeRegex = /(\d+(\.\d+)?)%/;
var rPixelBasedSizeRegex = /(\d+(\.\d+)?)px|em/;
var getPercentSize = function (elm, getter) {
var relativeParent = offsetParent(elm).getOr(getBody(owner(elm)));
return getter(elm) / getter(relativeParent) * 100;
};
var setPixelWidth = function (cell, amount) {
set$1(cell, 'width', amount + 'px');
};
var setPercentageWidth = function (cell, amount) {
set$1(cell, 'width', amount + '%');
};
var setHeight = function (cell, amount) {
set$1(cell, 'height', amount + 'px');
};
var getHeightValue = function (cell) {
return getRaw(cell, 'height').getOrThunk(function () {
return getHeight(cell) + 'px';
});
};
var convert = function (cell, number, getter, setter) {
var newSize = table(cell).map(function (table) {
var total = getter(table);
return Math.floor(number / 100 * total);
}).getOr(number);
setter(cell, newSize);
return newSize;
};
var normalizePixelSize = function (value, cell, getter, setter) {
var number = parseInt(value, 10);
return endsWith(value, '%') && name(cell) !== 'table' ? convert(cell, number, getter, setter) : number;
};
var getTotalHeight = function (cell) {
var value = getHeightValue(cell);
if (!value) {
return get$6(cell);
}
return normalizePixelSize(value, cell, get$6, setHeight);
};
var get$7 = function (cell, type, f) {
var v = f(cell);
var span = getSpan(cell, type);
return v / span;
};
var getRawWidth = function (element) {
var cssWidth = getRaw(element, 'width');
return cssWidth.fold(function () {
return Optional.from(get$2(element, 'width'));
}, function (width) {
return Optional.some(width);
});
};
var normalizePercentageWidth = function (cellWidth, tableSize) {
return cellWidth / tableSize.pixelWidth() * 100;
};
var choosePercentageSize = function (element, width, tableSize) {
var percentMatch = rPercentageBasedSizeRegex.exec(width);
if (percentMatch !== null) {
return parseFloat(percentMatch[1]);
} else {
var intWidth = getWidth(element);
return normalizePercentageWidth(intWidth, tableSize);
}
};
var getPercentageWidth = function (cell, tableSize) {
var width = getRawWidth(cell);
return width.fold(function () {
var intWidth = get$5(cell);
return normalizePercentageWidth(intWidth, tableSize);
}, function (w) {
return choosePercentageSize(cell, w, tableSize);
});
};
var normalizePixelWidth = function (cellWidth, tableSize) {
return cellWidth / 100 * tableSize.pixelWidth();
};
var choosePixelSize = function (element, width, tableSize) {
var pixelMatch = rPixelBasedSizeRegex.exec(width);
if (pixelMatch !== null) {
return parseInt(pixelMatch[1], 10);
}
var percentMatch = rPercentageBasedSizeRegex.exec(width);
if (percentMatch !== null) {
var floatWidth = parseFloat(percentMatch[1]);
return normalizePixelWidth(floatWidth, tableSize);
}
return getWidth(element);
};
var getPixelWidth = function (cell, tableSize) {
var width = getRawWidth(cell);
return width.fold(function () {
return getWidth(cell);
}, function (w) {
return choosePixelSize(cell, w, tableSize);
});
};
var getHeight$1 = function (cell) {
return get$7(cell, 'rowspan', getTotalHeight);
};
var getGenericWidth = function (cell) {
var width = getRawWidth(cell);
return width.bind(function (w) {
return parse(w, [
'fixed',
'relative',
'empty'
]);
});
};
var setGenericWidth = function (cell, amount, unit) {
set$1(cell, 'width', amount + unit);
};
var getPixelTableWidth = function (table) {
return get$5(table) + 'px';
};
var getPercentTableWidth = function (table) {
return getPercentSize(table, get$5) + '%';
};
var isPercentSizing = function (table) {
return getRawWidth(table).exists(function (size) {
return rPercentageBasedSizeRegex.test(size);
});
};
var isPixelSizing = function (table) {
return getRawWidth(table).exists(function (size) {
return rPixelBasedSizeRegex.test(size);
});
};
var isNoneSizing = function (table) {
return getRawWidth(table).isNone();
};
var percentageBasedSizeRegex = constant(rPercentageBasedSizeRegex);
var pixelBasedSizeRegex = constant(rPixelBasedSizeRegex);
var isCol = isTag('col');
var getRaw$1 = function (cell, property, getter) {
return getRaw(cell, property).fold(function () {
return getter(cell) + 'px';
}, function (raw) {
return raw;
});
};
var getRawW = function (cell, tableSize) {
var fallback = function (e) {
return isCol(e) ? get$5(e) : getPixelWidth(e, tableSize);
};
return getRaw$1(cell, 'width', fallback);
};
var getRawH = function (cell) {
return getRaw$1(cell, 'height', getHeight$1);
};
var justCols = function (warehouse) {
return map(Warehouse.justColumns(warehouse), function (column) {
return Optional.from(column.element);
});
};
var hasRawStyle = function (cell, prop) {
return getRaw(cell, prop).isSome();
};
var isValidColumn = function (cell) {
return !isCol(cell) || hasRawStyle(cell, 'width');
};
var getDimension = function (cellOpt, index, backups, filter, getter, fallback) {
return cellOpt.filter(filter).fold(function () {
return fallback(deduce(backups, index));
}, function (cell) {
return getter(cell);
});
};
var getWidthFrom = function (warehouse, table, getWidth, fallback, tableSize) {
var columnCells = columns$1(warehouse, function (cell) {
return hasRawStyle(cell, 'width');
});
var columns = Warehouse.hasColumns(warehouse) ? justCols(warehouse) : columnCells;
var backups = [Optional.some(width.edge(table))].concat(map(width.positions(columnCells, table), function (pos) {
return pos.map(function (p) {
return p.x;
});
}));
var colFilter = not(hasColspan);
return map(columns, function (cellOption, c) {
return getDimension(cellOption, c, backups, colFilter, function (column) {
if (isValidColumn(column)) {
return getWidth(column, tableSize);
} else {
var cell = bindFrom(columnCells[c], identity);
return getDimension(cell, c, backups, colFilter, function (cell) {
return fallback(Optional.some(get$5(cell)));
}, fallback);
}
}, fallback);
});
};
var getDeduced = function (deduced) {
return deduced.map(function (d) {
return d + 'px';
}).getOr('');
};
var getRawWidths = function (warehouse, table, tableSize) {
return getWidthFrom(warehouse, table, getRawW, getDeduced, tableSize);
};
var getPercentageWidths = function (warehouse, table, tableSize) {
return getWidthFrom(warehouse, table, getPercentageWidth, function (deduced) {
return deduced.fold(function () {
return tableSize.minCellWidth();
}, function (cellWidth) {
return cellWidth / tableSize.pixelWidth() * 100;
});
}, tableSize);
};
var getPixelWidths = function (warehouse, table, tableSize) {
return getWidthFrom(warehouse, table, getPixelWidth, function (deduced) {
return deduced.getOrThunk(tableSize.minCellWidth);
}, tableSize);
};
var getHeightFrom = function (warehouse, table, direction, getHeight, fallback) {
var rows = rows$1(warehouse);
var backups = [Optional.some(direction.edge(table))].concat(map(direction.positions(rows, table), function (pos) {
return pos.map(function (p) {
return p.y;
});
}));
return map(rows, function (cellOption, c) {
return getDimension(cellOption, c, backups, not(hasRowspan), getHeight, fallback);
});
};
var getPixelHeights = function (warehouse, table, direction) {
return getHeightFrom(warehouse, table, direction, getHeight$1, function (deduced) {
return deduced.getOrThunk(minHeight);
});
};
var getRawHeights = function (warehouse, table, direction) {
return getHeightFrom(warehouse, table, direction, getRawH, getDeduced);
};
var Cell = function (initial) {
var value = initial;
var get = function () {
return value;
};
var set = function (v) {
value = v;
};
return {
get: get,
set: set
};
};
var noneSize = function (table) {
var getWidth = function () {
return get$5(table);
};
var zero = constant(0);
var getWidths = function (warehouse, tableSize) {
return getPixelWidths(warehouse, table, tableSize);
};
return {
width: getWidth,
pixelWidth: getWidth,
getWidths: getWidths,
getCellDelta: zero,
singleColumnWidth: constant([0]),
minCellWidth: zero,
setElementWidth: noop,
adjustTableWidth: noop,
isRelative: true,
label: 'none'
};
};
var percentageSize = function (initialWidth, table) {
var floatWidth = Cell(parseFloat(initialWidth));
var pixelWidth = Cell(get$5(table));
var getCellDelta = function (delta) {
return delta / pixelWidth.get() * 100;
};
var singleColumnWidth = function (w, _delta) {
return [100 - w];
};
var minCellWidth = function () {
return minWidth() / pixelWidth.get() * 100;
};
var adjustTableWidth = function (delta) {
var currentWidth = floatWidth.get();
var change = delta / 100 * currentWidth;
var newWidth = currentWidth + change;
setPercentageWidth(table, newWidth);
floatWidth.set(newWidth);
pixelWidth.set(get$5(table));
};
var getWidths = function (warehouse, tableSize) {
return getPercentageWidths(warehouse, table, tableSize);
};
return {
width: floatWidth.get,
pixelWidth: pixelWidth.get,
getWidths: getWidths,
getCellDelta: getCellDelta,
singleColumnWidth: singleColumnWidth,
minCellWidth: minCellWidth,
setElementWidth: setPercentageWidth,
adjustTableWidth: adjustTableWidth,
isRelative: true,
label: 'percent'
};
};
var pixelSize = function (initialWidth, table) {
var width = Cell(initialWidth);
var getWidth = width.get;
var getCellDelta = identity;
var singleColumnWidth = function (w, delta) {
var newNext = Math.max(minWidth(), w + delta);
return [newNext - w];
};
var adjustTableWidth = function (delta) {
var newWidth = getWidth() + delta;
setPixelWidth(table, newWidth);
width.set(newWidth);
};
var getWidths = function (warehouse, tableSize) {
return getPixelWidths(warehouse, table, tableSize);
};
return {
width: getWidth,
pixelWidth: getWidth,
getWidths: getWidths,
getCellDelta: getCellDelta,
singleColumnWidth: singleColumnWidth,
minCellWidth: minWidth,
setElementWidth: setPixelWidth,
adjustTableWidth: adjustTableWidth,
isRelative: false,
label: 'pixel'
};
};
var chooseSize = function (element, width) {
var percentMatch = percentageBasedSizeRegex().exec(width);
if (percentMatch !== null) {
return percentageSize(percentMatch[1], element);
}
var pixelMatch = pixelBasedSizeRegex().exec(width);
if (pixelMatch !== null) {
var intWidth = parseInt(pixelMatch[1], 10);
return pixelSize(intWidth, element);
}
var fallbackWidth = get$5(element);
return pixelSize(fallbackWidth, element);
};
var getTableSize = function (table) {
var width = getRawWidth(table);
return width.fold(function () {
return noneSize(table);
}, function (w) {
return chooseSize(table, w);
});
};
var TableSize = {
getTableSize: getTableSize,
pixelSize: pixelSize,
percentageSize: percentageSize,
noneSize: noneSize
};
var statsStruct = function (minRow, minCol, maxRow, maxCol, allCells, selectedCells) {
return {
minRow: minRow,
minCol: minCol,
maxRow: maxRow,
maxCol: maxCol,
allCells: allCells,
selectedCells: selectedCells
};
};
var findSelectedStats = function (house, isSelected) {
var totalColumns = house.grid.columns;
var totalRows = house.grid.rows;
var minRow = totalRows;
var minCol = totalColumns;
var maxRow = 0;
var maxCol = 0;
var allCells = [];
var selectedCells = [];
each$1(house.access, function (detail) {
allCells.push(detail);
if (isSelected(detail)) {
selectedCells.push(detail);
var startRow = detail.row;
var endRow = startRow + detail.rowspan - 1;
var startCol = detail.column;
var endCol = startCol + detail.colspan - 1;
if (startRow < minRow) {
minRow = startRow;
} else if (endRow > maxRow) {
maxRow = endRow;
}
if (startCol < minCol) {
minCol = startCol;
} else if (endCol > maxCol) {
maxCol = endCol;
}
}
});
return statsStruct(minRow, minCol, maxRow, maxCol, allCells, selectedCells);
};
var makeCell = function (list, seenSelected, rowIndex) {
var row = list[rowIndex].element;
var td = SugarElement.fromTag('td');
append(td, SugarElement.fromTag('br'));
var f = seenSelected ? append : prepend;
f(row, td);
};
var fillInGaps = function (list, house, stats, isSelected) {
var totalColumns = house.grid.columns;
var totalRows = house.grid.rows;
for (var i = 0; i < totalRows; i++) {
var seenSelected = false;
for (var j = 0; j < totalColumns; j++) {
if (!(i < stats.minRow || i > stats.maxRow || j < stats.minCol || j > stats.maxCol)) {
var needCell = Warehouse.getAt(house, i, j).filter(isSelected).isNone();
if (needCell) {
makeCell(list, seenSelected, i);
} else {
seenSelected = true;
}
}
}
}
};
var clean = function (replica, stats, house, widthDelta) {
each$1(house.columns, function (col) {
if (col.column < stats.minCol || col.column > stats.maxCol) {
remove$2(col.element);
}
});
var emptyRows = filter(firstLayer(replica, 'tr'), function (row) {
return row.dom.childElementCount === 0;
});
each(emptyRows, remove$2);
if (stats.minCol === stats.maxCol || stats.minRow === stats.maxRow) {
each(firstLayer(replica, 'th,td'), function (cell) {
remove(cell, 'rowspan');
remove(cell, 'colspan');
});
}
remove(replica, LOCKED_COL_ATTR);
remove(replica, 'data-snooker-col-series');
var tableSize = TableSize.getTableSize(replica);
tableSize.adjustTableWidth(widthDelta);
};
var getTableWidthDelta = function (table, warehouse, tableSize, stats) {
if (stats.minCol === 0 && warehouse.grid.columns === stats.maxCol + 1) {
return 0;
}
var colWidths = getPixelWidths(warehouse, table, tableSize);
var allColsWidth = foldl(colWidths, function (acc, width) {
return acc + width;
}, 0);
var selectedColsWidth = foldl(colWidths.slice(stats.minCol, stats.maxCol + 1), function (acc, width) {
return acc + width;
}, 0);
var newWidth = selectedColsWidth / allColsWidth * tableSize.pixelWidth();
var delta = newWidth - tableSize.pixelWidth();
return tableSize.getCellDelta(delta);
};
var extract = function (table, selectedSelector) {
var isSelected = function (detail) {
return is(detail.element, selectedSelector);
};
var replica = deep(table);
var list = fromTable(replica);
var tableSize = TableSize.getTableSize(table);
var replicaHouse = Warehouse.generate(list);
var replicaStats = findSelectedStats(replicaHouse, isSelected);
var selector = 'th:not(' + selectedSelector + ')' + ',td:not(' + selectedSelector + ')';
var unselectedCells = filterFirstLayer(replica, 'th,td', function (cell) {
return is(cell, selector);
});
each(unselectedCells, remove$2);
fillInGaps(list, replicaHouse, replicaStats, isSelected);
var house = Warehouse.fromTable(table);
var widthDelta = getTableWidthDelta(table, house, tableSize, replicaStats);
clean(replica, replicaStats, replicaHouse, widthDelta);
return replica;
};
var nbsp = '\xA0';
var getEnd = function (element) {
return name(element) === 'img' ? 1 : getOption(element).fold(function () {
return children(element).length;
}, function (v) {
return v.length;
});
};
var isTextNodeWithCursorPosition = function (el) {
return getOption(el).filter(function (text) {
return text.trim().length !== 0 || text.indexOf(nbsp) > -1;
}).isSome();
};
var elementsWithCursorPosition = [
'img',
'br'
];
var isCursorPosition = function (elem) {
var hasCursorPosition = isTextNodeWithCursorPosition(elem);
return hasCursorPosition || contains(elementsWithCursorPosition, name(elem));
};
var first = function (element) {
return descendant(element, isCursorPosition);
};
var last$1 = function (element) {
return descendantRtl(element, isCursorPosition);
};
var descendantRtl = function (scope, predicate) {
var descend = function (element) {
var children$1 = children(element);
for (var i = children$1.length - 1; i >= 0; i--) {
var child = children$1[i];
if (predicate(child)) {
return Optional.some(child);
}
var res = descend(child);
if (res.isSome()) {
return res;
}
}
return Optional.none();
};
return descend(scope);
};
var transferableAttributes = {
scope: [
'row',
'col'
]
};
var createCell = function () {
var td = SugarElement.fromTag('td');
append(td, SugarElement.fromTag('br'));
return td;
};
var createCol = function () {
return SugarElement.fromTag('col');
};
var createColgroup = function () {
return SugarElement.fromTag('colgroup');
};
var replace = function (cell, tag, attrs) {
var replica = copy$1(cell, tag);
each$1(attrs, function (v, k) {
if (v === null) {
remove(replica, k);
} else {
set(replica, k, v);
}
});
return replica;
};
var pasteReplace = function (cell) {
return cell;
};
var newRow = function (doc) {
return function () {
return SugarElement.fromTag('tr', doc.dom);
};
};
var cloneFormats = function (oldCell, newCell, formats) {
var first$1 = first(oldCell);
return first$1.map(function (firstText) {
var formatSelector = formats.join(',');
var parents = ancestors$1(firstText, formatSelector, function (element) {
return eq$1(element, oldCell);
});
return foldr(parents, function (last, parent) {
var clonedFormat = shallow(parent);
remove(clonedFormat, 'contenteditable');
append(last, clonedFormat);
return clonedFormat;
}, newCell);
}).getOr(newCell);
};
var cloneAppropriateAttributes = function (original, clone) {
each$1(transferableAttributes, function (validAttributes, attributeName) {
return getOpt(original, attributeName).filter(function (attribute) {
return contains(validAttributes, attribute);
}).each(function (attribute) {
return set(clone, attributeName, attribute);
});
});
};
var cellOperations = function (mutate, doc, formatsToClone) {
var cloneCss = function (prev, clone) {
copy(prev.element, clone);
remove$1(clone, 'height');
if (prev.colspan !== 1) {
remove$1(clone, 'width');
}
};
var newCell = function (prev) {
var docu = owner(prev.element);
var td = SugarElement.fromTag(name(prev.element), docu.dom);
var formats = formatsToClone.getOr([
'strong',
'em',
'b',
'i',
'span',
'font',
'h1',
'h2',
'h3',
'h4',
'h5',
'h6',
'p',
'div'
]);
var lastNode = formats.length > 0 ? cloneFormats(prev.element, td, formats) : td;
append(lastNode, SugarElement.fromTag('br'));
cloneCss(prev, td);
cloneAppropriateAttributes(prev.element, td);
mutate(prev.element, td);
return td;
};
var newCol = function (prev) {
var doc = owner(prev.element);
var col = SugarElement.fromTag(name(prev.element), doc.dom);
cloneCss(prev, col);
mutate(prev.element, col);
return col;
};
return {
col: newCol,
colgroup: createColgroup,
row: newRow(doc),
cell: newCell,
replace: replace,
gap: createCell
};
};
var paste = function (doc) {
return {
col: createCol,
colgroup: createColgroup,
row: newRow(doc),
cell: createCell,
replace: pasteReplace,
gap: createCell
};
};
var fromHtml$1 = function (html, scope) {
var doc = scope || document;
var div = doc.createElement('div');
div.innerHTML = html;
return children(SugarElement.fromDom(div));
};
var fromDom$1 = function (nodes) {
return map(nodes, SugarElement.fromDom);
};
var getNodeName = function (elm) {
return elm.nodeName.toLowerCase();
};
var getBody$1 = function (editor) {
return SugarElement.fromDom(editor.getBody());
};
var getPixelWidth$1 = function (elm) {
return elm.getBoundingClientRect().width;
};
var getPixelHeight = function (elm) {
return elm.getBoundingClientRect().height;
};
var getIsRoot = function (editor) {
return function (element) {
return eq$1(element, getBody$1(editor));
};
};
var removePxSuffix = function (size) {
return size ? size.replace(/px$/, '') : '';
};
var addPxSuffix = function (size) {
return /^\d+(\.\d+)?$/.test(size) ? size + 'px' : size;
};
var removeDataStyle = function (table) {
remove(table, 'data-mce-style');
var removeStyleAttribute = function (element) {
return remove(element, 'data-mce-style');
};
each(cells(table), removeStyleAttribute);
each(columns(table), removeStyleAttribute);
};
var getRawWidth$1 = function (editor, elm) {
var raw = editor.dom.getStyle(elm, 'width') || editor.dom.getAttrib(elm, 'width');
return Optional.from(raw).filter(isNotEmpty);
};
var isPercentage = function (value) {
return /^(\d+(\.\d+)?)%$/.test(value);
};
var isPixel = function (value) {
return /^(\d+(\.\d+)?)px$/.test(value);
};
var getSelectionStart = function (editor) {
return SugarElement.fromDom(editor.selection.getStart());
};
var selection = function (selections) {
return cata(selections.get(), constant([]), identity, pure);
};
var unmergable = function (selections) {
var hasSpan = function (elem, type) {
return getOpt(elem, type).exists(function (span) {
return parseInt(span, 10) > 1;
});
};
var hasRowOrColSpan = function (elem) {
return hasSpan(elem, 'rowspan') || hasSpan(elem, 'colspan');
};
var candidates = selection(selections);
return candidates.length > 0 && forall(candidates, hasRowOrColSpan) ? Optional.some(candidates) : Optional.none();
};
var mergable = function (table, selections, ephemera) {
return cata(selections.get(), Optional.none, function (cells) {
if (cells.length <= 1) {
return Optional.none();
} else {
return retrieveBox(table, ephemera.firstSelectedSelector, ephemera.lastSelectedSelector).map(function (bounds) {
return {
bounds: bounds,
cells: cells
};
});
}
}, Optional.none);
};
var strSelected = 'data-mce-selected';
var strSelectedSelector = 'td[' + strSelected + '],th[' + strSelected + ']';
var strAttributeSelector = '[' + strSelected + ']';
var strFirstSelected = 'data-mce-first-selected';
var strFirstSelectedSelector = 'td[' + strFirstSelected + '],th[' + strFirstSelected + ']';
var strLastSelected = 'data-mce-last-selected';
var strLastSelectedSelector = 'td[' + strLastSelected + '],th[' + strLastSelected + ']';
var attributeSelector = strAttributeSelector;
var ephemera = {
selected: strSelected,
selectedSelector: strSelectedSelector,
firstSelected: strFirstSelected,
firstSelectedSelector: strFirstSelectedSelector,
lastSelected: strLastSelected,
lastSelectedSelector: strLastSelectedSelector
};
var noMenu = function (cell) {
return {
element: cell,
mergable: Optional.none(),
unmergable: Optional.none(),
selection: [cell]
};
};
var forMenu = function (selections, table, cell) {
return {
element: cell,
mergable: mergable(table, selections, ephemera),
unmergable: unmergable(selections),
selection: selection(selections)
};
};
var paste$1 = function (element, clipboard, generators) {
return {
element: element,
clipboard: clipboard,
generators: generators
};
};
var pasteRows = function (selections, cell, clipboard, generators) {
return {
selection: selection(selections),
clipboard: clipboard,
generators: generators
};
};
var extractSelected = function (cells) {
return table(cells[0]).map(function (table) {
var replica = extract(table, attributeSelector);
removeDataStyle(replica);
return [replica];
});
};
var serializeElements = function (editor, elements) {
return map(elements, function (elm) {
return editor.selection.serializer.serialize(elm.dom, {});
}).join('');
};
var getTextContent = function (elements) {
return map(elements, function (element) {
return element.dom.innerText;
}).join('');
};
var registerEvents = function (editor, selections, actions, cellSelection) {
editor.on('BeforeGetContent', function (e) {
var multiCellContext = function (cells) {
e.preventDefault();
extractSelected(cells).each(function (elements) {
e.content = e.format === 'text' ? getTextContent(elements) : serializeElements(editor, elements);
});
};
if (e.selection === true) {
cata(selections.get(), noop, multiCellContext, noop);
}
});
editor.on('BeforeSetContent', function (e) {
if (e.selection === true && e.paste === true) {
var cellOpt = Optional.from(editor.dom.getParent(editor.selection.getStart(), 'th,td'));
cellOpt.each(function (domCell) {
var cell = SugarElement.fromDom(domCell);
table(cell).each(function (table) {
var elements = filter(fromHtml$1(e.content), function (content) {
return name(content) !== 'meta';
});
var isTable = function (elm) {
return name(elm) === 'table';
};
if (elements.length === 1 && isTable(elements[0])) {
e.preventDefault();
var doc = SugarElement.fromDom(editor.getDoc());
var generators = paste(doc);
var targets = paste$1(cell, elements[0], generators);
actions.pasteCells(table, targets).each(function (data) {
editor.selection.setRng(data.rng);
editor.focus();
cellSelection.clear(table);
});
}
});
});
}
});
};
var adt = Adt.generate([
{ none: [] },
{ only: ['index'] },
{
left: [
'index',
'next'
]
},
{
middle: [
'prev',
'index',
'next'
]
},
{
right: [
'prev',
'index'
]
}
]);
var ColumnContext = __assign({}, adt);
var neighbours = function (input, index) {
if (input.length === 0) {
return ColumnContext.none();
}
if (input.length === 1) {
return ColumnContext.only(0);
}
if (index === 0) {
return ColumnContext.left(0, 1);
}
if (index === input.length - 1) {
return ColumnContext.right(index - 1, index);
}
if (index > 0 && index < input.length - 1) {
return ColumnContext.middle(index - 1, index, index + 1);
}
return ColumnContext.none();
};
var determine = function (input, column, step, tableSize, resize) {
var result = input.slice(0);
var context = neighbours(input, column);
var onNone = constant(map(result, constant(0)));
var onOnly = function (index) {
return tableSize.singleColumnWidth(result[index], step);
};
var onLeft = function (index, next) {
return resize.calcLeftEdgeDeltas(result, index, next, step, tableSize.minCellWidth(), tableSize.isRelative);
};
var onMiddle = function (prev, index, next) {
return resize.calcMiddleDeltas(result, prev, index, next, step, tableSize.minCellWidth(), tableSize.isRelative);
};
var onRight = function (prev, index) {
return resize.calcRightEdgeDeltas(result, prev, index, step, tableSize.minCellWidth(), tableSize.isRelative);
};
return context.fold(onNone, onOnly, onLeft, onMiddle, onRight);
};
var total = function (start, end, measures) {
var r = 0;
for (var i = start; i < end; i++) {
r += measures[i] !== undefined ? measures[i] : 0;
}
return r;
};
var recalculateWidthForCells = function (warehouse, widths) {
var all = Warehouse.justCells(warehouse);
return map(all, function (cell) {
var width = total(cell.column, cell.column + cell.colspan, widths);
return {
element: cell.element,
width: width,
colspan: cell.colspan
};
});
};
var recalculateWidthForColumns = function (warehouse, widths) {
var groups = Warehouse.justColumns(warehouse);
return map(groups, function (column, index) {
return {
element: column.element,
width: widths[index],
colspan: column.colspan
};
});
};
var recalculateHeightForCells = function (warehouse, heights) {
var all = Warehouse.justCells(warehouse);
return map(all, function (cell) {
var height = total(cell.row, cell.row + cell.rowspan, heights);
return {
element: cell.element,
height: height,
rowspan: cell.rowspan
};
});
};
var matchRowHeight = function (warehouse, heights) {
return map(warehouse.all, function (row, i) {
return {
element: row.element,
height: heights[i]
};
});
};
var sumUp = function (newSize) {
return foldr(newSize, function (b, a) {
return b + a;
}, 0);
};
var recalculate = function (warehouse, widths) {
if (Warehouse.hasColumns(warehouse)) {
return recalculateWidthForColumns(warehouse, widths);
} else {
return recalculateWidthForCells(warehouse, widths);
}
};
var recalculateAndApply = function (warehouse, widths, tableSize) {
var newSizes = recalculate(warehouse, widths);
each(newSizes, function (cell) {
tableSize.setElementWidth(cell.element, cell.width);
});
};
var adjustWidth = function (table, delta, index, resizing, tableSize) {
var warehouse = Warehouse.fromTable(table);
var step = tableSize.getCellDelta(delta);
var widths = tableSize.getWidths(warehouse, tableSize);
var isLastColumn = index === warehouse.grid.columns - 1;
var clampedStep = resizing.clampTableDelta(widths, index, step, tableSize.minCellWidth(), isLastColumn);
var deltas = determine(widths, index, clampedStep, tableSize, resizing);
var newWidths = map(deltas, function (dx, i) {
return dx + widths[i];
});
recalculateAndApply(warehouse, newWidths, tableSize);
resizing.resizeTable(tableSize.adjustTableWidth, clampedStep, isLastColumn);
};
var adjustHeight = function (table, delta, index, direction) {
var warehouse = Warehouse.fromTable(table);
var heights = getPixelHeights(warehouse, table, direction);
var newHeights = map(heights, function (dy, i) {
return index === i ? Math.max(delta + dy, minHeight()) : dy;
});
var newCellSizes = recalculateHeightForCells(warehouse, newHeights);
var newRowSizes = matchRowHeight(warehouse, newHeights);
each(newRowSizes, function (row) {
setHeight(row.element, row.height);
});
each(newCellSizes, function (cell) {
setHeight(cell.element, cell.height);
});
var total = sumUp(newHeights);
setHeight(table, total);
};
var adjustAndRedistributeWidths = function (_table, list, details, tableSize, resizeBehaviour) {
var warehouse = Warehouse.generate(list);
var sizes = tableSize.getWidths(warehouse, tableSize);
var tablePixelWidth = tableSize.pixelWidth();
var _a = resizeBehaviour.calcRedestributedWidths(sizes, tablePixelWidth, details.pixelDelta, tableSize.isRelative), newSizes = _a.newSizes, delta = _a.delta;
recalculateAndApply(warehouse, newSizes, tableSize);
tableSize.adjustTableWidth(delta);
};
var adjustWidthTo = function (_table, list, _info, tableSize) {
var warehouse = Warehouse.generate(list);
var widths = tableSize.getWidths(warehouse, tableSize);
recalculateAndApply(warehouse, widths, tableSize);
};
var zero = function (array) {
return map(array, constant(0));
};
var surround = function (sizes, startIndex, endIndex, results, f) {
return f(sizes.slice(0, startIndex)).concat(results).concat(f(sizes.slice(endIndex)));
};
var clampDeltaHelper = function (predicate) {
return function (sizes, index, delta, minCellSize) {
if (!predicate(delta)) {
return delta;
} else {
var newSize = Math.max(minCellSize, sizes[index] - Math.abs(delta));
var diff = Math.abs(newSize - sizes[index]);
return delta >= 0 ? diff : -diff;
}
};
};
var clampNegativeDelta = clampDeltaHelper(function (delta) {
return delta < 0;
});
var clampDelta = clampDeltaHelper(always);
var resizeTable = function () {
var calcFixedDeltas = function (sizes, index, next, delta, minCellSize) {
var clampedDelta = clampNegativeDelta(sizes, index, delta, minCellSize);
return surround(sizes, index, next + 1, [
clampedDelta,
0
], zero);
};
var calcRelativeDeltas = function (sizes, index, delta, minCellSize) {
var ratio = (100 + delta) / 100;
var newThis = Math.max(minCellSize, (sizes[index] + delta) / ratio);
return map(sizes, function (size, idx) {
var newSize = idx === index ? newThis : size / ratio;
return newSize - size;
});
};
var calcLeftEdgeDeltas = function (sizes, index, next, delta, minCellSize, isRelative) {
if (isRelative) {
return calcRelativeDeltas(sizes, index, delta, minCellSize);
} else {
return calcFixedDeltas(sizes, index, next, delta, minCellSize);
}
};
var calcMiddleDeltas = function (sizes, _prev, index, next, delta, minCellSize, isRelative) {
return calcLeftEdgeDeltas(sizes, index, next, delta, minCellSize, isRelative);
};
var resizeTable = function (resizer, delta) {
return resizer(delta);
};
var calcRightEdgeDeltas = function (sizes, _prev, index, delta, minCellSize, isRelative) {
if (isRelative) {
return calcRelativeDeltas(sizes, index, delta, minCellSize);
} else {
var clampedDelta = clampNegativeDelta(sizes, index, delta, minCellSize);
return zero(sizes.slice(0, index)).concat([clampedDelta]);
}
};
var calcRedestributedWidths = function (sizes, totalWidth, pixelDelta, isRelative) {
if (isRelative) {
var tableWidth = totalWidth + pixelDelta;
var ratio_1 = tableWidth / totalWidth;
var newSizes = map(sizes, function (size) {
return size / ratio_1;
});
return {
delta: ratio_1 * 100 - 100,
newSizes: newSizes
};
} else {
return {
delta: pixelDelta,
newSizes: sizes
};
}
};
return {
resizeTable: resizeTable,
clampTableDelta: clampNegativeDelta,
calcLeftEdgeDeltas: calcLeftEdgeDeltas,
calcMiddleDeltas: calcMiddleDeltas,
calcRightEdgeDeltas: calcRightEdgeDeltas,
calcRedestributedWidths: calcRedestributedWidths
};
};
var preserveTable = function () {
var calcLeftEdgeDeltas = function (sizes, index, next, delta, minCellSize) {
var idx = delta >= 0 ? next : index;
var clampedDelta = clampDelta(sizes, idx, delta, minCellSize);
return surround(sizes, index, next + 1, [
clampedDelta,
-clampedDelta
], zero);
};
var calcMiddleDeltas = function (sizes, _prev, index, next, delta, minCellSize) {
return calcLeftEdgeDeltas(sizes, index, next, delta, minCellSize);
};
var resizeTable = function (resizer, delta, isLastColumn) {
if (isLastColumn) {
resizer(delta);
}
};
var calcRightEdgeDeltas = function (sizes, _prev, _index, delta, _minCellSize, isRelative) {
if (isRelative) {
return zero(sizes);
} else {
var diff = delta / sizes.length;
return map(sizes, constant(diff));
}
};
var clampTableDelta = function (sizes, index, delta, minCellSize, isLastColumn) {
if (isLastColumn) {
if (delta >= 0) {
return delta;
} else {
var maxDelta = foldl(sizes, function (a, b) {
return a + b - minCellSize;
}, 0);
return Math.max(-maxDelta, delta);
}
} else {
return clampNegativeDelta(sizes, index, delta, minCellSize);
}
};
var calcRedestributedWidths = function (sizes, _totalWidth, _pixelDelta, _isRelative) {
return {
delta: 0,
newSizes: sizes
};
};
return {
resizeTable: resizeTable,
clampTableDelta: clampTableDelta,
calcLeftEdgeDeltas: calcLeftEdgeDeltas,
calcMiddleDeltas: calcMiddleDeltas,
calcRightEdgeDeltas: calcRightEdgeDeltas,
calcRedestributedWidths: calcRedestributedWidths
};
};
var only = function (element, isResizable) {
var parent = Optional.from(element.dom.documentElement).map(SugarElement.fromDom).getOr(element);
return {
parent: constant(parent),
view: constant(element),
origin: constant(SugarPosition(0, 0)),
isResizable: isResizable
};
};
var detached = function (editable, chrome, isResizable) {
var origin = function () {
return absolute(chrome);
};
return {
parent: constant(chrome),
view: constant(editable),
origin: origin,
isResizable: isResizable
};
};
var body$1 = function (editable, chrome, isResizable) {
return {
parent: constant(chrome),
view: constant(editable),
origin: constant(SugarPosition(0, 0)),
isResizable: isResizable
};
};
var ResizeWire = {
only: only,
detached: detached,
body: body$1
};
var adt$1 = Adt.generate([
{ invalid: ['raw'] },
{ pixels: ['value'] },
{ percent: ['value'] }
]);
var validateFor = function (suffix, type, value) {
var rawAmount = value.substring(0, value.length - suffix.length);
var amount = parseFloat(rawAmount);
return rawAmount === amount.toString() ? type(amount) : adt$1.invalid(value);
};
var from$1 = function (value) {
if (endsWith(value, '%')) {
return validateFor('%', adt$1.percent, value);
}
if (endsWith(value, 'px')) {
return validateFor('px', adt$1.pixels, value);
}
return adt$1.invalid(value);
};
var Size = __assign(__assign({}, adt$1), { from: from$1 });
var redistributeToPercent = function (widths, totalWidth) {
return map(widths, function (w) {
var colType = Size.from(w);
return colType.fold(function () {
return w;
}, function (px) {
var ratio = px / totalWidth * 100;
return ratio + '%';
}, function (pc) {
return pc + '%';
});
});
};
var redistributeToPx = function (widths, totalWidth, newTotalWidth) {
var scale = newTotalWidth / totalWidth;
return map(widths, function (w) {
var colType = Size.from(w);
return colType.fold(function () {
return w;
}, function (px) {
return px * scale + 'px';
}, function (pc) {
return pc / 100 * newTotalWidth + 'px';
});
});
};
var redistributeEmpty = function (newWidthType, columns) {
var f = newWidthType.fold(function () {
return constant('');
}, function (pixels) {
var num = pixels / columns;
return constant(num + 'px');
}, function () {
var num = 100 / columns;
return constant(num + '%');
});
return range(columns, f);
};
var redistributeValues = function (newWidthType, widths, totalWidth) {
return newWidthType.fold(function () {
return widths;
}, function (px) {
return redistributeToPx(widths, totalWidth, px);
}, function (_pc) {
return redistributeToPercent(widths, totalWidth);
});
};
var redistribute = function (widths, totalWidth, newWidth) {
var newType = Size.from(newWidth);
var floats = forall(widths, function (s) {
return s === '0px';
}) ? redistributeEmpty(newType, widths.length) : redistributeValues(newType, widths, totalWidth);
return normalize(floats);
};
var sum = function (values, fallback) {
if (values.length === 0) {
return fallback;
}
return foldr(values, function (rest, v) {
return Size.from(v).fold(constant(0), identity, identity) + rest;
}, 0);
};
var roundDown = function (num, unit) {
var floored = Math.floor(num);
return {
value: floored + unit,
remainder: num - floored
};
};
var add = function (value, amount) {
return Size.from(value).fold(constant(value), function (px) {
return px + amount + 'px';
}, function (pc) {
return pc + amount + '%';
});
};
var normalize = function (values) {
if (values.length === 0) {
return values;
}
var scan = foldr(values, function (rest, value) {
var info = Size.from(value).fold(function () {
return {
value: value,
remainder: 0
};
}, function (num) {
return roundDown(num, 'px');
}, function (num) {
return {
value: num + '%',
remainder: 0
};
});
return {
output: [info.value].concat(rest.output),
remainder: rest.remainder + info.remainder
};
}, {
output: [],
remainder: 0
});
var r = scan.output;
return r.slice(0, r.length - 1).concat([add(r[r.length - 1], Math.round(scan.remainder))]);
};
var validate = Size.from;
var redistributeToW = function (newWidths, cells, unit) {
each(cells, function (cell) {
var widths = newWidths.slice(cell.column, cell.colspan + cell.column);
var w = sum(widths, minWidth());
set$1(cell.element, 'width', w + unit);
});
};
var redistributeToColumns = function (newWidths, columns, unit) {
each(columns, function (column, index) {
var width = sum([newWidths[index]], minWidth());
set$1(column.element, 'width', width + unit);
});
};
var redistributeToH = function (newHeights, rows, cells, unit) {
each(cells, function (cell) {
var heights = newHeights.slice(cell.row, cell.rowspan + cell.row);
var h = sum(heights, minHeight());
set$1(cell.element, 'height', h + unit);
});
each(rows, function (row, i) {
set$1(row.element, 'height', newHeights[i]);
});
};
var getUnit = function (newSize) {
return validate(newSize).fold(constant('px'), constant('px'), constant('%'));
};
var redistribute$1 = function (table, optWidth, optHeight, tableSize) {
var warehouse = Warehouse.fromTable(table);
var rows = warehouse.all;
var cells = Warehouse.justCells(warehouse);
var columns = Warehouse.justColumns(warehouse);
optWidth.each(function (newWidth) {
var widthUnit = getUnit(newWidth);
var totalWidth = get$5(table);
var oldWidths = getRawWidths(warehouse, table, tableSize);
var nuWidths = redistribute(oldWidths, totalWidth, newWidth);
if (Warehouse.hasColumns(warehouse)) {
redistributeToColumns(nuWidths, columns, widthUnit);
} else {
redistributeToW(nuWidths, cells, widthUnit);
}
set$1(table, 'width', newWidth);
});
optHeight.each(function (newHeight) {
var hUnit = getUnit(newHeight);
var totalHeight = get$6(table);
var oldHeights = getRawHeights(warehouse, table, height);
var nuHeights = redistribute(oldHeights, totalHeight, newHeight);
redistributeToH(nuHeights, rows, cells, hUnit);
set$1(table, 'height', newHeight);
});
};
var isPercentSizing$1 = isPercentSizing;
var isPixelSizing$1 = isPixelSizing;
var isNoneSizing$1 = isNoneSizing;
var getPercentTableWidth$1 = getPercentTableWidth;
var getGridSize = function (table) {
var warehouse = Warehouse.fromTable(table);
return warehouse.grid;
};
var Event = function (fields) {
var handlers = [];
var bind = function (handler) {
if (handler === undefined) {
throw new Error('Event bind error: undefined handler');
}
handlers.push(handler);
};
var unbind = function (handler) {
handlers = filter(handlers, function (h) {
return h !== handler;
});
};
var trigger = function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
var event = {};
each(fields, function (name, i) {
event[name] = args[i];
});
each(handlers, function (handler) {
handler(event);
});
};
return {
bind: bind,
unbind: unbind,
trigger: trigger
};
};
var create = function (typeDefs) {
var registry = map$1(typeDefs, function (event) {
return {
bind: event.bind,
unbind: event.unbind
};
});
var trigger = map$1(typeDefs, function (event) {
return event.trigger;
});
return {
registry: registry,
trigger: trigger
};
};
var last$2 = function (fn, rate) {
var timer = null;
var cancel = function () {
if (timer !== null) {
clearTimeout(timer);
timer = null;
}
};
var throttle = function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
if (timer !== null) {
clearTimeout(timer);
}
timer = setTimeout(function () {
fn.apply(null, args);
timer = null;
}, rate);
};
return {
cancel: cancel,
throttle: throttle
};
};
var sort$1 = function (arr) {
return arr.slice(0).sort();
};
var reqMessage = function (required, keys) {
throw new Error('All required keys (' + sort$1(required).join(', ') + ') were not specified. Specified keys were: ' + sort$1(keys).join(', ') + '.');
};
var unsuppMessage = function (unsupported) {
throw new Error('Unsupported keys for object: ' + sort$1(unsupported).join(', '));
};
var validateStrArr = function (label, array) {
if (!isArray(array)) {
throw new Error('The ' + label + ' fields must be an array. Was: ' + array + '.');
}
each(array, function (a) {
if (!isString(a)) {
throw new Error('The value ' + a + ' in the ' + label + ' fields was not a string.');
}
});
};
var invalidTypeMessage = function (incorrect, type) {
throw new Error('All values need to be of type: ' + type + '. Keys (' + sort$1(incorrect).join(', ') + ') were not.');
};
var checkDupes = function (everything) {
var sorted = sort$1(everything);
var dupe = find(sorted, function (s, i) {
return i < sorted.length - 1 && s === sorted[i + 1];
});
dupe.each(function (d) {
throw new Error('The field: ' + d + ' occurs more than once in the combined fields: [' + sorted.join(', ') + '].');
});
};
var base = function (handleUnsupported, required) {
return baseWith(handleUnsupported, required, {
validate: isFunction,
label: 'function'
});
};
var baseWith = function (handleUnsupported, required, pred) {
if (required.length === 0) {
throw new Error('You must specify at least one required field.');
}
validateStrArr('required', required);
checkDupes(required);
return function (obj) {
var keys$1 = keys(obj);
var allReqd = forall(required, function (req) {
return contains(keys$1, req);
});
if (!allReqd) {
reqMessage(required, keys$1);
}
handleUnsupported(required, keys$1);
var invalidKeys = filter(required, function (key) {
return !pred.validate(obj[key], key);
});
if (invalidKeys.length > 0) {
invalidTypeMessage(invalidKeys, pred.label);
}
return obj;
};
};
var handleExact = function (required, keys) {
var unsupported = filter(keys, function (key) {
return !contains(required, key);
});
if (unsupported.length > 0) {
unsuppMessage(unsupported);
}
};
var exactly = function (required) {
return base(handleExact, required);
};
var DragMode = exactly([
'compare',
'extract',
'mutate',
'sink'
]);
var DragSink = exactly([
'element',
'start',
'stop',
'destroy'
]);
var DragApi = exactly([
'forceDrop',
'drop',
'move',
'delayDrop'
]);
var InDrag = function () {
var previous = Optional.none();
var reset = function () {
previous = Optional.none();
};
var update = function (mode, nu) {
var result = previous.map(function (old) {
return mode.compare(old, nu);
});
previous = Optional.some(nu);
return result;
};
var onEvent = function (event, mode) {
var dataOption = mode.extract(event);
dataOption.each(function (data) {
var offset = update(mode, data);
offset.each(function (d) {
events.trigger.move(d);
});
});
};
var events = create({ move: Event(['info']) });
return {
onEvent: onEvent,
reset: reset,
events: events.registry
};
};
var NoDrag = function () {
var events = create({ move: Event(['info']) });
return {
onEvent: noop,
reset: noop,
events: events.registry
};
};
var Movement = function () {
var noDragState = NoDrag();
var inDragState = InDrag();
var dragState = noDragState;
var on = function () {
dragState.reset();
dragState = inDragState;
};
var off = function () {
dragState.reset();
dragState = noDragState;
};
var onEvent = function (event, mode) {
dragState.onEvent(event, mode);
};
var isOn = function () {
return dragState === inDragState;
};
return {
on: on,
off: off,
isOn: isOn,
onEvent: onEvent,
events: inDragState.events
};
};
var setup = function (mutation, mode, settings) {
var active = false;
var events = create({
start: Event([]),
stop: Event([])
});
var movement = Movement();
var drop = function () {
sink.stop();
if (movement.isOn()) {
movement.off();
events.trigger.stop();
}
};
var throttledDrop = last$2(drop, 200);
var go = function (parent) {
sink.start(parent);
movement.on();
events.trigger.start();
};
var mousemove = function (event) {
throttledDrop.cancel();
movement.onEvent(event, mode);
};
movement.events.move.bind(function (event) {
mode.mutate(mutation, event.info);
});
var on = function () {
active = true;
};
var off = function () {
active = false;
};
var runIfActive = function (f) {
return function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
if (active) {
f.apply(null, args);
}
};
};
var sink = mode.sink(DragApi({
forceDrop: drop,
drop: runIfActive(drop),
move: runIfActive(mousemove),
delayDrop: runIfActive(throttledDrop.throttle)
}), settings);
var destroy = function () {
sink.destroy();
};
return {
element: sink.element,
go: go,
on: on,
off: off,
destroy: destroy,
events: events.registry
};
};
var mkEvent = function (target, x, y, stop, prevent, kill, raw) {
return {
target: target,
x: x,
y: y,
stop: stop,
prevent: prevent,
kill: kill,
raw: raw
};
};
var fromRawEvent = function (rawEvent) {
var target = SugarElement.fromDom(getOriginalEventTarget(rawEvent).getOr(rawEvent.target));
var stop = function () {
return rawEvent.stopPropagation();
};
var prevent = function () {
return rawEvent.preventDefault();
};
var kill = compose(prevent, stop);
return mkEvent(target, rawEvent.clientX, rawEvent.clientY, stop, prevent, kill, rawEvent);
};
var handle = function (filter, handler) {
return function (rawEvent) {
if (filter(rawEvent)) {
handler(fromRawEvent(rawEvent));
}
};
};
var binder = function (element, event, filter, handler, useCapture) {
var wrapped = handle(filter, handler);
element.dom.addEventListener(event, wrapped, useCapture);
return { unbind: curry(unbind, element, event, wrapped, useCapture) };
};
var bind$1 = function (element, event, filter, handler) {
return binder(element, event, filter, handler, false);
};
var unbind = function (element, event, handler, useCapture) {
element.dom.removeEventListener(event, handler, useCapture);
};
var filter$2 = always;
var bind$2 = function (element, event, handler) {
return bind$1(element, event, filter$2, handler);
};
var fromRawEvent$1 = fromRawEvent;
var read = function (element, attr) {
var value = get$2(element, attr);
return value === undefined || value === '' ? [] : value.split(' ');
};
var add$1 = function (element, attr, id) {
var old = read(element, attr);
var nu = old.concat([id]);
set(element, attr, nu.join(' '));
return true;
};
var remove$3 = function (element, attr, id) {
var nu = filter(read(element, attr), function (v) {
return v !== id;
});
if (nu.length > 0) {
set(element, attr, nu.join(' '));
} else {
remove(element, attr);
}
return false;
};
var supports = function (element) {
return element.dom.classList !== undefined;
};
var get$8 = function (element) {
return read(element, 'class');
};
var add$2 = function (element, clazz) {
return add$1(element, 'class', clazz);
};
var remove$4 = function (element, clazz) {
return remove$3(element, 'class', clazz);
};
var add$3 = function (element, clazz) {
if (supports(element)) {
element.dom.classList.add(clazz);
} else {
add$2(element, clazz);
}
};
var cleanClass = function (element) {
var classList = supports(element) ? element.dom.classList : get$8(element);
if (classList.length === 0) {
remove(element, 'class');
}
};
var remove$5 = function (element, clazz) {
if (supports(element)) {
var classList = element.dom.classList;
classList.remove(clazz);
} else {
remove$4(element, clazz);
}
cleanClass(element);
};
var has$1 = function (element, clazz) {
return supports(element) && element.dom.classList.contains(clazz);
};
var css = function (namespace) {
var dashNamespace = namespace.replace(/\./g, '-');
var resolve = function (str) {
return dashNamespace + '-' + str;
};
return { resolve: resolve };
};
var styles = css('ephox-dragster');
var resolve = styles.resolve;
var Blocker = function (options) {
var settings = __assign({ layerClass: resolve('blocker') }, options);
var div = SugarElement.fromTag('div');
set(div, 'role', 'presentation');
setAll$1(div, {
position: 'fixed',
left: '0px',
top: '0px',
width: '100%',
height: '100%'
});
add$3(div, resolve('blocker'));
add$3(div, settings.layerClass);
var element = function () {
return div;
};
var destroy = function () {
remove$2(div);
};
return {
element: element,
destroy: destroy
};
};
var compare = function (old, nu) {
return SugarPosition(nu.left - old.left, nu.top - old.top);
};
var extract$1 = function (event) {
return Optional.some(SugarPosition(event.x, event.y));
};
var mutate = function (mutation, info) {
mutation.mutate(info.left, info.top);
};
var sink = function (dragApi, settings) {
var blocker = Blocker(settings);
var mdown = bind$2(blocker.element(), 'mousedown', dragApi.forceDrop);
var mup = bind$2(blocker.element(), 'mouseup', dragApi.drop);
var mmove = bind$2(blocker.element(), 'mousemove', dragApi.move);
var mout = bind$2(blocker.element(), 'mouseout', dragApi.delayDrop);
var destroy = function () {
blocker.destroy();
mup.unbind();
mmove.unbind();
mout.unbind();
mdown.unbind();
};
var start = function (parent) {
append(parent, blocker.element());
};
var stop = function () {
remove$2(blocker.element());
};
return DragSink({
element: blocker.element,
start: start,
stop: stop,
destroy: destroy
});
};
var MouseDrag = DragMode({
compare: compare,
extract: extract$1,
sink: sink,
mutate: mutate
});
var transform = function (mutation, settings) {
if (settings === void 0) {
settings = {};
}
var mode = settings.mode !== undefined ? settings.mode : MouseDrag;
return setup(mutation, mode, settings);
};
var isContentEditableTrue = function (elm) {
return get$2(elm, 'contenteditable') === 'true';
};
var findClosestContentEditable = function (target, isRoot) {
return closest$1(target, '[contenteditable]', isRoot);
};
var styles$1 = css('ephox-snooker');
var resolve$1 = styles$1.resolve;
var Mutation = function () {
var events = create({
drag: Event([
'xDelta',
'yDelta'
])
});
var mutate = function (x, y) {
events.trigger.drag(x, y);
};
return {
mutate: mutate,
events: events.registry
};
};
var BarMutation = function () {
var events = create({
drag: Event([
'xDelta',
'yDelta',
'target'
])
});
var target = Optional.none();
var delegate = Mutation();
delegate.events.drag.bind(function (event) {
target.each(function (t) {
events.trigger.drag(event.xDelta, event.yDelta, t);
});
});
var assign = function (t) {
target = Optional.some(t);
};
var get = function () {
return target;
};
return {
assign: assign,
get: get,
mutate: delegate.mutate,
events: events.registry
};
};
var col = function (column, x, y, w, h) {
var bar = SugarElement.fromTag('div');
setAll$1(bar, {
position: 'absolute',
left: x - w / 2 + 'px',
top: y + 'px',
height: h + 'px',
width: w + 'px'
});
setAll(bar, {
'data-column': column,
'role': 'presentation'
});
return bar;
};
var row = function (r, x, y, w, h) {
var bar = SugarElement.fromTag('div');
setAll$1(bar, {
position: 'absolute',
left: x + 'px',
top: y - h / 2 + 'px',
height: h + 'px',
width: w + 'px'
});
setAll(bar, {
'data-row': r,
'role': 'presentation'
});
return bar;
};
var resizeBar = resolve$1('resizer-bar');
var resizeRowBar = resolve$1('resizer-rows');
var resizeColBar = resolve$1('resizer-cols');
var BAR_THICKNESS = 7;
var resizableRows = function (warehouse, isResizable) {
return bind(warehouse.all, function (row, i) {
return isResizable(row.element) ? [i] : [];
});
};
var resizableColumns = function (warehouse, isResizable) {
var resizableCols = [];
range(warehouse.grid.columns, function (index) {
var colElmOpt = Warehouse.getColumnAt(warehouse, index).map(function (col) {
return col.element;
});
if (colElmOpt.forall(isResizable)) {
resizableCols.push(index);
}
});
return filter(resizableCols, function (colIndex) {
var columnCells = Warehouse.filterItems(warehouse, function (cell) {
return cell.column === colIndex;
});
return forall(columnCells, function (cell) {
return isResizable(cell.element);
});
});
};
var destroy = function (wire) {
var previous = descendants$1(wire.parent(), '.' + resizeBar);
each(previous, remove$2);
};
var drawBar = function (wire, positions, create) {
var origin = wire.origin();
each(positions, function (cpOption) {
cpOption.each(function (cp) {
var bar = create(origin, cp);
add$3(bar, resizeBar);
append(wire.parent(), bar);
});
});
};
var refreshCol = function (wire, colPositions, position, tableHeight) {
drawBar(wire, colPositions, function (origin, cp) {
var colBar = col(cp.col, cp.x - origin.left, position.top - origin.top, BAR_THICKNESS, tableHeight);
add$3(colBar, resizeColBar);
return colBar;
});
};
var refreshRow = function (wire, rowPositions, position, tableWidth) {
drawBar(wire, rowPositions, function (origin, cp) {
var rowBar = row(cp.row, position.left - origin.left, cp.y - origin.top, tableWidth, BAR_THICKNESS);
add$3(rowBar, resizeRowBar);
return rowBar;
});
};
var refreshGrid = function (warhouse, wire, table, rows, cols) {
var position = absolute(table);
var isResizable = wire.isResizable;
var rowPositions = rows.length > 0 ? height.positions(rows, table) : [];
var resizableRowBars = rowPositions.length > 0 ? resizableRows(warhouse, isResizable) : [];
var resizableRowPositions = filter(rowPositions, function (_pos, i) {
return exists(resizableRowBars, function (barIndex) {
return i === barIndex;
});
});
refreshRow(wire, resizableRowPositions, position, getOuter(table));
var colPositions = cols.length > 0 ? width.positions(cols, table) : [];
var resizableColBars = colPositions.length > 0 ? resizableColumns(warhouse, isResizable) : [];
var resizableColPositions = filter(colPositions, function (_pos, i) {
return exists(resizableColBars, function (barIndex) {
return i === barIndex;
});
});
refreshCol(wire, resizableColPositions, position, getOuter$1(table));
};
var refresh = function (wire, table) {
destroy(wire);
if (wire.isResizable(table)) {
var warehouse = Warehouse.fromTable(table);
var rows = rows$1(warehouse);
var cols = columns$1(warehouse);
refreshGrid(warehouse, wire, table, rows, cols);
}
};
var each$2 = function (wire, f) {
var bars = descendants$1(wire.parent(), '.' + resizeBar);
each(bars, f);
};
var hide = function (wire) {
each$2(wire, function (bar) {
set$1(bar, 'display', 'none');
});
};
var show = function (wire) {
each$2(wire, function (bar) {
set$1(bar, 'display', 'block');
});
};
var isRowBar = function (element) {
return has$1(element, resizeRowBar);
};
var isColBar = function (element) {
return has$1(element, resizeColBar);
};
var resizeBarDragging = resolve$1('resizer-bar-dragging');
var BarManager = function (wire) {
var mutation = BarMutation();
var resizing = transform(mutation, {});
var hoverTable = Optional.none();
var getResizer = function (element, type) {
return Optional.from(get$2(element, type));
};
mutation.events.drag.bind(function (event) {
getResizer(event.target, 'data-row').each(function (_dataRow) {
var currentRow = getCssValue(event.target, 'top');
set$1(event.target, 'top', currentRow + event.yDelta + 'px');
});
getResizer(event.target, 'data-column').each(function (_dataCol) {
var currentCol = getCssValue(event.target, 'left');
set$1(event.target, 'left', currentCol + event.xDelta + 'px');
});
});
var getDelta = function (target, dir) {
var newX = getCssValue(target, dir);
var oldX = getAttrValue(target, 'data-initial-' + dir, 0);
return newX - oldX;
};
resizing.events.stop.bind(function () {
mutation.get().each(function (target) {
hoverTable.each(function (table) {
getResizer(target, 'data-row').each(function (row) {
var delta = getDelta(target, 'top');
remove(target, 'data-initial-top');
events.trigger.adjustHeight(table, delta, parseInt(row, 10));
});
getResizer(target, 'data-column').each(function (column) {
var delta = getDelta(target, 'left');
remove(target, 'data-initial-left');
events.trigger.adjustWidth(table, delta, parseInt(column, 10));
});
refresh(wire, table);
});
});
});
var handler = function (target, dir) {
events.trigger.startAdjust();
mutation.assign(target);
set(target, 'data-initial-' + dir, getCssValue(target, dir));
add$3(target, resizeBarDragging);
set$1(target, 'opacity', '0.2');
resizing.go(wire.parent());
};
var mousedown = bind$2(wire.parent(), 'mousedown', function (event) {
if (isRowBar(event.target)) {
handler(event.target, 'top');
}
if (isColBar(event.target)) {
handler(event.target, 'left');
}
});
var isRoot = function (e) {
return eq$1(e, wire.view());
};
var findClosestEditableTable = function (target) {
return closest$1(target, 'table', isRoot).filter(function (table) {
return findClosestContentEditable(table, isRoot).exists(isContentEditableTrue);
});
};
var mouseover = bind$2(wire.view(), 'mouseover', function (event) {
findClosestEditableTable(event.target).fold(function () {
if (inBody(event.target)) {
destroy(wire);
}
}, function (table) {
hoverTable = Optional.some(table);
refresh(wire, table);
});
});
var destroy$1 = function () {
mousedown.unbind();
mouseover.unbind();
resizing.destroy();
destroy(wire);
};
var refresh$1 = function (tbl) {
refresh(wire, tbl);
};
var events = create({
adjustHeight: Event([
'table',
'delta',
'row'
]),
adjustWidth: Event([
'table',
'delta',
'column'
]),
startAdjust: Event([])
});
return {
destroy: destroy$1,
refresh: refresh$1,
on: resizing.on,
off: resizing.off,
hideBars: curry(hide, wire),
showBars: curry(show, wire),
events: events.registry
};
};
var create$1 = function (wire, resizing, lazySizing) {
var hdirection = height;
var vdirection = width;
var manager = BarManager(wire);
var events = create({
beforeResize: Event([
'table',
'type'
]),
afterResize: Event([
'table',
'type'
]),
startDrag: Event([])
});
manager.events.adjustHeight.bind(function (event) {
var table = event.table;
events.trigger.beforeResize(table, 'row');
var delta = hdirection.delta(event.delta, table);
adjustHeight(table, delta, event.row, hdirection);
events.trigger.afterResize(table, 'row');
});
manager.events.startAdjust.bind(function (_event) {
events.trigger.startDrag();
});
manager.events.adjustWidth.bind(function (event) {
var table = event.table;
events.trigger.beforeResize(table, 'col');
var delta = vdirection.delta(event.delta, table);
var tableSize = lazySizing(table);
adjustWidth(table, delta, event.column, resizing, tableSize);
events.trigger.afterResize(table, 'col');
});
return {
on: manager.on,
off: manager.off,
hideBars: manager.hideBars,
showBars: manager.showBars,
destroy: manager.destroy,
events: events.registry
};
};
var TableResize = { create: create$1 };
var fireNewRow = function (editor, row) {
return editor.fire('newrow', { node: row });
};
var fireNewCell = function (editor, cell) {
return editor.fire('newcell', { node: cell });
};
var fireObjectResizeStart = function (editor, target, width, height, origin) {
editor.fire('ObjectResizeStart', {
target: target,
width: width,
height: height,
origin: origin
});
};
var fireObjectResized = function (editor, target, width, height, origin) {
editor.fire('ObjectResized', {
target: target,
width: width,
height: height,
origin: origin
});
};
var fireTableSelectionChange = function (editor, cells, start, finish, otherCells) {
editor.fire('TableSelectionChange', {
cells: cells,
start: start,
finish: finish,
otherCells: otherCells
});
};
var fireTableSelectionClear = function (editor) {
editor.fire('TableSelectionClear');
};
var fireTableModified = function (editor, table, data) {
editor.fire('TableModified', __assign(__assign({}, data), { table: table }));
};
var styleModified = {
structure: false,
style: true
};
var structureModified = {
structure: true,
style: false
};
var defaultTableToolbar = 'tableprops tabledelete | tableinsertrowbefore tableinsertrowafter tabledeleterow | tableinsertcolbefore tableinsertcolafter tabledeletecol';
var defaultStyles = {
'border-collapse': 'collapse',
'width': '100%'
};
var determineDefaultStyles = function (editor) {
if (isPixelsForced(editor)) {
var editorWidth = editor.getBody().offsetWidth;
return __assign(__assign({}, defaultStyles), { width: editorWidth + 'px' });
} else if (isResponsiveForced(editor)) {
return filter$1(defaultStyles, function (_value, key) {
return key !== 'width';
});
} else {
return defaultStyles;
}
};
var defaultAttributes = { border: '1' };
var defaultColumnResizingBehaviour = 'preservetable';
var getTableSizingMode = function (editor) {
return editor.getParam('table_sizing_mode', 'auto');
};
var getTableResponseWidth = function (editor) {
return editor.getParam('table_responsive_width');
};
var getDefaultAttributes = function (editor) {
return editor.getParam('table_default_attributes', defaultAttributes, 'object');
};
var getDefaultStyles = function (editor) {
return editor.getParam('table_default_styles', determineDefaultStyles(editor), 'object');
};
var hasTableResizeBars = function (editor) {
return editor.getParam('table_resize_bars', true, 'boolean');
};
var hasTabNavigation = function (editor) {
return editor.getParam('table_tab_navigation', true, 'boolean');
};
var hasAdvancedCellTab = function (editor) {
return editor.getParam('table_cell_advtab', true, 'boolean');
};
var hasAdvancedRowTab = function (editor) {
return editor.getParam('table_row_advtab', true, 'boolean');
};
var hasAdvancedTableTab = function (editor) {
return editor.getParam('table_advtab', true, 'boolean');
};
var hasAppearanceOptions = function (editor) {
return editor.getParam('table_appearance_options', true, 'boolean');
};
var hasTableGrid = function (editor) {
return editor.getParam('table_grid', true, 'boolean');
};
var shouldStyleWithCss = function (editor) {
return editor.getParam('table_style_by_css', false, 'boolean');
};
var getCellClassList = function (editor) {
return editor.getParam('table_cell_class_list', [], 'array');
};
var getRowClassList = function (editor) {
return editor.getParam('table_row_class_list', [], 'array');
};
var getTableClassList = function (editor) {
return editor.getParam('table_class_list', [], 'array');
};
var isPercentagesForced = function (editor) {
return getTableSizingMode(editor) === 'relative' || getTableResponseWidth(editor) === true;
};
var isPixelsForced = function (editor) {
return getTableSizingMode(editor) === 'fixed' || getTableResponseWidth(editor) === false;
};
var isResponsiveForced = function (editor) {
return getTableSizingMode(editor) === 'responsive';
};
var getToolbar = function (editor) {
return editor.getParam('table_toolbar', defaultTableToolbar);
};
var useColumnGroup = function (editor) {
return editor.getParam('table_use_colgroups', false, 'boolean');
};
var getTableHeaderType = function (editor) {
var defaultValue = 'section';
var value = editor.getParam('table_header_type', defaultValue, 'string');
var validValues = [
'section',
'cells',
'sectionCells',
'auto'
];
if (!contains(validValues, value)) {
return defaultValue;
} else {
return value;
}
};
var getColumnResizingBehaviour = function (editor) {
var validModes = [
'preservetable',
'resizetable'
];
var givenMode = editor.getParam('table_column_resizing', defaultColumnResizingBehaviour, 'string');
return find(validModes, function (mode) {
return mode === givenMode;
}).getOr(defaultColumnResizingBehaviour);
};
var isPreserveTableColumnResizing = function (editor) {
return getColumnResizingBehaviour(editor) === 'preservetable';
};
var isResizeTableColumnResizing = function (editor) {
return getColumnResizingBehaviour(editor) === 'resizetable';
};
var getCloneElements = function (editor) {
var cloneElements = editor.getParam('table_clone_elements');
if (isString(cloneElements)) {
return Optional.some(cloneElements.split(/[ ,]/));
} else if (Array.isArray(cloneElements)) {
return Optional.some(cloneElements);
} else {
return Optional.none();
}
};
var hasObjectResizing = function (editor) {
var objectResizing = editor.getParam('object_resizing', true);
return isString(objectResizing) ? objectResizing === 'table' : objectResizing;
};
var get$9 = function (editor, table) {
if (isPercentagesForced(editor)) {
var width = getRawWidth$1(editor, table.dom).filter(isPercentage).getOrThunk(function () {
return getPercentTableWidth$1(table);
});
return TableSize.percentageSize(width, table);
} else if (isPixelsForced(editor)) {
return TableSize.pixelSize(get$5(table), table);
} else {
return TableSize.getTableSize(table);
}
};
var cleanupLegacyAttributes = function (element) {
remove(element, 'width');
};
var convertToPercentSize = function (table, tableSize) {
var newWidth = getPercentTableWidth(table);
redistribute$1(table, Optional.some(newWidth), Optional.none(), tableSize);
cleanupLegacyAttributes(table);
};
var convertToPixelSize = function (table, tableSize) {
var newWidth = getPixelTableWidth(table);
redistribute$1(table, Optional.some(newWidth), Optional.none(), tableSize);
cleanupLegacyAttributes(table);
};
var convertToNoneSize = function (table) {
remove$1(table, 'width');
var columns$1 = columns(table);
var rowElements = columns$1.length > 0 ? columns$1 : cells(table);
each(rowElements, function (cell) {
remove$1(cell, 'width');
cleanupLegacyAttributes(cell);
});
cleanupLegacyAttributes(table);
};
var enforcePercentage = function (editor, table) {
var tableSizing = get$9(editor, table);
convertToPercentSize(table, tableSizing);
};
var enforcePixels = function (editor, table) {
var tableSizing = get$9(editor, table);
convertToPixelSize(table, tableSizing);
};
var enforceNone = convertToNoneSize;
var syncPixels = function (table) {
var warehouse = Warehouse.fromTable(table);
if (!Warehouse.hasColumns(warehouse)) {
each(cells(table), function (cell) {
var computedWidth = get$3(cell, 'width');
set$1(cell, 'width', computedWidth);
remove(cell, 'width');
});
}
};
var createContainer = function () {
var container = SugarElement.fromTag('div');
setAll$1(container, {
position: 'static',
height: '0',
width: '0',
padding: '0',
margin: '0',
border: '0'
});
append(body(), container);
return container;
};
var get$a = function (editor, isResizable) {
return editor.inline ? ResizeWire.body(getBody$1(editor), createContainer(), isResizable) : ResizeWire.only(SugarElement.fromDom(editor.getDoc()), isResizable);
};
var remove$6 = function (editor, wire) {
if (editor.inline) {
remove$2(wire.parent());
}
};
var barResizerPrefix = 'bar-';
var isResizable = function (elm) {
return get$2(elm, 'data-mce-resize') !== 'false';
};
var getResizeHandler = function (editor) {
var selectionRng = Optional.none();
var resize = Optional.none();
var wire = Optional.none();
var startW;
var startRawW;
var isTable = function (elm) {
return elm.nodeName === 'TABLE';
};
var lazyResize = function () {
return resize;
};
var lazyWire = function () {
return wire.getOr(ResizeWire.only(SugarElement.fromDom(editor.getBody()), isResizable));
};
var lazySizing = function (table) {
return get$9(editor, table);
};
var lazyResizingBehaviour = function () {
return isPreserveTableColumnResizing(editor) ? preserveTable() : resizeTable();
};
var getNumColumns = function (table) {
return getGridSize(table).columns;
};
var afterCornerResize = function (table, origin, width) {
var isRightEdgeResize = endsWith(origin, 'e');
if (startRawW === '') {
enforcePercentage(editor, table);
}
if (width !== startW && startRawW !== '') {
set$1(table, 'width', startRawW);
var resizing = lazyResizingBehaviour();
var tableSize = lazySizing(table);
var col = isPreserveTableColumnResizing(editor) || isRightEdgeResize ? getNumColumns(table) - 1 : 0;
adjustWidth(table, width - startW, col, resizing, tableSize);
} else if (isPercentage(startRawW)) {
var percentW = parseFloat(startRawW.replace('%', ''));
var targetPercentW = width * percentW / startW;
set$1(table, 'width', targetPercentW + '%');
}
if (isPixel(startRawW)) {
syncPixels(table);
}
};
var destroy = function () {
resize.each(function (sz) {
sz.destroy();
});
wire.each(function (w) {
remove$6(editor, w);
});
};
editor.on('init', function () {
var rawWire = get$a(editor, isResizable);
wire = Optional.some(rawWire);
if (hasObjectResizing(editor) && hasTableResizeBars(editor)) {
var resizing = lazyResizingBehaviour();
var sz = TableResize.create(rawWire, resizing, lazySizing);
sz.on();
sz.events.startDrag.bind(function (_event) {
selectionRng = Optional.some(editor.selection.getRng());
});
sz.events.beforeResize.bind(function (event) {
var rawTable = event.table.dom;
fireObjectResizeStart(editor, rawTable, getPixelWidth$1(rawTable), getPixelHeight(rawTable), barResizerPrefix + event.type);
});
sz.events.afterResize.bind(function (event) {
var table = event.table;
var rawTable = table.dom;
removeDataStyle(table);
selectionRng.each(function (rng) {
editor.selection.setRng(rng);
editor.focus();
});
fireObjectResized(editor, rawTable, getPixelWidth$1(rawTable), getPixelHeight(rawTable), barResizerPrefix + event.type);
editor.undoManager.add();
});
resize = Optional.some(sz);
}
});
editor.on('ObjectResizeStart', function (e) {
var targetElm = e.target;
if (isTable(targetElm)) {
var table = SugarElement.fromDom(targetElm);
each(editor.dom.select('.mce-clonedresizable'), function (clone) {
editor.dom.addClass(clone, 'mce-' + getColumnResizingBehaviour(editor) + '-columns');
});
if (!isPixelSizing$1(table) && isPixelsForced(editor)) {
enforcePixels(editor, table);
} else if (!isPercentSizing$1(table) && isPercentagesForced(editor)) {
enforcePercentage(editor, table);
}
if (isNoneSizing$1(table) && startsWith(e.origin, barResizerPrefix)) {
enforcePercentage(editor, table);
}
startW = e.width;
startRawW = isResponsiveForced(editor) ? '' : getRawWidth$1(editor, targetElm).getOr('');
}
});
editor.on('ObjectResized', function (e) {
var targetElm = e.target;
if (isTable(targetElm)) {
var table = SugarElement.fromDom(targetElm);
var origin_1 = e.origin;
if (startsWith(origin_1, 'corner-')) {
afterCornerResize(table, origin_1, e.width);
}
removeDataStyle(table);
fireTableModified(editor, table.dom, styleModified);
}
});
editor.on('SwitchMode', function () {
lazyResize().each(function (resize) {
if (editor.mode.isReadOnly()) {
resize.hideBars();
} else {
resize.showBars();
}
});
});
return {
lazyResize: lazyResize,
lazyWire: lazyWire,
destroy: destroy
};
};
var point = function (element, offset) {
return {
element: element,
offset: offset
};
};
var scan = function (universe, element, direction) {
if (universe.property().isText(element) && universe.property().getText(element).trim().length === 0 || universe.property().isComment(element)) {
return direction(element).bind(function (elem) {
return scan(universe, elem, direction).orThunk(function () {
return Optional.some(elem);
});
});
} else {
return Optional.none();
}
};
var toEnd = function (universe, element) {
if (universe.property().isText(element)) {
return universe.property().getText(element).length;
}
var children = universe.property().children(element);
return children.length;
};
var freefallRtl = function (universe, element) {
var candidate = scan(universe, element, universe.query().prevSibling).getOr(element);
if (universe.property().isText(candidate)) {
return point(candidate, toEnd(universe, candidate));
}
var children = universe.property().children(candidate);
return children.length > 0 ? freefallRtl(universe, children[children.length - 1]) : point(candidate, toEnd(universe, candidate));
};
var freefallRtl$1 = freefallRtl;
var universe$1 = DomUniverse();
var freefallRtl$2 = function (element) {
return freefallRtl$1(universe$1, element);
};
var halve = function (main, other) {
var colspan = getSpan(main, 'colspan');
if (colspan === 1) {
var width = getGenericWidth(main);
width.each(function (w) {
var newWidth = w.value / 2;
setGenericWidth(main, newWidth, w.unit);
setGenericWidth(other, newWidth, w.unit);
});
}
};
var setIfNot = function (element, property, value, ignore) {
if (value === ignore) {
remove(element, property);
} else {
set(element, property, value);
}
};
var insert = function (table, selector, element) {
last(children$2(table, selector)).fold(function () {
return prepend(table, element);
}, function (child) {
return after(child, element);
});
};
var generateSection = function (table, sectionName) {
var section = child$2(table, sectionName).getOrThunk(function () {
var newSection = SugarElement.fromTag(sectionName, owner(table).dom);
if (sectionName === 'thead') {
insert(table, 'caption,colgroup', newSection);
} else if (sectionName === 'colgroup') {
insert(table, 'caption', newSection);
} else {
append(table, newSection);
}
return newSection;
});
empty(section);
return section;
};
var render = function (table, grid) {
var newRows = [];
var newCells = [];
var syncRows = function (gridSection) {
return map(gridSection, function (row) {
if (row.isNew) {
newRows.push(row.element);
}
var tr = row.element;
empty(tr);
each(row.cells, function (cell) {
if (cell.isNew) {
newCells.push(cell.element);
}
setIfNot(cell.element, 'colspan', cell.colspan, 1);
setIfNot(cell.element, 'rowspan', cell.rowspan, 1);
append(tr, cell.element);
});
return tr;
});
};
var syncColGroup = function (gridSection) {
return bind(gridSection, function (colGroup) {
return map(colGroup.cells, function (col) {
setIfNot(col.element, 'span', col.colspan, 1);
return col.element;
});
});
};
var renderSection = function (gridSection, sectionName) {
var section = generateSection(table, sectionName);
var sync = sectionName === 'colgroup' ? syncColGroup : syncRows;
var sectionElems = sync(gridSection);
append$1(section, sectionElems);
};
var removeSection = function (sectionName) {
child$2(table, sectionName).each(remove$2);
};
var renderOrRemoveSection = function (gridSection, sectionName) {
if (gridSection.length > 0) {
renderSection(gridSection, sectionName);
} else {
removeSection(sectionName);
}
};
var headSection = [];
var bodySection = [];
var footSection = [];
var columnGroupsSection = [];
each(grid, function (row) {
switch (row.section) {
case 'thead':
headSection.push(row);
break;
case 'tbody':
bodySection.push(row);
break;
case 'tfoot':
footSection.push(row);
break;
case 'colgroup':
columnGroupsSection.push(row);
break;
}
});
renderOrRemoveSection(columnGroupsSection, 'colgroup');
renderOrRemoveSection(headSection, 'thead');
renderOrRemoveSection(bodySection, 'tbody');
renderOrRemoveSection(footSection, 'tfoot');
return {
newRows: newRows,
newCells: newCells
};
};
var copy$2 = function (grid) {
return map(grid, function (row) {
var tr = shallow(row.element);
each(row.cells, function (cell) {
var clonedCell = deep(cell.element);
setIfNot(clonedCell, 'colspan', cell.colspan, 1);
setIfNot(clonedCell, 'rowspan', cell.rowspan, 1);
append(tr, clonedCell);
});
return tr;
});
};
var getColumn = function (grid, index) {
return map(grid, function (row) {
return getCell(row, index);
});
};
var getRow = function (grid, index) {
return grid[index];
};
var findDiff = function (xs, comp) {
if (xs.length === 0) {
return 0;
}
var first = xs[0];
var index = findIndex(xs, function (x) {
return !comp(first.element, x.element);
});
return index.fold(function () {
return xs.length;
}, function (ind) {
return ind;
});
};
var subgrid = function (grid, row, column, comparator) {
var restOfRow = getRow(grid, row).cells.slice(column);
var endColIndex = findDiff(restOfRow, comparator);
var restOfColumn = getColumn(grid, column).slice(row);
var endRowIndex = findDiff(restOfColumn, comparator);
return {
colspan: endColIndex,
rowspan: endRowIndex
};
};
var toDetails = function (grid, comparator) {
var seen = map(grid, function (row) {
return map(row.cells, never);
});
var updateSeen = function (rowIndex, columnIndex, rowspan, colspan) {
for (var row = rowIndex; row < rowIndex + rowspan; row++) {
for (var column = columnIndex; column < columnIndex + colspan; column++) {
seen[row][column] = true;
}
}
};
return map(grid, function (row, rowIndex) {
var details = bind(row.cells, function (cell, columnIndex) {
if (seen[rowIndex][columnIndex] === false) {
var result = subgrid(grid, rowIndex, columnIndex, comparator);
updateSeen(rowIndex, columnIndex, result.rowspan, result.colspan);
return [detailnew(cell.element, result.rowspan, result.colspan, cell.isNew)];
} else {
return [];
}
});
return rowdetails(details, row.section);
});
};
var toGrid = function (warehouse, generators, isNew) {
var grid = [];
if (Warehouse.hasColumns(warehouse)) {
var groupElementNew = map(Warehouse.justColumns(warehouse), function (column) {
return elementnew(column.element, isNew, false);
});
grid.push(rowcells(groupElementNew, 'colgroup'));
}
for (var rowIndex = 0; rowIndex < warehouse.grid.rows; rowIndex++) {
var rowCells = [];
for (var columnIndex = 0; columnIndex < warehouse.grid.columns; columnIndex++) {
var element = Warehouse.getAt(warehouse, rowIndex, columnIndex).map(function (item) {
return elementnew(item.element, isNew, item.isLocked);
}).getOrThunk(function () {
return elementnew(generators.gap(), true, false);
});
rowCells.push(element);
}
var row = rowcells(rowCells, warehouse.all[rowIndex].section);
grid.push(row);
}
return grid;
};
var fromWarehouse = function (warehouse, generators) {
return toGrid(warehouse, generators, false);
};
var deriveRows = function (rendered, generators) {
var findRow = function (details) {
var rowOfCells = findMap(details, function (detail) {
return parent(detail.element).map(function (row) {
var isNew = parent(row).isNone();
return elementnew(row, isNew, false);
});
});
return rowOfCells.getOrThunk(function () {
return elementnew(generators.row(), true, false);
});
};
return map(rendered, function (details) {
var row = findRow(details.details);
return rowdatanew(row.element, details.details, details.section, row.isNew);
});
};
var toDetailList = function (grid, generators) {
var rendered = toDetails(grid, eq$1);
return deriveRows(rendered, generators);
};
var findInWarehouse = function (warehouse, element) {
return findMap(warehouse.all, function (r) {
return find(r.cells, function (e) {
return eq$1(element, e.element);
});
});
};
var extractCells = function (warehouse, target, predicate) {
var details = map(target.selection, function (cell$1) {
return cell(cell$1).bind(function (lc) {
return findInWarehouse(warehouse, lc);
}).filter(predicate);
});
var cells = cat(details);
return someIf(cells.length > 0, cells);
};
var run = function (operation, extract, adjustment, postAction, genWrappers) {
return function (wire, table, target, generators, sizing, resizeBehaviour) {
var warehouse = Warehouse.fromTable(table);
var output = extract(warehouse, target).map(function (info) {
var model = fromWarehouse(warehouse, generators);
var result = operation(model, info, eq$1, genWrappers(generators));
var lockedColumns = getLockedColumnsFromGrid(result.grid);
var grid = toDetailList(result.grid, generators);
return {
info: info,
grid: grid,
cursor: result.cursor,
lockedColumns: lockedColumns
};
});
return output.bind(function (out) {
var newElements = render(table, out.grid);
var tableSizing = Optional.from(sizing).getOrThunk(function () {
return TableSize.getTableSize(table);
});
var resizing = Optional.from(resizeBehaviour).getOrThunk(preserveTable);
adjustment(table, out.grid, out.info, tableSizing, resizing);
postAction(table);
refresh(wire, table);
remove(table, LOCKED_COL_ATTR);
if (out.lockedColumns.length > 0) {
set(table, LOCKED_COL_ATTR, out.lockedColumns.join(','));
}
return Optional.some({
cursor: out.cursor,
newRows: newElements.newRows,
newCells: newElements.newCells
});
});
};
};
var onCell = function (warehouse, target) {
return cell(target.element).bind(function (cell) {
return findInWarehouse(warehouse, cell);
});
};
var onPaste = function (warehouse, target) {
return cell(target.element).bind(function (cell) {
return findInWarehouse(warehouse, cell).map(function (details) {
var value = __assign(__assign({}, details), {
generators: target.generators,
clipboard: target.clipboard
});
return value;
});
});
};
var onPasteByEditor = function (warehouse, target) {
return extractCells(warehouse, target, always).map(function (cells) {
return {
cells: cells,
generators: target.generators,
clipboard: target.clipboard
};
});
};
var onMergable = function (_warehouse, target) {
return target.mergable;
};
var onUnmergable = function (_warehouse, target) {
return target.unmergable;
};
var onCells = function (warehouse, target) {
return extractCells(warehouse, target, always);
};
var onUnlockedCell = function (warehouse, target) {
return onCell(warehouse, target).filter(function (detail) {
return !detail.isLocked;
});
};
var onUnlockedCells = function (warehouse, target) {
return extractCells(warehouse, target, function (detail) {
return !detail.isLocked;
});
};
var isUnlockedTableCell = function (warehouse, cell) {
return findInWarehouse(warehouse, cell).exists(function (detail) {
return !detail.isLocked;
});
};
var allUnlocked = function (warehouse, cells) {
return forall(cells, function (cell) {
return isUnlockedTableCell(warehouse, cell);
});
};
var onUnlockedMergable = function (warehouse, target) {
return onMergable(warehouse, target).filter(function (mergeable) {
return allUnlocked(warehouse, mergeable.cells);
});
};
var onUnlockedUnmergable = function (warehouse, target) {
return onUnmergable(warehouse, target).filter(function (cells) {
return allUnlocked(warehouse, cells);
});
};
var merge = function (grid, bounds, comparator, substitution) {
var rows = extractGridDetails(grid).rows;
if (rows.length === 0) {
return grid;
}
for (var i = bounds.startRow; i <= bounds.finishRow; i++) {
for (var j = bounds.startCol; j <= bounds.finishCol; j++) {
var row = rows[i];
var isLocked = getCell(row, j).isLocked;
mutateCell(row, j, elementnew(substitution(), false, isLocked));
}
}
return grid;
};
var unmerge = function (grid, target, comparator, substitution) {
var rows = extractGridDetails(grid).rows;
var first = true;
for (var i = 0; i < rows.length; i++) {
for (var j = 0; j < cellLength(rows[0]); j++) {
var row = rows[i];
var currentCell = getCell(row, j);
var currentCellElm = currentCell.element;
var isToReplace = comparator(currentCellElm, target);
if (isToReplace === true && first === false) {
mutateCell(row, j, elementnew(substitution(), true, currentCell.isLocked));
} else if (isToReplace === true) {
first = false;
}
}
}
return grid;
};
var uniqueCells = function (row, comparator) {
return foldl(row, function (rest, cell) {
return exists(rest, function (currentCell) {
return comparator(currentCell.element, cell.element);
}) ? rest : rest.concat([cell]);
}, []);
};
var splitCols = function (grid, index, comparator, substitution) {
if (index > 0 && index < grid[0].cells.length) {
each(grid, function (row) {
var prevCell = row.cells[index - 1];
var current = row.cells[index];
var isToReplace = comparator(current.element, prevCell.element);
if (isToReplace) {
mutateCell(row, index, elementnew(substitution(), true, current.isLocked));
}
});
}
return grid;
};
var splitRows = function (grid, index, comparator, substitution) {
var rows = extractGridDetails(grid).rows;
if (index > 0 && index < rows.length) {
var rowPrevCells = rows[index - 1].cells;
var cells = uniqueCells(rowPrevCells, comparator);
each(cells, function (cell) {
var replacement = Optional.none();
for (var i = index; i < rows.length; i++) {
var _loop_1 = function (j) {
var row = rows[i];
var current = getCell(row, j);
var isToReplace = comparator(current.element, cell.element);
if (isToReplace) {
if (replacement.isNone()) {
replacement = Optional.some(substitution());
}
replacement.each(function (sub) {
mutateCell(row, j, elementnew(sub, true, current.isLocked));
});
}
};
for (var j = 0; j < cellLength(rows[0]); j++) {
_loop_1(j);
}
}
});
}
return grid;
};
var value = function (o) {
var is = function (v) {
return o === v;
};
var or = function (_opt) {
return value(o);
};
var orThunk = function (_f) {
return value(o);
};
var map = function (f) {
return value(f(o));
};
var mapError = function (_f) {
return value(o);
};
var each = function (f) {
f(o);
};
var bind = function (f) {
return f(o);
};
var fold = function (_, onValue) {
return onValue(o);
};
var exists = function (f) {
return f(o);
};
var forall = function (f) {
return f(o);
};
var toOptional = function () {
return Optional.some(o);
};
return {
is: is,
isValue: always,
isError: never,
getOr: constant(o),
getOrThunk: constant(o),
getOrDie: constant(o),
or: or,
orThunk: orThunk,
fold: fold,
map: map,
mapError: mapError,
each: each,
bind: bind,
exists: exists,
forall: forall,
toOptional: toOptional
};
};
var error = function (message) {
var getOrThunk = function (f) {
return f();
};
var getOrDie = function () {
return die(String(message))();
};
var or = function (opt) {
return opt;
};
var orThunk = function (f) {
return f();
};
var map = function (_f) {
return error(message);
};
var mapError = function (f) {
return error(f(message));
};
var bind = function (_f) {
return error(message);
};
var fold = function (onError, _) {
return onError(message);
};
return {
is: never,
isValue: never,
isError: always,
getOr: identity,
getOrThunk: getOrThunk,
getOrDie: getOrDie,
or: or,
orThunk: orThunk,
fold: fold,
map: map,
mapError: mapError,
each: noop,
bind: bind,
exists: never,
forall: always,
toOptional: Optional.none
};
};
var fromOption = function (opt, err) {
return opt.fold(function () {
return error(err);
}, value);
};
var Result = {
value: value,
error: error,
fromOption: fromOption
};
var measure = function (startAddress, gridA, gridB) {
if (startAddress.row >= gridA.length || startAddress.column > cellLength(gridA[0])) {
return Result.error('invalid start address out of table bounds, row: ' + startAddress.row + ', column: ' + startAddress.column);
}
var rowRemainder = gridA.slice(startAddress.row);
var colRemainder = rowRemainder[0].cells.slice(startAddress.column);
var colRequired = cellLength(gridB[0]);
var rowRequired = gridB.length;
return Result.value({
rowDelta: rowRemainder.length - rowRequired,
colDelta: colRemainder.length - colRequired
});
};
var measureWidth = function (gridA, gridB) {
var colLengthA = cellLength(gridA[0]);
var colLengthB = cellLength(gridB[0]);
return {
rowDelta: 0,
colDelta: colLengthA - colLengthB
};
};
var measureHeight = function (gridA, gridB) {
var rowLengthA = gridA.length;
var rowLengthB = gridB.length;
return {
rowDelta: rowLengthA - rowLengthB,
colDelta: 0
};
};
var generateElements = function (amount, row, generators, isLocked) {
var generator = row.section === 'colgroup' ? generators.col : generators.cell;
return range(amount, function (idx) {
return elementnew(generator(), true, isLocked(idx));
});
};
var rowFill = function (grid, amount, generators, lockedColumns) {
return grid.concat(range(amount, function () {
var row = grid[grid.length - 1];
var elements = generateElements(row.cells.length, row, generators, function (idx) {
return has(lockedColumns, idx.toString());
});
return setCells(row, elements);
}));
};
var colFill = function (grid, amount, generators, startIndex) {
return map(grid, function (row) {
var newChildren = generateElements(amount, row, generators, never);
return addCells(row, startIndex, newChildren);
});
};
var lockedColFill = function (grid, generators, lockedColumns) {
return map(grid, function (row) {
return foldl(lockedColumns, function (acc, colNum) {
var newChild = generateElements(1, row, generators, always)[0];
return addCell(acc, colNum, newChild);
}, row);
});
};
var tailor = function (gridA, delta, generators) {
var fillCols = delta.colDelta < 0 ? colFill : identity;
var fillRows = delta.rowDelta < 0 ? rowFill : identity;
var lockedColumns = getLockedColumnsFromGrid(gridA);
var gridWidth = cellLength(gridA[0]);
var isLastColLocked = exists(lockedColumns, function (locked) {
return locked === gridWidth - 1;
});
var modifiedCols = fillCols(gridA, Math.abs(delta.colDelta), generators, isLastColLocked ? gridWidth - 1 : gridWidth);
var newLockedColumns = getLockedColumnsFromGrid(modifiedCols);
return fillRows(modifiedCols, Math.abs(delta.rowDelta), generators, mapToObject(newLockedColumns, always));
};
var isSpanning = function (grid, row, col, comparator) {
var candidate = getCell(grid[row], col);
var matching = curry(comparator, candidate.element);
var currentRow = grid[row];
return grid.length > 1 && cellLength(currentRow) > 1 && (col > 0 && matching(getCellElement(currentRow, col - 1)) || col < currentRow.cells.length - 1 && matching(getCellElement(currentRow, col + 1)) || row > 0 && matching(getCellElement(grid[row - 1], col)) || row < grid.length - 1 && matching(getCellElement(grid[row + 1], col)));
};
var mergeTables = function (startAddress, gridA, gridB, generator, comparator, lockedColumns) {
var startRow = startAddress.row;
var startCol = startAddress.column;
var mergeHeight = gridB.length;
var mergeWidth = cellLength(gridB[0]);
var endRow = startRow + mergeHeight;
var endCol = startCol + mergeWidth + lockedColumns.length;
var lockedColumnObj = mapToObject(lockedColumns, always);
for (var r = startRow; r < endRow; r++) {
var skippedCol = 0;
for (var c = startCol; c < endCol; c++) {
if (lockedColumnObj[c]) {
skippedCol++;
continue;
}
if (isSpanning(gridA, r, c, comparator)) {
unmerge(gridA, getCellElement(gridA[r], c), comparator, generator.cell);
}
var gridBColIndex = c - startCol - skippedCol;
var newCell = getCell(gridB[r - startRow], gridBColIndex);
var newCellElm = newCell.element;
var replacement = generator.replace(newCellElm);
mutateCell(gridA[r], c, elementnew(replacement, true, newCell.isLocked));
}
}
return gridA;
};
var getValidStartAddress = function (currentStartAddress, grid, lockedColumns) {
var gridColLength = cellLength(grid[0]);
var possibleColAddresses = range(gridColLength - currentStartAddress.column, function (num) {
return num + currentStartAddress.column;
});
var validColAddress = find(possibleColAddresses, function (num) {
return forall(lockedColumns, function (col) {
return col !== num;
});
}).getOr(gridColLength - 1);
return __assign(__assign({}, currentStartAddress), { column: validColAddress });
};
var getLockedColumnsWithinBounds = function (startAddress, grid, lockedColumns) {
return filter(lockedColumns, function (colNum) {
return colNum >= startAddress.column && colNum <= cellLength(grid[0]) + startAddress.column;
});
};
var merge$1 = function (startAddress, gridA, gridB, generator, comparator) {
var lockedColumns = getLockedColumnsFromGrid(gridA);
var validStartAddress = getValidStartAddress(startAddress, gridA, lockedColumns);
var lockedColumnsWithinBounds = getLockedColumnsWithinBounds(validStartAddress, gridB, lockedColumns);
var result = measure(validStartAddress, gridA, gridB);
return result.map(function (diff) {
var delta = __assign(__assign({}, diff), { colDelta: diff.colDelta - lockedColumnsWithinBounds.length });
var fittedGrid = tailor(gridA, delta, generator);
var newLockedColumns = getLockedColumnsFromGrid(fittedGrid);
var newLockedColumnsWithinBounds = getLockedColumnsWithinBounds(validStartAddress, gridB, newLockedColumns);
return mergeTables(validStartAddress, fittedGrid, gridB, generator, comparator, newLockedColumnsWithinBounds);
});
};
var insertCols = function (index, gridA, gridB, generator, comparator) {
splitCols(gridA, index, comparator, generator.cell);
var delta = measureHeight(gridB, gridA);
var fittedNewGrid = tailor(gridB, delta, generator);
var secondDelta = measureHeight(gridA, fittedNewGrid);
var fittedOldGrid = tailor(gridA, secondDelta, generator);
return map(fittedOldGrid, function (gridRow, i) {
return addCells(gridRow, index, fittedNewGrid[i].cells);
});
};
var insertRows = function (index, gridA, gridB, generator, comparator) {
splitRows(gridA, index, comparator, generator.cell);
var locked = getLockedColumnsFromGrid(gridA);
var diff = measureWidth(gridA, gridB);
var delta = __assign(__assign({}, diff), { colDelta: diff.colDelta - locked.length });
var fittedOldGrid = tailor(gridA, delta, generator);
var _a = extractGridDetails(fittedOldGrid), oldCols = _a.cols, oldRows = _a.rows;
var newLocked = getLockedColumnsFromGrid(fittedOldGrid);
var secondDiff = measureWidth(gridB, gridA);
var secondDelta = __assign(__assign({}, secondDiff), { colDelta: secondDiff.colDelta + newLocked.length });
var fittedGridB = lockedColFill(gridB, generator, newLocked);
var fittedNewGrid = tailor(fittedGridB, secondDelta, generator);
return oldCols.concat(oldRows.slice(0, index)).concat(fittedNewGrid).concat(oldRows.slice(index, oldRows.length));
};
var insertRowAt = function (grid, index, example, comparator, substitution) {
var _a = extractGridDetails(grid), rows = _a.rows, cols = _a.cols;
var before = rows.slice(0, index);
var after = rows.slice(index);
var between = mapCells(rows[example], function (ex, c) {
var withinSpan = index > 0 && index < rows.length && comparator(getCellElement(rows[index - 1], c), getCellElement(rows[index], c));
var ret = withinSpan ? getCell(rows[index], c) : elementnew(substitution(ex.element, comparator), true, ex.isLocked);
return ret;
});
return cols.concat(before).concat([between]).concat(after);
};
var getElementFor = function (row, column, section, withinSpan, example, comparator, substitution) {
if (section === 'colgroup' || !withinSpan) {
var cell = getCell(row, example);
return elementnew(substitution(cell.element, comparator), true, false);
} else {
return getCell(row, column);
}
};
var insertColumnAt = function (grid, index, example, comparator, substitution) {
return map(grid, function (row) {
var withinSpan = index > 0 && index < cellLength(row) && comparator(getCellElement(row, index - 1), getCellElement(row, index));
var sub = getElementFor(row, index, row.section, withinSpan, example, comparator, substitution);
return addCell(row, index, sub);
});
};
var deleteColumnsAt = function (grid, columns) {
return bind(grid, function (row) {
var existingCells = row.cells;
var cells = foldr(columns, function (acc, column) {
return column >= 0 && column < acc.length ? acc.slice(0, column).concat(acc.slice(column + 1)) : acc;
}, existingCells);
return cells.length > 0 ? [rowcells(cells, row.section)] : [];
});
};
var deleteRowsAt = function (grid, start, finish) {
var _a = extractGridDetails(grid), rows = _a.rows, cols = _a.cols;
return cols.concat(rows.slice(0, start)).concat(rows.slice(finish + 1));
};
var replaceIn = function (grid, targets, comparator, substitution) {
var isTarget = function (cell) {
return exists(targets, function (target) {
return comparator(cell.element, target.element);
});
};
return map(grid, function (row) {
return mapCells(row, function (cell) {
return isTarget(cell) ? elementnew(substitution(cell.element, comparator), true, cell.isLocked) : cell;
});
});
};
var notStartRow = function (grid, rowIndex, colIndex, comparator) {
return getCellElement(grid[rowIndex], colIndex) !== undefined && (rowIndex > 0 && comparator(getCellElement(grid[rowIndex - 1], colIndex), getCellElement(grid[rowIndex], colIndex)));
};
var notStartColumn = function (row, index, comparator) {
return index > 0 && comparator(getCellElement(row, index - 1), getCellElement(row, index));
};
var replaceColumn = function (grid, index, comparator, substitution) {
var rows = extractGridDetails(grid).rows;
var targets = bind(rows, function (row, i) {
var alreadyAdded = notStartRow(grid, i, index, comparator) || notStartColumn(row, index, comparator);
return alreadyAdded ? [] : [getCell(row, index)];
});
return replaceIn(grid, targets, comparator, substitution);
};
var replaceRow = function (grid, index, comparator, substitution) {
var rows = extractGridDetails(grid).rows;
var targetRow = rows[index];
var targets = bind(targetRow.cells, function (item, i) {
var alreadyAdded = notStartRow(rows, index, i, comparator) || notStartColumn(targetRow, i, comparator);
return alreadyAdded ? [] : [item];
});
return replaceIn(grid, targets, comparator, substitution);
};
var uniqueColumns = function (details) {
var uniqueCheck = function (rest, detail) {
var columnExists = exists(rest, function (currentDetail) {
return currentDetail.column === detail.column;
});
return columnExists ? rest : rest.concat([detail]);
};
return foldl(details, uniqueCheck, []).sort(function (detailA, detailB) {
return detailA.column - detailB.column;
});
};
var elementToData = function (element) {
var colspan = getAttrValue(element, 'colspan', 1);
var rowspan = getAttrValue(element, 'rowspan', 1);
return {
element: element,
colspan: colspan,
rowspan: rowspan
};
};
var modification = function (generators, toData) {
if (toData === void 0) {
toData = elementToData;
}
var position = Cell(Optional.none());
var nu = function (data) {
switch (name(data.element)) {
case 'col':
return generators.col(data);
default:
return generators.cell(data);
}
};
var nuFrom = function (element) {
var data = toData(element);
return nu(data);
};
var add = function (element) {
var replacement = nuFrom(element);
if (position.get().isNone()) {
position.set(Optional.some(replacement));
}
recent = Optional.some({
item: element,
replacement: replacement
});
return replacement;
};
var recent = Optional.none();
var getOrInit = function (element, comparator) {
return recent.fold(function () {
return add(element);
}, function (p) {
return comparator(element, p.item) ? p.replacement : add(element);
});
};
return {
getOrInit: getOrInit,
cursor: position.get
};
};
var transform$1 = function (scope, tag) {
return function (generators) {
var position = Cell(Optional.none());
var list = [];
var find$1 = function (element, comparator) {
return find(list, function (x) {
return comparator(x.item, element);
});
};
var makeNew = function (element) {
var attrs = { scope: scope };
var cell = generators.replace(element, tag, attrs);
list.push({
item: element,
sub: cell
});
if (position.get().isNone()) {
position.set(Optional.some(cell));
}
return cell;
};
var replaceOrInit = function (element, comparator) {
if (name(element) === 'col') {
return element;
} else {
return find$1(element, comparator).fold(function () {
return makeNew(element);
}, function (p) {
return comparator(element, p.item) ? p.sub : makeNew(element);
});
}
};
return {
replaceOrInit: replaceOrInit,
cursor: position.get
};
};
};
var getScopeAttribute = function (cell) {
return getOpt(cell, 'scope').map(function (attribute) {
return attribute.substr(0, 3);
});
};
var merging = function (generators) {
var position = Cell(Optional.none());
var unmerge = function (cell) {
if (position.get().isNone()) {
position.set(Optional.some(cell));
}
var scope = getScopeAttribute(cell);
scope.each(function (attribute) {
return set(cell, 'scope', attribute);
});
return function () {
var raw = generators.cell({
element: cell,
colspan: 1,
rowspan: 1
});
remove$1(raw, 'width');
remove$1(cell, 'width');
scope.each(function (attribute) {
return set(raw, 'scope', attribute);
});
return raw;
};
};
var merge = function (cells) {
var getScopeProperty = function () {
var stringAttributes = cat(map(cells, getScopeAttribute));
if (stringAttributes.length === 0) {
return Optional.none();
} else {
var baseScope_1 = stringAttributes[0];
var scopes_1 = [
'row',
'col'
];
var isMixed = exists(stringAttributes, function (attribute) {
return attribute !== baseScope_1 && contains(scopes_1, attribute);
});
return isMixed ? Optional.none() : Optional.from(baseScope_1);
}
};
remove$1(cells[0], 'width');
getScopeProperty().fold(function () {
return remove(cells[0], 'scope');
}, function (attribute) {
return set(cells[0], 'scope', attribute + 'group');
});
return constant(cells[0]);
};
return {
unmerge: unmerge,
merge: merge,
cursor: position.get
};
};
var Generators = {
modification: modification,
transform: transform$1,
merging: merging
};
var blockList = [
'body',
'p',
'div',
'article',
'aside',
'figcaption',
'figure',
'footer',
'header',
'nav',
'section',
'ol',
'ul',
'table',
'thead',
'tfoot',
'tbody',
'caption',
'tr',
'td',
'th',
'h1',
'h2',
'h3',
'h4',
'h5',
'h6',
'blockquote',
'pre',
'address'
];
var isList = function (universe, item) {
var tagName = universe.property().name(item);
return contains([
'ol',
'ul'
], tagName);
};
var isBlock = function (universe, item) {
var tagName = universe.property().name(item);
return contains(blockList, tagName);
};
var isEmptyTag = function (universe, item) {
return contains([
'br',
'img',
'hr',
'input'
], universe.property().name(item));
};
var universe$2 = DomUniverse();
var isBlock$1 = function (element) {
return isBlock(universe$2, element);
};
var isList$1 = function (element) {
return isList(universe$2, element);
};
var isEmptyTag$1 = function (element) {
return isEmptyTag(universe$2, element);
};
var merge$2 = function (cells) {
var isBr = function (el) {
return name(el) === 'br';
};
var advancedBr = function (children) {
return forall(children, function (c) {
return isBr(c) || isText(c) && get$4(c).trim().length === 0;
});
};
var isListItem = function (el) {
return name(el) === 'li' || ancestor(el, isList$1).isSome();
};
var siblingIsBlock = function (el) {
return nextSibling(el).map(function (rightSibling) {
if (isBlock$1(rightSibling)) {
return true;
}
if (isEmptyTag$1(rightSibling)) {
return name(rightSibling) === 'img' ? false : true;
}
return false;
}).getOr(false);
};
var markCell = function (cell) {
return last$1(cell).bind(function (rightEdge) {
var rightSiblingIsBlock = siblingIsBlock(rightEdge);
return parent(rightEdge).map(function (parent) {
return rightSiblingIsBlock === true || isListItem(parent) || isBr(rightEdge) || isBlock$1(parent) && !eq$1(cell, parent) ? [] : [SugarElement.fromTag('br')];
});
}).getOr([]);
};
var markContent = function () {
var content = bind(cells, function (cell) {
var children$1 = children(cell);
return advancedBr(children$1) ? [] : children$1.concat(markCell(cell));
});
return content.length === 0 ? [SugarElement.fromTag('br')] : content;
};
var contents = markContent();
empty(cells[0]);
append$1(cells[0], contents);
};
var prune = function (table) {
var cells$1 = cells(table);
if (cells$1.length === 0) {
remove$2(table);
}
};
var outcome = function (grid, cursor) {
return {
grid: grid,
cursor: cursor
};
};
var elementFromGrid = function (grid, row, column) {
var rows = extractGridDetails(grid).rows;
return findIn(rows, row, column).orThunk(function () {
return findIn(rows, 0, 0);
});
};
var findIn = function (grid, row, column) {
return Optional.from(grid[row]).bind(function (r) {
return Optional.from(r.cells[column]).bind(function (c) {
return Optional.from(c.element);
});
});
};
var bundle = function (grid, row, column) {
var rows = extractGridDetails(grid).rows;
return outcome(grid, findIn(rows, row, column));
};
var uniqueRows = function (details) {
var rowCompilation = function (rest, detail) {
var rowExists = exists(rest, function (currentDetail) {
return currentDetail.row === detail.row;
});
return rowExists ? rest : rest.concat([detail]);
};
return foldl(details, rowCompilation, []).sort(function (detailA, detailB) {
return detailA.row - detailB.row;
});
};
var opInsertRowsBefore = function (grid, details, comparator, genWrappers) {
var targetIndex = details[0].row;
var rows = uniqueRows(details);
var newGrid = foldr(rows, function (acc, row) {
var newG = insertRowAt(acc.grid, targetIndex, row.row + acc.delta, comparator, genWrappers.getOrInit);
return {
grid: newG,
delta: acc.delta + 1
};
}, {
grid: grid,
delta: 0
}).grid;
return bundle(newGrid, targetIndex, details[0].column);
};
var opInsertRowsAfter = function (grid, details, comparator, genWrappers) {
var rows = uniqueRows(details);
var target = rows[rows.length - 1];
var targetIndex = target.row + target.rowspan;
var newGrid = foldr(rows, function (newG, row) {
return insertRowAt(newG, targetIndex, row.row, comparator, genWrappers.getOrInit);
}, grid);
return bundle(newGrid, targetIndex, details[0].column);
};
var opInsertColumnsBefore = function (grid, extractDetail, comparator, genWrappers) {
var details = extractDetail.details;
var columns = uniqueColumns(details);
var targetIndex = columns[0].column;
var newGrid = foldr(columns, function (acc, col) {
var newG = insertColumnAt(acc.grid, targetIndex, col.column + acc.delta, comparator, genWrappers.getOrInit);
return {
grid: newG,
delta: acc.delta + 1
};
}, {
grid: grid,
delta: 0
}).grid;
return bundle(newGrid, details[0].row, targetIndex);
};
var opInsertColumnsAfter = function (grid, extractDetail, comparator, genWrappers) {
var details = extractDetail.details;
var target = details[details.length - 1];
var targetIndex = target.column + target.colspan;
var columns = uniqueColumns(details);
var newGrid = foldr(columns, function (newG, col) {
return insertColumnAt(newG, targetIndex, col.column, comparator, genWrappers.getOrInit);
}, grid);
return bundle(newGrid, details[0].row, targetIndex);
};
var opMakeRowHeader = function (grid, detail, comparator, genWrappers) {
var newGrid = replaceRow(grid, detail.row, comparator, genWrappers.replaceOrInit);
return bundle(newGrid, detail.row, detail.column);
};
var opMakeRowsHeader = function (initialGrid, details, comparator, genWrappers) {
var rows = uniqueRows(details);
var replacer = function (currentGrid, row) {
return replaceRow(currentGrid, row.row, comparator, genWrappers.replaceOrInit);
};
var newGrid = foldl(rows, replacer, initialGrid);
return bundle(newGrid, details[0].row, details[0].column);
};
var opMakeColumnHeader = function (initialGrid, detail, comparator, genWrappers) {
var newGrid = replaceColumn(initialGrid, detail.column, comparator, genWrappers.replaceOrInit);
return bundle(newGrid, detail.row, detail.column);
};
var opMakeColumnsHeader = function (initialGrid, details, comparator, genWrappers) {
var columns = uniqueColumns(details);
var replacer = function (currentGrid, column) {
return replaceColumn(currentGrid, column.column, comparator, genWrappers.replaceOrInit);
};
var newGrid = foldl(columns, replacer, initialGrid);
return bundle(newGrid, details[0].row, details[0].column);
};
var opUnmakeRowHeader = function (grid, detail, comparator, genWrappers) {
var newGrid = replaceRow(grid, detail.row, comparator, genWrappers.replaceOrInit);
return bundle(newGrid, detail.row, detail.column);
};
var opUnmakeRowsHeader = function (initialGrid, details, comparator, genWrappers) {
var rows = uniqueRows(details);
var replacer = function (currentGrid, row) {
return replaceRow(currentGrid, row.row, comparator, genWrappers.replaceOrInit);
};
var newGrid = foldl(rows, replacer, initialGrid);
return bundle(newGrid, details[0].row, details[0].column);
};
var opUnmakeColumnHeader = function (initialGrid, detail, comparator, genWrappers) {
var newGrid = replaceColumn(initialGrid, detail.column, comparator, genWrappers.replaceOrInit);
return bundle(newGrid, detail.row, detail.column);
};
var opUnmakeColumnsHeader = function (initialGrid, details, comparator, genWrappers) {
var columns = uniqueColumns(details);
var replacer = function (currentGrid, column) {
return replaceColumn(currentGrid, column.column, comparator, genWrappers.replaceOrInit);
};
var newGrid = foldl(columns, replacer, initialGrid);
return bundle(newGrid, details[0].row, details[0].column);
};
var opEraseColumns = function (grid, extractDetail, _comparator, _genWrappers) {
var columns = uniqueColumns(extractDetail.details);
var newGrid = deleteColumnsAt(grid, map(columns, function (column) {
return column.column;
}));
var cursor = elementFromGrid(newGrid, columns[0].row, columns[0].column);
return outcome(newGrid, cursor);
};
var opEraseRows = function (grid, details, _comparator, _genWrappers) {
var rows = uniqueRows(details);
var newGrid = deleteRowsAt(grid, rows[0].row, rows[rows.length - 1].row);
var cursor = elementFromGrid(newGrid, details[0].row, details[0].column);
return outcome(newGrid, cursor);
};
var opMergeCells = function (grid, mergable, comparator, genWrappers) {
var cells = mergable.cells;
merge$2(cells);
var newGrid = merge(grid, mergable.bounds, comparator, genWrappers.merge(cells));
return outcome(newGrid, Optional.from(cells[0]));
};
var opUnmergeCells = function (grid, unmergable, comparator, genWrappers) {
var unmerge$1 = function (b, cell) {
return unmerge(b, cell, comparator, genWrappers.unmerge(cell));
};
var newGrid = foldr(unmergable, unmerge$1, grid);
return outcome(newGrid, Optional.from(unmergable[0]));
};
var opPasteCells = function (grid, pasteDetails, comparator, _genWrappers) {
var gridify = function (table, generators) {
var wh = Warehouse.fromTable(table);
return toGrid(wh, generators, true);
};
var gridB = gridify(pasteDetails.clipboard, pasteDetails.generators);
var startAddress = address(pasteDetails.row, pasteDetails.column);
var mergedGrid = merge$1(startAddress, grid, gridB, pasteDetails.generators, comparator);
return mergedGrid.fold(function () {
return outcome(grid, Optional.some(pasteDetails.element));
}, function (newGrid) {
var cursor = elementFromGrid(newGrid, pasteDetails.row, pasteDetails.column);
return outcome(newGrid, cursor);
});
};
var gridifyRows = function (rows, generators, context) {
var pasteDetails = fromPastedRows(rows, context.section);
var wh = Warehouse.generate(pasteDetails);
return toGrid(wh, generators, true);
};
var opPasteColsBefore = function (grid, pasteDetails, comparator, _genWrappers) {
var rows = extractGridDetails(grid).rows;
var index = pasteDetails.cells[0].column;
var context = rows[pasteDetails.cells[0].row];
var gridB = gridifyRows(pasteDetails.clipboard, pasteDetails.generators, context);
var mergedGrid = insertCols(index, grid, gridB, pasteDetails.generators, comparator);
var cursor = elementFromGrid(mergedGrid, pasteDetails.cells[0].row, pasteDetails.cells[0].column);
return outcome(mergedGrid, cursor);
};
var opPasteColsAfter = function (grid, pasteDetails, comparator, _genWrappers) {
var rows = extractGridDetails(grid).rows;
var index = pasteDetails.cells[pasteDetails.cells.length - 1].column + pasteDetails.cells[pasteDetails.cells.length - 1].colspan;
var context = rows[pasteDetails.cells[0].row];
var gridB = gridifyRows(pasteDetails.clipboard, pasteDetails.generators, context);
var mergedGrid = insertCols(index, grid, gridB, pasteDetails.generators, comparator);
var cursor = elementFromGrid(mergedGrid, pasteDetails.cells[0].row, pasteDetails.cells[0].column);
return outcome(mergedGrid, cursor);
};
var opPasteRowsBefore = function (grid, pasteDetails, comparator, _genWrappers) {
var rows = extractGridDetails(grid).rows;
var index = pasteDetails.cells[0].row;
var context = rows[index];
var gridB = gridifyRows(pasteDetails.clipboard, pasteDetails.generators, context);
var mergedGrid = insertRows(index, grid, gridB, pasteDetails.generators, comparator);
var cursor = elementFromGrid(mergedGrid, pasteDetails.cells[0].row, pasteDetails.cells[0].column);
return outcome(mergedGrid, cursor);
};
var opPasteRowsAfter = function (grid, pasteDetails, comparator, _genWrappers) {
var rows = extractGridDetails(grid).rows;
var index = pasteDetails.cells[pasteDetails.cells.length - 1].row + pasteDetails.cells[pasteDetails.cells.length - 1].rowspan;
var context = rows[pasteDetails.cells[0].row];
var gridB = gridifyRows(pasteDetails.clipboard, pasteDetails.generators, context);
var mergedGrid = insertRows(index, grid, gridB, pasteDetails.generators, comparator);
var cursor = elementFromGrid(mergedGrid, pasteDetails.cells[0].row, pasteDetails.cells[0].column);
return outcome(mergedGrid, cursor);
};
var opGetColumnType = function (table, target) {
var house = Warehouse.fromTable(table);
var details = onCells(house, target);
return details.bind(function (selectedCells) {
var lastSelectedCell = selectedCells[selectedCells.length - 1];
var minColRange = selectedCells[0].column;
var maxColRange = lastSelectedCell.column + lastSelectedCell.colspan;
var selectedColumnCells = flatten(map(house.all, function (row) {
return filter(row.cells, function (cell) {
return cell.column >= minColRange && cell.column < maxColRange;
});
}));
return getCellsType(selectedColumnCells, function (cell) {
return name(cell.element) === 'th';
});
}).getOr('');
};
var getCellsType = function (cells, headerPred) {
var headerCells = filter(cells, headerPred);
if (headerCells.length === 0) {
return Optional.some('td');
} else if (headerCells.length === cells.length) {
return Optional.some('th');
} else {
return Optional.none();
}
};
var resize = adjustWidthTo;
var adjustAndRedistributeWidths$1 = adjustAndRedistributeWidths;
var firstColumnIsLocked = function (_warehouse, details) {
return exists(details, function (detail) {
return detail.column === 0 && detail.isLocked;
});
};
var lastColumnIsLocked = function (warehouse, details) {
return exists(details, function (detail) {
return detail.column + detail.colspan >= warehouse.grid.columns && detail.isLocked;
});
};
var getColumnsWidth = function (warehouse, details) {
var columns = columns$1(warehouse);
var uniqueCols = uniqueColumns(details);
return foldl(uniqueCols, function (acc, detail) {
var column = columns[detail.column];
var colWidth = column.map(getOuter).getOr(0);
return acc + colWidth;
}, 0);
};
var insertColumnsExtractor = function (before) {
return function (warehouse, target) {
return onCells(warehouse, target).filter(function (details) {
var checkLocked = before ? firstColumnIsLocked : lastColumnIsLocked;
return !checkLocked(warehouse, details);
}).map(function (details) {
return {
details: details,
pixelDelta: getColumnsWidth(warehouse, details)
};
});
};
};
var eraseColumnsExtractor = function (warehouse, target) {
return onUnlockedCells(warehouse, target).map(function (details) {
return {
details: details,
pixelDelta: -getColumnsWidth(warehouse, details)
};
});
};
var pasteColumnsExtractor = function (before) {
return function (warehouse, target) {
return onPasteByEditor(warehouse, target).filter(function (details) {
var checkLocked = before ? firstColumnIsLocked : lastColumnIsLocked;
return !checkLocked(warehouse, details.cells);
});
};
};
var insertRowsBefore = run(opInsertRowsBefore, onCells, noop, noop, Generators.modification);
var insertRowsAfter = run(opInsertRowsAfter, onCells, noop, noop, Generators.modification);
var insertColumnsBefore = run(opInsertColumnsBefore, insertColumnsExtractor(true), adjustAndRedistributeWidths$1, noop, Generators.modification);
var insertColumnsAfter = run(opInsertColumnsAfter, insertColumnsExtractor(false), adjustAndRedistributeWidths$1, noop, Generators.modification);
var eraseColumns = run(opEraseColumns, eraseColumnsExtractor, adjustAndRedistributeWidths$1, prune, Generators.modification);
var eraseRows = run(opEraseRows, onCells, noop, prune, Generators.modification);
var makeColumnHeader = run(opMakeColumnHeader, onUnlockedCell, noop, noop, Generators.transform('row', 'th'));
var makeColumnsHeader = run(opMakeColumnsHeader, onUnlockedCells, noop, noop, Generators.transform('row', 'th'));
var unmakeColumnHeader = run(opUnmakeColumnHeader, onUnlockedCell, noop, noop, Generators.transform(null, 'td'));
var unmakeColumnsHeader = run(opUnmakeColumnsHeader, onUnlockedCells, noop, noop, Generators.transform(null, 'td'));
var makeRowHeader = run(opMakeRowHeader, onCell, noop, noop, Generators.transform('col', 'th'));
var makeRowsHeader = run(opMakeRowsHeader, onCells, noop, noop, Generators.transform('col', 'th'));
var unmakeRowHeader = run(opUnmakeRowHeader, onCell, noop, noop, Generators.transform(null, 'td'));
var unmakeRowsHeader = run(opUnmakeRowsHeader, onCells, noop, noop, Generators.transform(null, 'td'));
var mergeCells = run(opMergeCells, onUnlockedMergable, resize, noop, Generators.merging);
var unmergeCells = run(opUnmergeCells, onUnlockedUnmergable, resize, noop, Generators.merging);
var pasteCells = run(opPasteCells, onPaste, resize, noop, Generators.modification);
var pasteColsBefore = run(opPasteColsBefore, pasteColumnsExtractor(true), noop, noop, Generators.modification);
var pasteColsAfter = run(opPasteColsAfter, pasteColumnsExtractor(false), noop, noop, Generators.modification);
var pasteRowsBefore = run(opPasteRowsBefore, onPasteByEditor, noop, noop, Generators.modification);
var pasteRowsAfter = run(opPasteRowsAfter, onPasteByEditor, noop, noop, Generators.modification);
var getColumnType = opGetColumnType;
var getSection = function (elm) {
return getNodeName(elm.parentNode);
};
var mapSectionNameToType = function (section) {
if (section === 'thead') {
return 'header';
} else if (section === 'tfoot') {
return 'footer';
} else {
return 'body';
}
};
var detectHeaderRow = function (editor, elm) {
var isThead = getSection(elm) === 'thead';
var areAllCellsThs = !exists(elm.cells, function (c) {
return getNodeName(c) !== 'th';
});
return isThead || areAllCellsThs ? Optional.some({
thead: isThead,
ths: areAllCellsThs
}) : Optional.none();
};
var getRowType = function (editor, elm) {
return mapSectionNameToType(detectHeaderRow(editor, elm).fold(function () {
return getSection(elm);
}, function (_rowConfig) {
return 'thead';
}));
};
var switchRowSection = function (dom, rowElm, newSectionName) {
var tableElm = dom.getParent(rowElm, 'table');
var oldSectionElm = rowElm.parentNode;
var oldSectionName = getNodeName(oldSectionElm);
if (newSectionName !== oldSectionName) {
var sectionElm_1 = dom.select(newSectionName, tableElm)[0];
if (!sectionElm_1) {
sectionElm_1 = dom.create(newSectionName);
var firstTableChild_1 = tableElm.firstChild;
if (newSectionName === 'thead') {
last(children$2(SugarElement.fromDom(tableElm), 'caption,colgroup')).fold(function () {
return tableElm.insertBefore(sectionElm_1, firstTableChild_1);
}, function (c) {
return dom.insertAfter(sectionElm_1, c.dom);
});
} else {
tableElm.appendChild(sectionElm_1);
}
}
if (newSectionName === 'tbody' && oldSectionName === 'thead' && sectionElm_1.firstChild) {
sectionElm_1.insertBefore(rowElm, sectionElm_1.firstChild);
} else {
sectionElm_1.appendChild(rowElm);
}
if (!oldSectionElm.hasChildNodes()) {
dom.remove(oldSectionElm);
}
}
};
var renameCell = function (editor, cell, newCellType) {
if (isNonNullable(newCellType) && getNodeName(cell) !== newCellType) {
var newCellElm = editor.dom.rename(cell, newCellType);
fireNewCell(editor, newCellElm);
return newCellElm;
} else {
return cell;
}
};
var switchCellType = function (editor, cell, newCellType, scope) {
var dom = editor.dom;
var newCell = renameCell(editor, cell, newCellType);
if (!isUndefined(scope)) {
dom.setAttrib(newCell, 'scope', scope);
}
return newCell;
};
var switchCellsType = function (editor, cells, newCellType, scope) {
return each(cells, function (c) {
return switchCellType(editor, c, newCellType, scope);
});
};
var switchSectionType = function (editor, rowElm, newType) {
var determineHeaderRowType = function () {
var allTableRows = table(SugarElement.fromDom(rowElm.cells[0])).map(function (table) {
return rows(table);
}).getOr([]);
return findMap(allTableRows, function (row) {
return detectHeaderRow(editor, row.dom);
}).map(function (detectedType) {
if (detectedType.thead && detectedType.ths) {
return 'sectionCells';
} else {
return detectedType.thead ? 'section' : 'cells';
}
}).getOr('section');
};
var dom = editor.dom;
if (newType === 'header') {
var headerRowTypeSetting = getTableHeaderType(editor);
var headerRowType = headerRowTypeSetting === 'auto' ? determineHeaderRowType() : headerRowTypeSetting;
switchCellsType(editor, rowElm.cells, headerRowType === 'section' ? 'td' : 'th', 'col');
switchRowSection(dom, rowElm, headerRowType === 'cells' ? 'tbody' : 'thead');
} else {
switchCellsType(editor, rowElm.cells, 'td', null);
switchRowSection(dom, rowElm, newType === 'footer' ? 'tfoot' : 'tbody');
}
};
var getSelectionStartCellFallback = function (start) {
return table(start).bind(function (table) {
return retrieve$1(table, ephemera.firstSelectedSelector);
}).fold(function () {
return start;
}, function (cells) {
return cells[0];
});
};
var getSelectionStartFromSelector = function (selector) {
return function (start, isRoot) {
var startCellName = name(start);
var startCell = startCellName === 'col' || startCellName === 'colgroup' ? getSelectionStartCellFallback(start) : start;
return closest$1(startCell, selector, isRoot);
};
};
var getSelectionStartCell = getSelectionStartFromSelector('th,td');
var getSelectionStartCellOrCaption = getSelectionStartFromSelector('th,td,caption');
var getCellsFromSelection = function (start, selections, isRoot) {
return getSelectionStartCell(start, isRoot).map(function (_cell) {
return selection(selections);
}).getOr([]);
};
var getRowsFromSelection = function (start, selector) {
var cellOpt = getSelectionStartCell(start);
var rowsOpt = cellOpt.bind(function (cell) {
return table(cell);
}).map(function (table) {
return rows(table);
});
return lift2(cellOpt, rowsOpt, function (cell, rows) {
return filter(rows, function (row) {
return exists(fromDom$1(row.dom.cells), function (rowCell) {
return get$2(rowCell, selector) === '1' || eq$1(rowCell, cell);
});
});
}).getOr([]);
};
var TableActions = function (editor, lazyWire, selections) {
var isTableBody = function (editor) {
return name(getBody$1(editor)) === 'table';
};
var lastRowGuard = function (table) {
return isTableBody(editor) === false || getGridSize(table).rows > 1;
};
var lastColumnGuard = function (table) {
return isTableBody(editor) === false || getGridSize(table).columns > 1;
};
var cloneFormats = getCloneElements(editor);
var colMutationOp = isResizeTableColumnResizing(editor) ? noop : halve;
var execute = function (operation, guard, mutate, lazyWire, effect) {
return function (table, target) {
removeDataStyle(table);
var wire = lazyWire();
var doc = SugarElement.fromDom(editor.getDoc());
var generators = cellOperations(mutate, doc, cloneFormats);
var sizing = get$9(editor, table);
var resizeBehaviour = isResizeTableColumnResizing(editor) ? resizeTable() : preserveTable();
return guard(table) ? operation(wire, table, target, generators, sizing, resizeBehaviour).bind(function (result) {
each(result.newRows, function (row) {
fireNewRow(editor, row.dom);
});
each(result.newCells, function (cell) {
fireNewCell(editor, cell.dom);
});
return result.cursor.map(function (cell) {
var des = freefallRtl$2(cell);
var rng = editor.dom.createRng();
rng.setStart(des.element.dom, des.offset);
rng.setEnd(des.element.dom, des.offset);
return {
rng: rng,
effect: effect
};
});
}) : Optional.none();
};
};
var deleteRow = execute(eraseRows, lastRowGuard, noop, lazyWire, structureModified);
var deleteColumn = execute(eraseColumns, lastColumnGuard, noop, lazyWire, structureModified);
var insertRowsBefore$1 = execute(insertRowsBefore, always, noop, lazyWire, structureModified);
var insertRowsAfter$1 = execute(insertRowsAfter, always, noop, lazyWire, structureModified);
var insertColumnsBefore$1 = execute(insertColumnsBefore, always, colMutationOp, lazyWire, structureModified);
var insertColumnsAfter$1 = execute(insertColumnsAfter, always, colMutationOp, lazyWire, structureModified);
var mergeCells$1 = execute(mergeCells, always, noop, lazyWire, structureModified);
var unmergeCells$1 = execute(unmergeCells, always, noop, lazyWire, structureModified);
var pasteColsBefore$1 = execute(pasteColsBefore, always, noop, lazyWire, structureModified);
var pasteColsAfter$1 = execute(pasteColsAfter, always, noop, lazyWire, structureModified);
var pasteRowsBefore$1 = execute(pasteRowsBefore, always, noop, lazyWire, structureModified);
var pasteRowsAfter$1 = execute(pasteRowsAfter, always, noop, lazyWire, structureModified);
var pasteCells$1 = execute(pasteCells, always, noop, lazyWire, structureModified);
var extractType = function (args, validTypes) {
return get$1(args, 'type').filter(function (type) {
return contains(validTypes, type);
});
};
var setTableCellType = function (editor, args) {
return extractType(args, [
'td',
'th'
]).each(function (type) {
var cells = map(getCellsFromSelection(getSelectionStart(editor), selections), function (c) {
return c.dom;
});
switchCellsType(editor, cells, type, null);
});
};
var setTableRowType = function (editor, args) {
return extractType(args, [
'header',
'body',
'footer'
]).each(function (type) {
map(getRowsFromSelection(getSelectionStart(editor), ephemera.selected), function (row) {
return switchSectionType(editor, row.dom, type);
});
});
};
var makeColumnsHeader$1 = execute(makeColumnsHeader, always, noop, lazyWire, structureModified);
var unmakeColumnsHeader$1 = execute(unmakeColumnsHeader, always, noop, lazyWire, structureModified);
var getTableRowType = function (editor) {
var rows = getRowsFromSelection(getSelectionStart(editor), ephemera.selected);
if (rows.length > 0) {
var rowTypes = map(rows, function (r) {
return getRowType(editor, r.dom);
});
var hasHeader = contains(rowTypes, 'header');
var hasFooter = contains(rowTypes, 'footer');
if (!hasHeader && !hasFooter) {
return 'body';
} else {
var hasBody = contains(rowTypes, 'body');
if (hasHeader && !hasBody && !hasFooter) {
return 'header';
} else if (!hasHeader && !hasBody && hasFooter) {
return 'footer';
} else {
return '';
}
}
}
};
var getTableCellType = function (editor) {
return getCellsType(getCellsFromSelection(getSelectionStart(editor), selections), function (cell) {
return name(cell) === 'th';
}).getOr('');
};
var getTableColType = getColumnType;
return {
deleteRow: deleteRow,
deleteColumn: deleteColumn,
insertRowsBefore: insertRowsBefore$1,
insertRowsAfter: insertRowsAfter$1,
insertColumnsBefore: insertColumnsBefore$1,
insertColumnsAfter: insertColumnsAfter$1,
mergeCells: mergeCells$1,
unmergeCells: unmergeCells$1,
pasteColsBefore: pasteColsBefore$1,
pasteColsAfter: pasteColsAfter$1,
pasteRowsBefore: pasteRowsBefore$1,
pasteRowsAfter: pasteRowsAfter$1,
pasteCells: pasteCells$1,
setTableCellType: setTableCellType,
setTableRowType: setTableRowType,
makeColumnsHeader: makeColumnsHeader$1,
unmakeColumnsHeader: unmakeColumnsHeader$1,
getTableRowType: getTableRowType,
getTableCellType: getTableCellType,
getTableColType: getTableColType
};
};
var DefaultRenderOptions = {
styles: {
'border-collapse': 'collapse',
'width': '100%'
},
attributes: { border: '1' },
colGroups: false
};
var tableHeaderCell = function () {
return SugarElement.fromTag('th');
};
var tableCell = function () {
return SugarElement.fromTag('td');
};
var tableColumn = function () {
return SugarElement.fromTag('col');
};
var createRow = function (columns, rowHeaders, columnHeaders, rowIndex) {
var tr = SugarElement.fromTag('tr');
for (var j = 0; j < columns; j++) {
var td = rowIndex < rowHeaders || j < columnHeaders ? tableHeaderCell() : tableCell();
if (j < columnHeaders) {
set(td, 'scope', 'row');
}
if (rowIndex < rowHeaders) {
set(td, 'scope', 'col');
}
append(td, SugarElement.fromTag('br'));
append(tr, td);
}
return tr;
};
var createGroupRow = function (columns) {
var columnGroup = SugarElement.fromTag('colgroup');
range(columns, function () {
return append(columnGroup, tableColumn());
});
return columnGroup;
};
var createRows = function (rows, columns, rowHeaders, columnHeaders) {
return range(rows, function (r) {
return createRow(columns, rowHeaders, columnHeaders, r);
});
};
var render$1 = function (rows, columns, rowHeaders, columnHeaders, headerType, renderOpts) {
if (renderOpts === void 0) {
renderOpts = DefaultRenderOptions;
}
var table = SugarElement.fromTag('table');
var rowHeadersGoInThead = headerType !== 'cells';
setAll$1(table, renderOpts.styles);
setAll(table, renderOpts.attributes);
if (renderOpts.colGroups) {
append(table, createGroupRow(columns));
}
var actualRowHeaders = Math.min(rows, rowHeaders);
if (rowHeadersGoInThead && rowHeaders > 0) {
var thead = SugarElement.fromTag('thead');
append(table, thead);
var theadRowHeaders = headerType === 'sectionCells' ? actualRowHeaders : 0;
var theadRows = createRows(rowHeaders, columns, theadRowHeaders, columnHeaders);
append$1(thead, theadRows);
}
var tbody = SugarElement.fromTag('tbody');
append(table, tbody);
var numRows = rowHeadersGoInThead ? rows - actualRowHeaders : rows;
var numRowHeaders = rowHeadersGoInThead ? 0 : rowHeaders;
var tbodyRows = createRows(numRows, columns, numRowHeaders, columnHeaders);
append$1(tbody, tbodyRows);
return table;
};
var get$b = function (element) {
return element.dom.innerHTML;
};
var getOuter$2 = function (element) {
var container = SugarElement.fromTag('div');
var clone = SugarElement.fromDom(element.dom.cloneNode(true));
append(container, clone);
return get$b(container);
};
var placeCaretInCell = function (editor, cell) {
editor.selection.select(cell.dom, true);
editor.selection.collapse(true);
};
var selectFirstCellInTable = function (editor, tableElm) {
descendant$1(tableElm, 'td,th').each(curry(placeCaretInCell, editor));
};
var fireEvents = function (editor, table) {
each(descendants$1(table, 'tr'), function (row) {
fireNewRow(editor, row.dom);
each(descendants$1(row, 'th,td'), function (cell) {
fireNewCell(editor, cell.dom);
});
});
};
var isPercentage$1 = function (width) {
return isString(width) && width.indexOf('%') !== -1;
};
var insert$1 = function (editor, columns, rows, colHeaders, rowHeaders) {
var defaultStyles = getDefaultStyles(editor);
var options = {
styles: defaultStyles,
attributes: getDefaultAttributes(editor),
colGroups: useColumnGroup(editor)
};
editor.undoManager.ignore(function () {
var table = render$1(rows, columns, rowHeaders, colHeaders, getTableHeaderType(editor), options);
set(table, 'data-mce-id', '__mce');
var html = getOuter$2(table);
editor.insertContent(html);
editor.addVisual();
});
return descendant$1(getBody$1(editor), 'table[data-mce-id="__mce"]').map(function (table) {
if (isPixelsForced(editor)) {
enforcePixels(editor, table);
} else if (isResponsiveForced(editor)) {
enforceNone(table);
} else if (isPercentagesForced(editor) || isPercentage$1(defaultStyles.width)) {
enforcePercentage(editor, table);
}
removeDataStyle(table);
remove(table, 'data-mce-id');
fireEvents(editor, table);
selectFirstCellInTable(editor, table);
return table.dom;
}).getOr(null);
};
var insertTableWithDataValidation = function (editor, rows, columns, options, errorMsg) {
if (options === void 0) {
options = {};
}
var checkInput = function (val) {
return isNumber(val) && val > 0;
};
if (checkInput(rows) && checkInput(columns)) {
var headerRows = options.headerRows || 0;
var headerColumns = options.headerColumns || 0;
return insert$1(editor, columns, rows, headerColumns, headerRows);
} else {
console.error(errorMsg);
return null;
}
};
var getClipboardElements = function (getClipboard) {
return function () {
return getClipboard().fold(function () {
return [];
}, function (elems) {
return map(elems, function (e) {
return e.dom;
});
});
};
};
var setClipboardElements = function (setClipboard) {
return function (elems) {
var elmsOpt = elems.length > 0 ? Optional.some(fromDom$1(elems)) : Optional.none();
setClipboard(elmsOpt);
};
};
var insertTable = function (editor) {
return function (columns, rows, options) {
if (options === void 0) {
options = {};
}
var table = insertTableWithDataValidation(editor, rows, columns, options, 'Invalid values for insertTable - rows and columns values are required to insert a table.');
editor.undoManager.add();
return table;
};
};
var getApi = function (editor, clipboard, resizeHandler, selectionTargets) {
return {
insertTable: insertTable(editor),
setClipboardRows: setClipboardElements(clipboard.setRows),
getClipboardRows: getClipboardElements(clipboard.getRows),
setClipboardCols: setClipboardElements(clipboard.setColumns),
getClipboardCols: getClipboardElements(clipboard.getColumns),
resizeHandler: resizeHandler,
selectionTargets: selectionTargets
};
};
var constrainSpan = function (element, property, value) {
var currentColspan = getAttrValue(element, property, 1);
if (value === 1 || currentColspan <= 1) {
remove(element, property);
} else {
set(element, property, Math.min(value, currentColspan));
}
};
var generateColGroup = function (house, minColRange, maxColRange) {
if (Warehouse.hasColumns(house)) {
var colsToCopy = filter(Warehouse.justColumns(house), function (col) {
return col.column >= minColRange && col.column < maxColRange;
});
var copiedCols = map(colsToCopy, function (c) {
var clonedCol = deep(c.element);
constrainSpan(clonedCol, 'span', maxColRange - minColRange);
return clonedCol;
});
var fakeColgroup = SugarElement.fromTag('colgroup');
append$1(fakeColgroup, copiedCols);
return [fakeColgroup];
} else {
return [];
}
};
var generateRows = function (house, minColRange, maxColRange) {
return map(house.all, function (row) {
var cellsToCopy = filter(row.cells, function (cell) {
return cell.column >= minColRange && cell.column < maxColRange;
});
var copiedCells = map(cellsToCopy, function (cell) {
var clonedCell = deep(cell.element);
constrainSpan(clonedCell, 'colspan', maxColRange - minColRange);
return clonedCell;
});
var fakeTR = SugarElement.fromTag('tr');
append$1(fakeTR, copiedCells);
return fakeTR;
});
};
var copyCols = function (table, target) {
var house = Warehouse.fromTable(table);
var details = onUnlockedCells(house, target);
return details.map(function (selectedCells) {
var lastSelectedCell = selectedCells[selectedCells.length - 1];
var minColRange = selectedCells[0].column;
var maxColRange = lastSelectedCell.column + lastSelectedCell.colspan;
var fakeColGroups = generateColGroup(house, minColRange, maxColRange);
var fakeRows = generateRows(house, minColRange, maxColRange);
return __spreadArrays(fakeColGroups, fakeRows);
});
};
var copyRows = function (table, target, generators) {
var warehouse = Warehouse.fromTable(table);
var details = onCells(warehouse, target);
return details.bind(function (selectedCells) {
var grid = toGrid(warehouse, generators, false);
var rows = extractGridDetails(grid).rows;
var slicedGrid = rows.slice(selectedCells[0].row, selectedCells[selectedCells.length - 1].row + selectedCells[selectedCells.length - 1].rowspan);
var filteredGrid = bind(slicedGrid, function (row) {
var newCells = filter(row.cells, function (cell) {
return !cell.isLocked;
});
return newCells.length > 0 ? [__assign(__assign({}, row), { cells: newCells })] : [];
});
var slicedDetails = toDetailList(filteredGrid, generators);
return someIf(slicedDetails.length > 0, slicedDetails);
}).map(function (slicedDetails) {
return copy$2(slicedDetails);
});
};
var global$1 = tinymce.util.Tools.resolve('tinymce.util.Tools');
var getTDTHOverallStyle = function (dom, elm, name) {
var cells = dom.select('td,th', elm);
var firstChildStyle;
var checkChildren = function (firstChildStyle, elms) {
for (var i = 0; i < elms.length; i++) {
var currentStyle = dom.getStyle(elms[i], name);
if (typeof firstChildStyle === 'undefined') {
firstChildStyle = currentStyle;
}
if (firstChildStyle !== currentStyle) {
return '';
}
}
return firstChildStyle;
};
return checkChildren(firstChildStyle, cells);
};
var applyAlign = function (editor, elm, name) {
if (name) {
editor.formatter.apply('align' + name, {}, elm);
}
};
var applyVAlign = function (editor, elm, name) {
if (name) {
editor.formatter.apply('valign' + name, {}, elm);
}
};
var unApplyAlign = function (editor, elm) {
global$1.each('left center right'.split(' '), function (name) {
editor.formatter.remove('align' + name, {}, elm);
});
};
var unApplyVAlign = function (editor, elm) {
global$1.each('top middle bottom'.split(' '), function (name) {
editor.formatter.remove('valign' + name, {}, elm);
});
};
var isListGroup = function (item) {
return hasNonNullableKey(item, 'menu');
};
var buildListItems = function (inputList, startItems) {
var appendItems = function (values, acc) {
return acc.concat(map(values, function (item) {
var text = item.text || item.title;
if (isListGroup(item)) {
return {
text: text,
items: buildListItems(item.menu)
};
} else {
return {
text: text,
value: item.value
};
}
}));
};
return appendItems(inputList, startItems || []);
};
var rgbToHex = function (dom) {
return function (value) {
return startsWith(value, 'rgb') ? dom.toHex(value) : value;
};
};
var extractAdvancedStyles = function (dom, elm) {
var element = SugarElement.fromDom(elm);
return {
borderwidth: getRaw(element, 'border-width').getOr(''),
borderstyle: getRaw(element, 'border-style').getOr(''),
bordercolor: getRaw(element, 'border-color').map(rgbToHex(dom)).getOr(''),
backgroundcolor: getRaw(element, 'background-color').map(rgbToHex(dom)).getOr('')
};
};
var getSharedValues = function (data) {
var baseData = data[0];
var comparisonData = data.slice(1);
each(comparisonData, function (items) {
each(keys(baseData), function (key) {
each$1(items, function (itemValue, itemKey) {
var comparisonValue = baseData[key];
if (comparisonValue !== '' && key === itemKey) {
if (comparisonValue !== itemValue) {
baseData[key] = '';
}
}
});
});
});
return baseData;
};
var getAdvancedTab = function (dialogName) {
var advTabItems = [
{
name: 'borderstyle',
type: 'listbox',
label: 'Border style',
items: [
{
text: 'Select...',
value: ''
},
{
text: 'Solid',
value: 'solid'
},
{
text: 'Dotted',
value: 'dotted'
},
{
text: 'Dashed',
value: 'dashed'
},
{
text: 'Double',
value: 'double'
},
{
text: 'Groove',
value: 'groove'
},
{
text: 'Ridge',
value: 'ridge'
},
{
text: 'Inset',
value: 'inset'
},
{
text: 'Outset',
value: 'outset'
},
{
text: 'None',
value: 'none'
},
{
text: 'Hidden',
value: 'hidden'
}
]
},
{
name: 'bordercolor',
type: 'colorinput',
label: 'Border color'
},
{
name: 'backgroundcolor',
type: 'colorinput',
label: 'Background color'
}
];
var borderWidth = {
name: 'borderwidth',
type: 'input',
label: 'Border width'
};
var items = dialogName === 'cell' ? [borderWidth].concat(advTabItems) : advTabItems;
return {
title: 'Advanced',
name: 'advanced',
items: items
};
};
var getAlignment = function (formats, formatName, editor, elm) {
return find(formats, function (name) {
return editor.formatter.matchNode(elm, formatName + name);
}).getOr('');
};
var getHAlignment = curry(getAlignment, [
'left',
'center',
'right'
], 'align');
var getVAlignment = curry(getAlignment, [
'top',
'middle',
'bottom'
], 'valign');
var extractDataFromSettings = function (editor, hasAdvTableTab) {
var style = getDefaultStyles(editor);
var attrs = getDefaultAttributes(editor);
var extractAdvancedStyleData = function (dom) {
return {
borderstyle: get$1(style, 'border-style').getOr(''),
bordercolor: rgbToHex(dom)(get$1(style, 'border-color').getOr('')),
backgroundcolor: rgbToHex(dom)(get$1(style, 'background-color').getOr(''))
};
};
var defaultData = {
height: '',
width: '100%',
cellspacing: '',
cellpadding: '',
caption: false,
class: '',
align: '',
border: ''
};
var getBorder = function () {
var borderWidth = style['border-width'];
if (shouldStyleWithCss(editor) && borderWidth) {
return { border: borderWidth };
}
return get$1(attrs, 'border').fold(function () {
return {};
}, function (border) {
return { border: border };
});
};
var advStyle = hasAdvTableTab ? extractAdvancedStyleData(editor.dom) : {};
var getCellPaddingCellSpacing = function () {
var spacing = get$1(style, 'border-spacing').or(get$1(attrs, 'cellspacing')).fold(function () {
return {};
}, function (cellspacing) {
return { cellspacing: cellspacing };
});
var padding = get$1(style, 'border-padding').or(get$1(attrs, 'cellpadding')).fold(function () {
return {};
}, function (cellpadding) {
return { cellpadding: cellpadding };
});
return __assign(__assign({}, spacing), padding);
};
var data = __assign(__assign(__assign(__assign(__assign(__assign({}, defaultData), style), attrs), advStyle), getBorder()), getCellPaddingCellSpacing());
return data;
};
var extractDataFromTableElement = function (editor, elm, hasAdvTableTab) {
var getBorder = function (dom, elm) {
var 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');
};
var dom = editor.dom;
return __assign({
width: dom.getStyle(elm, 'width') || dom.getAttrib(elm, 'width'),
height: dom.getStyle(elm, 'height') || dom.getAttrib(elm, 'height'),
cellspacing: dom.getStyle(elm, 'border-spacing') || dom.getAttrib(elm, 'cellspacing'),
cellpadding: dom.getAttrib(elm, 'cellpadding') || getTDTHOverallStyle(editor.dom, elm, 'padding'),
border: getBorder(dom, elm),
caption: !!dom.select('caption', elm)[0],
class: dom.getAttrib(elm, 'class', ''),
align: getHAlignment(editor, elm)
}, hasAdvTableTab ? extractAdvancedStyles(dom, elm) : {});
};
var extractDataFromRowElement = function (editor, elm, hasAdvancedRowTab) {
var dom = editor.dom;
return __assign({
height: dom.getStyle(elm, 'height') || dom.getAttrib(elm, 'height'),
class: dom.getAttrib(elm, 'class', ''),
type: getRowType(editor, elm),
align: getHAlignment(editor, elm)
}, hasAdvancedRowTab ? extractAdvancedStyles(dom, elm) : {});
};
var extractDataFromCellElement = function (editor, cell, hasAdvancedCellTab, column) {
var dom = editor.dom;
var colElm = column.getOr(cell);
var getStyle = function (element, style) {
return dom.getStyle(element, style) || dom.getAttrib(element, style);
};
return __assign({
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(dom, cell) : {});
};
var getClassList = function (editor) {
var classes = buildListItems(getCellClassList(editor));
if (classes.length > 0) {
return Optional.some({
name: 'class',
type: 'listbox',
label: 'Class',
items: classes
});
}
return Optional.none();
};
var children$3 = [
{
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: [
{
text: 'None',
value: ''
},
{
text: 'Top',
value: 'top'
},
{
text: 'Middle',
value: 'middle'
},
{
text: 'Bottom',
value: 'bottom'
}
]
}
];
var getItems = function (editor) {
return children$3.concat(getClassList(editor).toArray());
};
var modifiers = function (testTruthy) {
return function (editor, node) {
var dom = editor.dom;
var setAttrib = function (attr, value) {
if (!testTruthy || value) {
dom.setAttrib(node, attr, value);
}
};
var setStyle = function (prop, value) {
if (!testTruthy || value) {
dom.setStyle(node, prop, value);
}
};
var setFormat = function (formatName, value) {
if (!testTruthy || value) {
if (value === '') {
editor.formatter.remove(formatName, { value: null }, node, true);
} else {
editor.formatter.apply(formatName, { value: value }, node);
}
}
};
return {
setAttrib: setAttrib,
setStyle: setStyle,
setFormat: setFormat
};
};
};
var DomModifier = {
normal: modifiers(false),
ifTruthy: modifiers(true)
};
var getSelectedCells = function (cells) {
return table(cells[0]).map(function (table) {
var warehouse = Warehouse.fromTable(table);
var allCells = Warehouse.justCells(warehouse);
var filtered = filter(allCells, function (cellA) {
return exists(cells, function (cellB) {
return eq$1(cellA.element, cellB);
});
});
return map(filtered, function (cell) {
return {
element: cell.element.dom,
column: Warehouse.getColumnAt(warehouse, cell.column).map(function (col) {
return col.element.dom;
})
};
});
});
};
var updateSimpleProps = function (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));
};
var updateAdvancedProps = function (modifier, data) {
modifier.setFormat('tablecellbackgroundcolor', data.backgroundcolor);
modifier.setFormat('tablecellbordercolor', data.bordercolor);
modifier.setFormat('tablecellborderstyle', data.borderstyle);
modifier.setFormat('tablecellborderwidth', addPxSuffix(data.borderwidth));
};
var applyCellData = function (editor, cells, oldData, data) {
var isSingleCell = cells.length === 1;
var modifiedData = filter$1(data, function (value, key) {
return oldData[key] !== value;
});
if (size(modifiedData) > 0 && cells.length >= 1) {
var tableOpt = table(cells[0]);
getSelectedCells(cells).each(function (selectedCells) {
each(selectedCells, function (item) {
var cellElm = switchCellType(editor, item.element, data.celltype);
var modifier = isSingleCell ? DomModifier.normal(editor, cellElm) : DomModifier.ifTruthy(editor, cellElm);
var colModifier = item.column.map(function (col) {
return isSingleCell ? DomModifier.normal(editor, col) : DomModifier.ifTruthy(editor, col);
}).getOr(modifier);
updateSimpleProps(modifier, colModifier, data);
if (hasAdvancedCellTab(editor)) {
updateAdvancedProps(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);
}
});
});
var styleModified_1 = size(filter$1(modifiedData, function (_value, key) {
return key !== 'scope' && key !== 'celltype';
})) > 0;
tableOpt.each(function (table) {
return fireTableModified(editor, table.dom, {
structure: has(modifiedData, 'celltype'),
style: styleModified_1
});
});
}
};
var onSubmitCellForm = function (editor, cells, oldData, api) {
var data = api.getData();
api.close();
editor.undoManager.transact(function () {
applyCellData(editor, cells, oldData, data);
editor.focus();
});
};
var getData = function (editor, cells) {
var cellsData = getSelectedCells(cells).map(function (selectedCells) {
return map(selectedCells, function (item) {
return extractDataFromCellElement(editor, item.element, hasAdvancedCellTab(editor), item.column);
});
});
return getSharedValues(cellsData.getOrDie());
};
var open = function (editor, selections) {
var cells = getCellsFromSelection(getSelectionStart(editor), selections);
if (cells.length === 0) {
return;
}
var data = getData(editor, cells);
var dialogTabPanel = {
type: 'tabpanel',
tabs: [
{
title: 'General',
name: 'general',
items: getItems(editor)
},
getAdvancedTab('cell')
]
};
var dialogPanel = {
type: 'panel',
items: [{
type: 'grid',
columns: 2,
items: getItems(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)
});
};
var getClassList$1 = function (editor) {
var classes = buildListItems(getRowClassList(editor));
if (classes.length > 0) {
return Optional.some({
name: 'class',
type: 'listbox',
label: 'Class',
items: classes
});
}
return Optional.none();
};
var 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'
}
];
var getItems$1 = function (editor) {
return formChildren.concat(getClassList$1(editor).toArray());
};
var updateSimpleProps$1 = function (modifier, data) {
modifier.setAttrib('class', data.class);
modifier.setStyle('height', addPxSuffix(data.height));
};
var updateAdvancedProps$1 = function (modifier, data) {
modifier.setStyle('background-color', data.backgroundcolor);
modifier.setStyle('border-color', data.bordercolor);
modifier.setStyle('border-style', data.borderstyle);
};
var applyRowData = function (editor, rows, oldData, data) {
var isSingleRow = rows.length === 1;
var modifiedData = filter$1(data, function (value, key) {
return oldData[key] !== value;
});
if (size(modifiedData) > 0) {
each(rows, function (rowElm) {
if (data.type !== getNodeName(rowElm.parentNode)) {
switchSectionType(editor, rowElm, data.type);
}
var modifier = isSingleRow ? DomModifier.normal(editor, rowElm) : DomModifier.ifTruthy(editor, rowElm);
updateSimpleProps$1(modifier, data);
if (hasAdvancedRowTab(editor)) {
updateAdvancedProps$1(modifier, data);
}
if (data.align !== oldData.align) {
unApplyAlign(editor, rowElm);
applyAlign(editor, rowElm, data.align);
}
});
var typeModified_1 = has(modifiedData, 'type');
var styleModified_1 = typeModified_1 ? size(modifiedData) > 1 : true;
table(SugarElement.fromDom(rows[0])).each(function (table) {
return fireTableModified(editor, table.dom, {
structure: typeModified_1,
style: styleModified_1
});
});
}
};
var onSubmitRowForm = function (editor, rows, oldData, api) {
var data = api.getData();
api.close();
editor.undoManager.transact(function () {
applyRowData(editor, rows, oldData, data);
editor.focus();
});
};
var open$1 = function (editor) {
var rows = getRowsFromSelection(getSelectionStart(editor), ephemera.selected);
if (rows.length === 0) {
return;
}
var rowsData = map(rows, function (rowElm) {
return extractDataFromRowElement(editor, rowElm.dom, hasAdvancedRowTab(editor));
});
var data = getSharedValues(rowsData);
var dialogTabPanel = {
type: 'tabpanel',
tabs: [
{
title: 'General',
name: 'general',
items: getItems$1(editor)
},
getAdvancedTab('row')
]
};
var 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, function (r) {
return r.dom;
}), data)
});
};
var global$2 = tinymce.util.Tools.resolve('tinymce.Env');
var getItems$2 = function (editor, classes, insertNewTable) {
var rowColCountItems = !insertNewTable ? [] : [
{
type: 'input',
name: 'cols',
label: 'Cols',
inputMode: 'numeric'
},
{
type: 'input',
name: 'rows',
label: 'Rows',
inputMode: 'numeric'
}
];
var alwaysItems = [
{
type: 'input',
name: 'width',
label: 'Width'
},
{
type: 'input',
name: 'height',
label: 'Height'
}
];
var 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'
}]
}
] : [];
var alignmentItem = [{
type: 'listbox',
name: 'align',
label: 'Alignment',
items: [
{
text: 'None',
value: ''
},
{
text: 'Left',
value: 'left'
},
{
text: 'Center',
value: 'center'
},
{
text: 'Right',
value: 'right'
}
]
}];
var classListItem = classes.length > 0 ? [{
type: 'listbox',
name: 'class',
label: 'Class',
items: classes
}] : [];
return rowColCountItems.concat(alwaysItems).concat(appearanceItems).concat(alignmentItem).concat(classListItem);
};
var styleTDTH = function (dom, elm, name, value) {
if (elm.tagName === 'TD' || elm.tagName === 'TH') {
if (isString(name)) {
dom.setStyle(elm, name, value);
} else {
dom.setStyle(elm, name);
}
} else {
if (elm.children) {
for (var i = 0; i < elm.children.length; i++) {
styleTDTH(dom, elm.children[i], name, value);
}
}
}
};
var applyDataToElement = function (editor, tableElm, data) {
var dom = editor.dom;
var attrs = {};
var 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 (var 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(__assign(__assign({}, getDefaultStyles(editor)), styles));
dom.setAttribs(tableElm, __assign(__assign({}, getDefaultAttributes(editor)), attrs));
};
var onSubmitTableForm = function (editor, tableElm, oldData, api) {
var dom = editor.dom;
var captionElm;
var data = api.getData();
var modifiedData = filter$1(data, function (value, key) {
return oldData[key] !== value;
});
api.close();
if (data.class === '') {
delete data.class;
}
editor.undoManager.transact(function () {
if (!tableElm) {
var cols = parseInt(data.cols, 10) || 1;
var rows = parseInt(data.rows, 10) || 1;
tableElm = insert$1(editor, cols, rows, 0, 0);
}
if (size(modifiedData) > 0) {
applyDataToElement(editor, tableElm, data);
captionElm = dom.select('caption', tableElm)[0];
if (captionElm && !data.caption) {
dom.remove(captionElm);
}
if (!captionElm && data.caption) {
captionElm = dom.create('caption');
captionElm.innerHTML = !global$2.ie ? '<br data-mce-bogus="1"/>' : nbsp;
tableElm.insertBefore(captionElm, tableElm.firstChild);
}
if (data.align === '') {
unApplyAlign(editor, tableElm);
} else {
applyAlign(editor, tableElm, data.align);
}
}
editor.focus();
editor.addVisual();
if (size(modifiedData) > 0) {
var captionModified = has(modifiedData, 'caption');
var styleModified = captionModified ? size(modifiedData) > 1 : true;
fireTableModified(editor, tableElm, {
structure: captionModified,
style: styleModified
});
}
});
};
var open$2 = function (editor, insertNewTable) {
var dom = editor.dom;
var tableElm;
var 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 = '';
}
}
var classes = buildListItems(getTableClassList(editor));
if (classes.length > 0) {
if (data.class) {
data.class = data.class.replace(/\s*mce\-item\-table\s*/g, '');
}
}
var generalPanel = {
type: 'grid',
columns: 2,
items: getItems$2(editor, classes, insertNewTable)
};
var nonAdvancedForm = function () {
return {
type: 'panel',
items: [generalPanel]
};
};
var advancedForm = function () {
return {
type: 'tabpanel',
tabs: [
{
title: 'General',
name: 'general',
items: [generalPanel]
},
getAdvancedTab('table')
]
};
};
var 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
});
};
var getSelectionStartCellOrCaption$1 = function (editor) {
return getSelectionStartCellOrCaption(getSelectionStart(editor), getIsRoot(editor));
};
var getSelectionStartCell$1 = function (editor) {
return getSelectionStartCell(getSelectionStart(editor), getIsRoot(editor));
};
var registerCommands = function (editor, actions, cellSelection, selections, clipboard) {
var isRoot = getIsRoot(editor);
var eraseTable = function () {
return getSelectionStartCellOrCaption$1(editor).each(function (cellOrCaption) {
table(cellOrCaption, isRoot).filter(not(isRoot)).each(function (table) {
var cursor = SugarElement.fromText('');
after(table, cursor);
remove$2(table);
if (editor.dom.isEmpty(editor.getBody())) {
editor.setContent('');
editor.selection.setCursorLocation();
} else {
var rng = editor.dom.createRng();
rng.setStart(cursor.dom, 0);
rng.setEnd(cursor.dom, 0);
editor.selection.setRng(rng);
editor.nodeChanged();
}
});
});
};
var setSizingMode = function (sizing) {
return getSelectionStartCellOrCaption$1(editor).each(function (cellOrCaption) {
var isForcedSizing = isResponsiveForced(editor) || isPixelsForced(editor) || isPercentagesForced(editor);
if (!isForcedSizing) {
table(cellOrCaption, isRoot).each(function (table) {
if (sizing === 'relative' && !isPercentSizing$1(table)) {
enforcePercentage(editor, table);
} else if (sizing === 'fixed' && !isPixelSizing$1(table)) {
enforcePixels(editor, table);
} else if (sizing === 'responsive' && !isNoneSizing$1(table)) {
enforceNone(table);
}
removeDataStyle(table);
fireTableModified(editor, table.dom, structureModified);
});
}
});
};
var getTableFromCell = function (cell) {
return table(cell, isRoot);
};
var postExecute = function (table) {
return function (data) {
editor.selection.setRng(data.rng);
editor.focus();
cellSelection.clear(table);
removeDataStyle(table);
fireTableModified(editor, table.dom, data.effect);
};
};
var actOnSelection = function (execute) {
return getSelectionStartCell$1(editor).each(function (cell) {
getTableFromCell(cell).each(function (table) {
var targets = forMenu(selections, table, cell);
execute(table, targets).each(postExecute(table));
});
});
};
var copyRowSelection = function () {
return getSelectionStartCell$1(editor).map(function (cell) {
return getTableFromCell(cell).bind(function (table) {
var targets = forMenu(selections, table, cell);
var generators = cellOperations(noop, SugarElement.fromDom(editor.getDoc()), Optional.none());
return copyRows(table, targets, generators);
});
});
};
var copyColSelection = function () {
return getSelectionStartCell$1(editor).map(function (cell) {
return getTableFromCell(cell).bind(function (table) {
var targets = forMenu(selections, table, cell);
return copyCols(table, targets);
});
});
};
var pasteOnSelection = function (execute, getRows) {
return getRows().each(function (rows) {
var clonedRows = map(rows, function (row) {
return deep(row);
});
getSelectionStartCell$1(editor).each(function (cell) {
return getTableFromCell(cell).each(function (table) {
var generators = paste(SugarElement.fromDom(editor.getDoc()));
var targets = pasteRows(selections, cell, clonedRows, generators);
execute(table, targets).each(postExecute(table));
});
});
});
};
each$1({
mceTableSplitCells: function () {
return actOnSelection(actions.unmergeCells);
},
mceTableMergeCells: function () {
return actOnSelection(actions.mergeCells);
},
mceTableInsertRowBefore: function () {
return actOnSelection(actions.insertRowsBefore);
},
mceTableInsertRowAfter: function () {
return actOnSelection(actions.insertRowsAfter);
},
mceTableInsertColBefore: function () {
return actOnSelection(actions.insertColumnsBefore);
},
mceTableInsertColAfter: function () {
return actOnSelection(actions.insertColumnsAfter);
},
mceTableDeleteCol: function () {
return actOnSelection(actions.deleteColumn);
},
mceTableDeleteRow: function () {
return actOnSelection(actions.deleteRow);
},
mceTableCutCol: function (_grid) {
return copyColSelection().each(function (selection) {
clipboard.setColumns(selection);
actOnSelection(actions.deleteColumn);
});
},
mceTableCutRow: function (_grid) {
return copyRowSelection().each(function (selection) {
clipboard.setRows(selection);
actOnSelection(actions.deleteRow);
});
},
mceTableCopyCol: function (_grid) {
return copyColSelection().each(function (selection) {
return clipboard.setColumns(selection);
});
},
mceTableCopyRow: function (_grid) {
return copyRowSelection().each(function (selection) {
return clipboard.setRows(selection);
});
},
mceTablePasteColBefore: function (_grid) {
return pasteOnSelection(actions.pasteColsBefore, clipboard.getColumns);
},
mceTablePasteColAfter: function (_grid) {
return pasteOnSelection(actions.pasteColsAfter, clipboard.getColumns);
},
mceTablePasteRowBefore: function (_grid) {
return pasteOnSelection(actions.pasteRowsBefore, clipboard.getRows);
},
mceTablePasteRowAfter: function (_grid) {
return pasteOnSelection(actions.pasteRowsAfter, clipboard.getRows);
},
mceTableDelete: eraseTable,
mceTableSizingMode: function (ui, sizing) {
return setSizingMode(sizing);
}
}, function (func, name) {
return editor.addCommand(name, func);
});
var fireTableModifiedForSelection = function (editor, tableOpt) {
tableOpt.each(function (table) {
fireTableModified(editor, table.dom, structureModified);
});
};
each$1({
mceTableCellType: function (_ui, args) {
var tableOpt = table(getSelectionStart(editor), isRoot);
actions.setTableCellType(editor, args);
fireTableModifiedForSelection(editor, tableOpt);
},
mceTableRowType: function (_ui, args) {
var tableOpt = table(getSelectionStart(editor), isRoot);
actions.setTableRowType(editor, args);
fireTableModifiedForSelection(editor, tableOpt);
}
}, function (func, name) {
return editor.addCommand(name, func);
});
editor.addCommand('mceTableColType', function (_ui, args) {
return get$1(args, 'type').each(function (type) {
return actOnSelection(type === 'th' ? actions.makeColumnsHeader : actions.unmakeColumnsHeader);
});
});
each$1({
mceTableProps: curry(open$2, editor, false),
mceTableRowProps: curry(open$1, editor),
mceTableCellProps: curry(open, editor, selections)
}, function (func, name) {
return editor.addCommand(name, function () {
return func();
});
});
editor.addCommand('mceInsertTable', function (_ui, args) {
if (isObject(args) && keys(args).length > 0) {
insertTableWithDataValidation(editor, args.rows, args.columns, args.options, 'Invalid values for mceInsertTable - rows and columns values are required to insert a table.');
} else {
open$2(editor, true);
}
});
editor.addCommand('mceTableApplyCellStyle', function (_ui, args) {
var getFormatName = function (style) {
return 'tablecell' + style.toLowerCase().replace('-', '');
};
if (!isObject(args)) {
return;
}
var cells = getCellsFromSelection(getSelectionStart(editor), selections, isRoot);
if (cells.length === 0) {
return;
}
var validArgs = filter$1(args, function (value, style) {
return editor.formatter.has(getFormatName(style)) && isString(value);
});
if (isEmpty(validArgs)) {
return;
}
each$1(validArgs, function (value, style) {
each(cells, function (cell) {
DomModifier.normal(editor, cell.dom).setFormat(getFormatName(style), value);
});
});
getTableFromCell(cells[0]).each(function (table) {
return fireTableModified(editor, table.dom, styleModified);
});
});
};
var registerQueryCommands = function (editor, actions, selections) {
var isRoot = getIsRoot(editor);
var getTableFromCell = function (cell) {
return table(cell, isRoot);
};
each$1({
mceTableRowType: function () {
return actions.getTableRowType(editor);
},
mceTableCellType: function () {
return actions.getTableCellType(editor);
},
mceTableColType: function () {
return getSelectionStartCell(getSelectionStart(editor)).bind(function (cell) {
return getTableFromCell(cell).map(function (table) {
var targets = forMenu(selections, table, cell);
return actions.getTableColType(table, targets);
});
}).getOr('');
}
}, function (func, name) {
return editor.addQueryValueHandler(name, func);
});
};
var Clipboard = function () {
var rows = Cell(Optional.none());
var cols = Cell(Optional.none());
var clearClipboard = function (clipboard) {
clipboard.set(Optional.none());
};
return {
getRows: rows.get,
setRows: function (r) {
rows.set(r);
clearClipboard(cols);
},
clearRows: function () {
return clearClipboard(rows);
},
getColumns: cols.get,
setColumns: function (c) {
cols.set(c);
clearClipboard(rows);
},
clearColumns: function () {
return clearClipboard(cols);
}
};
};
var cellFormats = {
tablecellbackgroundcolor: {
selector: 'td,th',
styles: { backgroundColor: '%value' },
remove_similar: true
},
tablecellbordercolor: {
selector: 'td,th',
styles: { borderColor: '%value' },
remove_similar: true
},
tablecellborderstyle: {
selector: 'td,th',
styles: { borderStyle: '%value' },
remove_similar: true
},
tablecellborderwidth: {
selector: 'td,th',
styles: { borderWidth: '%value' },
remove_similar: true
}
};
var registerFormats = function (editor) {
editor.formatter.register(cellFormats);
};
var adt$2 = Adt.generate([
{ none: ['current'] },
{ first: ['current'] },
{
middle: [
'current',
'target'
]
},
{ last: ['current'] }
]);
var none$2 = function (current) {
if (current === void 0) {
current = undefined;
}
return adt$2.none(current);
};
var CellLocation = __assign(__assign({}, adt$2), { none: none$2 });
var detect$5 = function (current, isRoot) {
return table(current, isRoot).bind(function (table) {
var all = cells(table);
var index = findIndex(all, function (x) {
return eq$1(current, x);
});
return index.map(function (index) {
return {
index: index,
all: all
};
});
});
};
var next = function (current, isRoot) {
var detection = detect$5(current, isRoot);
return detection.fold(function () {
return CellLocation.none(current);
}, function (info) {
return info.index + 1 < info.all.length ? CellLocation.middle(current, info.all[info.index + 1]) : CellLocation.last(current);
});
};
var prev = function (current, isRoot) {
var detection = detect$5(current, isRoot);
return detection.fold(function () {
return CellLocation.none();
}, function (info) {
return info.index - 1 >= 0 ? CellLocation.middle(current, info.all[info.index - 1]) : CellLocation.first(current);
});
};
var create$2 = function (start, soffset, finish, foffset) {
return {
start: start,
soffset: soffset,
finish: finish,
foffset: foffset
};
};
var SimRange = { create: create$2 };
var adt$3 = Adt.generate([
{ before: ['element'] },
{
on: [
'element',
'offset'
]
},
{ after: ['element'] }
]);
var cata$1 = function (subject, onBefore, onOn, onAfter) {
return subject.fold(onBefore, onOn, onAfter);
};
var getStart = function (situ) {
return situ.fold(identity, identity, identity);
};
var before$2 = adt$3.before;
var on = adt$3.on;
var after$2 = adt$3.after;
var Situ = {
before: before$2,
on: on,
after: after$2,
cata: cata$1,
getStart: getStart
};
var adt$4 = Adt.generate([
{ domRange: ['rng'] },
{
relative: [
'startSitu',
'finishSitu'
]
},
{
exact: [
'start',
'soffset',
'finish',
'foffset'
]
}
]);
var exactFromRange = function (simRange) {
return adt$4.exact(simRange.start, simRange.soffset, simRange.finish, simRange.foffset);
};
var getStart$1 = function (selection) {
return selection.match({
domRange: function (rng) {
return SugarElement.fromDom(rng.startContainer);
},
relative: function (startSitu, _finishSitu) {
return Situ.getStart(startSitu);
},
exact: function (start, _soffset, _finish, _foffset) {
return start;
}
});
};
var domRange = adt$4.domRange;
var relative = adt$4.relative;
var exact = adt$4.exact;
var getWin = function (selection) {
var start = getStart$1(selection);
return defaultView(start);
};
var range$1 = SimRange.create;
var SimSelection = {
domRange: domRange,
relative: relative,
exact: exact,
exactFromRange: exactFromRange,
getWin: getWin,
range: range$1
};
var selectNodeContents = function (win, element) {
var rng = win.document.createRange();
selectNodeContentsUsing(rng, element);
return rng;
};
var selectNodeContentsUsing = function (rng, element) {
return rng.selectNodeContents(element.dom);
};
var setStart = function (rng, situ) {
situ.fold(function (e) {
rng.setStartBefore(e.dom);
}, function (e, o) {
rng.setStart(e.dom, o);
}, function (e) {
rng.setStartAfter(e.dom);
});
};
var setFinish = function (rng, situ) {
situ.fold(function (e) {
rng.setEndBefore(e.dom);
}, function (e, o) {
rng.setEnd(e.dom, o);
}, function (e) {
rng.setEndAfter(e.dom);
});
};
var relativeToNative = function (win, startSitu, finishSitu) {
var range = win.document.createRange();
setStart(range, startSitu);
setFinish(range, finishSitu);
return range;
};
var exactToNative = function (win, start, soffset, finish, foffset) {
var rng = win.document.createRange();
rng.setStart(start.dom, soffset);
rng.setEnd(finish.dom, foffset);
return rng;
};
var toRect = function (rect) {
return {
left: rect.left,
top: rect.top,
right: rect.right,
bottom: rect.bottom,
width: rect.width,
height: rect.height
};
};
var getFirstRect = function (rng) {
var rects = rng.getClientRects();
var rect = rects.length > 0 ? rects[0] : rng.getBoundingClientRect();
return rect.width > 0 || rect.height > 0 ? Optional.some(rect).map(toRect) : Optional.none();
};
var adt$5 = Adt.generate([
{
ltr: [
'start',
'soffset',
'finish',
'foffset'
]
},
{
rtl: [
'start',
'soffset',
'finish',
'foffset'
]
}
]);
var fromRange = function (win, type, range) {
return type(SugarElement.fromDom(range.startContainer), range.startOffset, SugarElement.fromDom(range.endContainer), range.endOffset);
};
var getRanges = function (win, selection) {
return selection.match({
domRange: function (rng) {
return {
ltr: constant(rng),
rtl: Optional.none
};
},
relative: function (startSitu, finishSitu) {
return {
ltr: cached(function () {
return relativeToNative(win, startSitu, finishSitu);
}),
rtl: cached(function () {
return Optional.some(relativeToNative(win, finishSitu, startSitu));
})
};
},
exact: function (start, soffset, finish, foffset) {
return {
ltr: cached(function () {
return exactToNative(win, start, soffset, finish, foffset);
}),
rtl: cached(function () {
return Optional.some(exactToNative(win, finish, foffset, start, soffset));
})
};
}
});
};
var doDiagnose = function (win, ranges) {
var rng = ranges.ltr();
if (rng.collapsed) {
var reversed = ranges.rtl().filter(function (rev) {
return rev.collapsed === false;
});
return reversed.map(function (rev) {
return adt$5.rtl(SugarElement.fromDom(rev.endContainer), rev.endOffset, SugarElement.fromDom(rev.startContainer), rev.startOffset);
}).getOrThunk(function () {
return fromRange(win, adt$5.ltr, rng);
});
} else {
return fromRange(win, adt$5.ltr, rng);
}
};
var diagnose = function (win, selection) {
var ranges = getRanges(win, selection);
return doDiagnose(win, ranges);
};
var asLtrRange = function (win, selection) {
var diagnosis = diagnose(win, selection);
return diagnosis.match({
ltr: function (start, soffset, finish, foffset) {
var rng = win.document.createRange();
rng.setStart(start.dom, soffset);
rng.setEnd(finish.dom, foffset);
return rng;
},
rtl: function (start, soffset, finish, foffset) {
var rng = win.document.createRange();
rng.setStart(finish.dom, foffset);
rng.setEnd(start.dom, soffset);
return rng;
}
});
};
var ltr$1 = adt$5.ltr;
var rtl$1 = adt$5.rtl;
var searchForPoint = function (rectForOffset, x, y, maxX, length) {
if (length === 0) {
return 0;
} else if (x === maxX) {
return length - 1;
}
var xDelta = maxX;
for (var i = 1; i < length; i++) {
var rect = rectForOffset(i);
var curDeltaX = Math.abs(x - rect.left);
if (y <= rect.bottom) {
if (y < rect.top || curDeltaX > xDelta) {
return i - 1;
} else {
xDelta = curDeltaX;
}
}
}
return 0;
};
var inRect = function (rect, x, y) {
return x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom;
};
var locateOffset = function (doc, textnode, x, y, rect) {
var rangeForOffset = function (o) {
var r = doc.dom.createRange();
r.setStart(textnode.dom, o);
r.collapse(true);
return r;
};
var rectForOffset = function (o) {
var r = rangeForOffset(o);
return r.getBoundingClientRect();
};
var length = get$4(textnode).length;
var offset = searchForPoint(rectForOffset, x, y, rect.right, length);
return rangeForOffset(offset);
};
var locate = function (doc, node, x, y) {
var r = doc.dom.createRange();
r.selectNode(node.dom);
var rects = r.getClientRects();
var foundRect = findMap(rects, function (rect) {
return inRect(rect, x, y) ? Optional.some(rect) : Optional.none();
});
return foundRect.map(function (rect) {
return locateOffset(doc, node, x, y, rect);
});
};
var searchInChildren = function (doc, node, x, y) {
var r = doc.dom.createRange();
var nodes = children(node);
return findMap(nodes, function (n) {
r.selectNode(n.dom);
return inRect(r.getBoundingClientRect(), x, y) ? locateNode(doc, n, x, y) : Optional.none();
});
};
var locateNode = function (doc, node, x, y) {
return isText(node) ? locate(doc, node, x, y) : searchInChildren(doc, node, x, y);
};
var locate$1 = function (doc, node, x, y) {
var r = doc.dom.createRange();
r.selectNode(node.dom);
var rect = r.getBoundingClientRect();
var boundedX = Math.max(rect.left, Math.min(rect.right, x));
var boundedY = Math.max(rect.top, Math.min(rect.bottom, y));
return locateNode(doc, node, boundedX, boundedY);
};
var COLLAPSE_TO_LEFT = true;
var COLLAPSE_TO_RIGHT = false;
var getCollapseDirection = function (rect, x) {
return x - rect.left < rect.right - x ? COLLAPSE_TO_LEFT : COLLAPSE_TO_RIGHT;
};
var createCollapsedNode = function (doc, target, collapseDirection) {
var r = doc.dom.createRange();
r.selectNode(target.dom);
r.collapse(collapseDirection);
return r;
};
var locateInElement = function (doc, node, x) {
var cursorRange = doc.dom.createRange();
cursorRange.selectNode(node.dom);
var rect = cursorRange.getBoundingClientRect();
var collapseDirection = getCollapseDirection(rect, x);
var f = collapseDirection === COLLAPSE_TO_LEFT ? first : last$1;
return f(node).map(function (target) {
return createCollapsedNode(doc, target, collapseDirection);
});
};
var locateInEmpty = function (doc, node, x) {
var rect = node.dom.getBoundingClientRect();
var collapseDirection = getCollapseDirection(rect, x);
return Optional.some(createCollapsedNode(doc, node, collapseDirection));
};
var search = function (doc, node, x) {
var f = children(node).length === 0 ? locateInEmpty : locateInElement;
return f(doc, node, x);
};
var caretPositionFromPoint = function (doc, x, y) {
return Optional.from(doc.dom.caretPositionFromPoint(x, y)).bind(function (pos) {
if (pos.offsetNode === null) {
return Optional.none();
}
var r = doc.dom.createRange();
r.setStart(pos.offsetNode, pos.offset);
r.collapse();
return Optional.some(r);
});
};
var caretRangeFromPoint = function (doc, x, y) {
return Optional.from(doc.dom.caretRangeFromPoint(x, y));
};
var searchTextNodes = function (doc, node, x, y) {
var r = doc.dom.createRange();
r.selectNode(node.dom);
var rect = r.getBoundingClientRect();
var boundedX = Math.max(rect.left, Math.min(rect.right, x));
var boundedY = Math.max(rect.top, Math.min(rect.bottom, y));
return locate$1(doc, node, boundedX, boundedY);
};
var searchFromPoint = function (doc, x, y) {
return SugarElement.fromPoint(doc, x, y).bind(function (elem) {
var fallback = function () {
return search(doc, elem, x);
};
return children(elem).length === 0 ? fallback() : searchTextNodes(doc, elem, x, y).orThunk(fallback);
});
};
var availableSearch = function () {
if (document.caretPositionFromPoint) {
return caretPositionFromPoint;
} else if (document.caretRangeFromPoint) {
return caretRangeFromPoint;
} else {
return searchFromPoint;
}
}();
var fromPoint$1 = function (win, x, y) {
var doc = SugarElement.fromDom(win.document);
return availableSearch(doc, x, y).map(function (rng) {
return SimRange.create(SugarElement.fromDom(rng.startContainer), rng.startOffset, SugarElement.fromDom(rng.endContainer), rng.endOffset);
});
};
var beforeSpecial = function (element, offset) {
var name$1 = name(element);
if ('input' === name$1) {
return Situ.after(element);
} else if (!contains([
'br',
'img'
], name$1)) {
return Situ.on(element, offset);
} else {
return offset === 0 ? Situ.before(element) : Situ.after(element);
}
};
var preprocessRelative = function (startSitu, finishSitu) {
var start = startSitu.fold(Situ.before, beforeSpecial, Situ.after);
var finish = finishSitu.fold(Situ.before, beforeSpecial, Situ.after);
return SimSelection.relative(start, finish);
};
var preprocessExact = function (start, soffset, finish, foffset) {
var startSitu = beforeSpecial(start, soffset);
var finishSitu = beforeSpecial(finish, foffset);
return SimSelection.relative(startSitu, finishSitu);
};
var preprocess = function (selection) {
return selection.match({
domRange: function (rng) {
var start = SugarElement.fromDom(rng.startContainer);
var finish = SugarElement.fromDom(rng.endContainer);
return preprocessExact(start, rng.startOffset, finish, rng.endOffset);
},
relative: preprocessRelative,
exact: preprocessExact
});
};
var makeRange = function (start, soffset, finish, foffset) {
var doc = owner(start);
var rng = doc.dom.createRange();
rng.setStart(start.dom, soffset);
rng.setEnd(finish.dom, foffset);
return rng;
};
var after$3 = function (start, soffset, finish, foffset) {
var r = makeRange(start, soffset, finish, foffset);
var same = eq$1(start, finish) && soffset === foffset;
return r.collapsed && !same;
};
var getNativeSelection = function (win) {
return Optional.from(win.getSelection());
};
var doSetNativeRange = function (win, rng) {
getNativeSelection(win).each(function (selection) {
selection.removeAllRanges();
selection.addRange(rng);
});
};
var doSetRange = function (win, start, soffset, finish, foffset) {
var rng = exactToNative(win, start, soffset, finish, foffset);
doSetNativeRange(win, rng);
};
var setLegacyRtlRange = function (win, selection, start, soffset, finish, foffset) {
selection.collapse(start.dom, soffset);
selection.extend(finish.dom, foffset);
};
var setRangeFromRelative = function (win, relative) {
return diagnose(win, relative).match({
ltr: function (start, soffset, finish, foffset) {
doSetRange(win, start, soffset, finish, foffset);
},
rtl: function (start, soffset, finish, foffset) {
getNativeSelection(win).each(function (selection) {
if (selection.setBaseAndExtent) {
selection.setBaseAndExtent(start.dom, soffset, finish.dom, foffset);
} else if (selection.extend) {
try {
setLegacyRtlRange(win, selection, start, soffset, finish, foffset);
} catch (e) {
doSetRange(win, finish, foffset, start, soffset);
}
} else {
doSetRange(win, finish, foffset, start, soffset);
}
});
}
});
};
var setExact = function (win, start, soffset, finish, foffset) {
var relative = preprocessExact(start, soffset, finish, foffset);
setRangeFromRelative(win, relative);
};
var setRelative = function (win, startSitu, finishSitu) {
var relative = preprocessRelative(startSitu, finishSitu);
setRangeFromRelative(win, relative);
};
var toNative = function (selection) {
var win = SimSelection.getWin(selection).dom;
var getDomRange = function (start, soffset, finish, foffset) {
return exactToNative(win, start, soffset, finish, foffset);
};
var filtered = preprocess(selection);
return diagnose(win, filtered).match({
ltr: getDomRange,
rtl: getDomRange
});
};
var readRange = function (selection) {
if (selection.rangeCount > 0) {
var firstRng = selection.getRangeAt(0);
var lastRng = selection.getRangeAt(selection.rangeCount - 1);
return Optional.some(SimRange.create(SugarElement.fromDom(firstRng.startContainer), firstRng.startOffset, SugarElement.fromDom(lastRng.endContainer), lastRng.endOffset));
} else {
return Optional.none();
}
};
var doGetExact = function (selection) {
if (selection.anchorNode === null || selection.focusNode === null) {
return readRange(selection);
} else {
var anchor = SugarElement.fromDom(selection.anchorNode);
var focus_1 = SugarElement.fromDom(selection.focusNode);
return after$3(anchor, selection.anchorOffset, focus_1, selection.focusOffset) ? Optional.some(SimRange.create(anchor, selection.anchorOffset, focus_1, selection.focusOffset)) : readRange(selection);
}
};
var setToElement = function (win, element) {
var rng = selectNodeContents(win, element);
doSetNativeRange(win, rng);
};
var getExact = function (win) {
return getNativeSelection(win).filter(function (sel) {
return sel.rangeCount > 0;
}).bind(doGetExact);
};
var get$c = function (win) {
return getExact(win).map(function (range) {
return SimSelection.exact(range.start, range.soffset, range.finish, range.foffset);
});
};
var getFirstRect$1 = function (win, selection) {
var rng = asLtrRange(win, selection);
return getFirstRect(rng);
};
var getAtPoint = function (win, x, y) {
return fromPoint$1(win, x, y);
};
var clear = function (win) {
getNativeSelection(win).each(function (selection) {
return selection.removeAllRanges();
});
};
var global$3 = tinymce.util.Tools.resolve('tinymce.util.VK');
var forward = function (editor, isRoot, cell) {
return go(editor, isRoot, next(cell));
};
var backward = function (editor, isRoot, cell) {
return go(editor, isRoot, prev(cell));
};
var getCellFirstCursorPosition = function (editor, cell) {
var selection = SimSelection.exact(cell, 0, cell, 0);
return toNative(selection);
};
var getNewRowCursorPosition = function (editor, table) {
var rows = descendants$1(table, 'tr');
return last(rows).bind(function (last) {
return descendant$1(last, 'td,th').map(function (first) {
return getCellFirstCursorPosition(editor, first);
});
});
};
var go = function (editor, isRoot, cell) {
return cell.fold(Optional.none, Optional.none, function (current, next) {
return first(next).map(function (cell) {
return getCellFirstCursorPosition(editor, cell);
});
}, function (current) {
return table(current, isRoot).bind(function (table) {
editor.execCommand('mceTableInsertRowAfter');
return getNewRowCursorPosition(editor, table);
});
});
};
var rootElements = [
'table',
'li',
'dl'
];
var handle$1 = function (event, editor, cellSelection) {
if (event.keyCode === global$3.TAB) {
var body_1 = getBody$1(editor);
var isRoot_1 = function (element) {
var name$1 = name(element);
return eq$1(element, body_1) || contains(rootElements, name$1);
};
var rng = editor.selection.getRng();
var container = SugarElement.fromDom(event.shiftKey ? rng.startContainer : rng.endContainer);
cell(container, isRoot_1).each(function (cell) {
event.preventDefault();
table(cell, isRoot_1).each(cellSelection.clear);
editor.selection.collapse(event.shiftKey);
var navigation = event.shiftKey ? backward : forward;
var rng = navigation(editor, isRoot_1, cell);
rng.each(function (range) {
editor.selection.setRng(range);
});
});
}
};
var create$3 = function (selection, kill) {
return {
selection: selection,
kill: kill
};
};
var Response = { create: create$3 };
var create$4 = function (start, soffset, finish, foffset) {
return {
start: Situ.on(start, soffset),
finish: Situ.on(finish, foffset)
};
};
var Situs = { create: create$4 };
var convertToRange = function (win, selection) {
var rng = asLtrRange(win, selection);
return SimRange.create(SugarElement.fromDom(rng.startContainer), rng.startOffset, SugarElement.fromDom(rng.endContainer), rng.endOffset);
};
var makeSitus = Situs.create;
var sync = function (container, isRoot, start, soffset, finish, foffset, selectRange) {
if (!(eq$1(start, finish) && soffset === foffset)) {
return closest$1(start, 'td,th', isRoot).bind(function (s) {
return closest$1(finish, 'td,th', isRoot).bind(function (f) {
return detect$6(container, isRoot, s, f, selectRange);
});
});
} else {
return Optional.none();
}
};
var detect$6 = function (container, isRoot, start, finish, selectRange) {
if (!eq$1(start, finish)) {
return identify(start, finish, isRoot).bind(function (cellSel) {
var boxes = cellSel.boxes.getOr([]);
if (boxes.length > 0) {
selectRange(container, boxes, cellSel.start, cellSel.finish);
return Optional.some(Response.create(Optional.some(makeSitus(start, 0, start, getEnd(start))), true));
} else {
return Optional.none();
}
});
} else {
return Optional.none();
}
};
var update = function (rows, columns, container, selected, annotations) {
var updateSelection = function (newSels) {
annotations.clearBeforeUpdate(container);
annotations.selectRange(container, newSels.boxes, newSels.start, newSels.finish);
return newSels.boxes;
};
return shiftSelection(selected, rows, columns, annotations.firstSelectedSelector, annotations.lastSelectedSelector).map(updateSelection);
};
var traverse = function (item, mode) {
return {
item: item,
mode: mode
};
};
var backtrack = function (universe, item, _direction, transition) {
if (transition === void 0) {
transition = sidestep;
}
return universe.property().parent(item).map(function (p) {
return traverse(p, transition);
});
};
var sidestep = function (universe, item, direction, transition) {
if (transition === void 0) {
transition = advance;
}
return direction.sibling(universe, item).map(function (p) {
return traverse(p, transition);
});
};
var advance = function (universe, item, direction, transition) {
if (transition === void 0) {
transition = advance;
}
var children = universe.property().children(item);
var result = direction.first(children);
return result.map(function (r) {
return traverse(r, transition);
});
};
var successors = [
{
current: backtrack,
next: sidestep,
fallback: Optional.none()
},
{
current: sidestep,
next: advance,
fallback: Optional.some(backtrack)
},
{
current: advance,
next: advance,
fallback: Optional.some(sidestep)
}
];
var go$1 = function (universe, item, mode, direction, rules) {
if (rules === void 0) {
rules = successors;
}
var ruleOpt = find(rules, function (succ) {
return succ.current === mode;
});
return ruleOpt.bind(function (rule) {
return rule.current(universe, item, direction, rule.next).orThunk(function () {
return rule.fallback.bind(function (fb) {
return go$1(universe, item, fb, direction);
});
});
});
};
var left = function () {
var sibling = function (universe, item) {
return universe.query().prevSibling(item);
};
var first = function (children) {
return children.length > 0 ? Optional.some(children[children.length - 1]) : Optional.none();
};
return {
sibling: sibling,
first: first
};
};
var right = function () {
var sibling = function (universe, item) {
return universe.query().nextSibling(item);
};
var first = function (children) {
return children.length > 0 ? Optional.some(children[0]) : Optional.none();
};
return {
sibling: sibling,
first: first
};
};
var Walkers = {
left: left,
right: right
};
var hone = function (universe, item, predicate, mode, direction, isRoot) {
var next = go$1(universe, item, mode, direction);
return next.bind(function (n) {
if (isRoot(n.item)) {
return Optional.none();
} else {
return predicate(n.item) ? Optional.some(n.item) : hone(universe, n.item, predicate, n.mode, direction, isRoot);
}
});
};
var left$1 = function (universe, item, predicate, isRoot) {
return hone(universe, item, predicate, sidestep, Walkers.left(), isRoot);
};
var right$1 = function (universe, item, predicate, isRoot) {
return hone(universe, item, predicate, sidestep, Walkers.right(), isRoot);
};
var isLeaf = function (universe) {
return function (element) {
return universe.property().children(element).length === 0;
};
};
var before$3 = function (universe, item, isRoot) {
return seekLeft(universe, item, isLeaf(universe), isRoot);
};
var after$4 = function (universe, item, isRoot) {
return seekRight(universe, item, isLeaf(universe), isRoot);
};
var seekLeft = left$1;
var seekRight = right$1;
var universe$3 = DomUniverse();
var before$4 = function (element, isRoot) {
return before$3(universe$3, element, isRoot);
};
var after$5 = function (element, isRoot) {
return after$4(universe$3, element, isRoot);
};
var seekLeft$1 = function (element, predicate, isRoot) {
return seekLeft(universe$3, element, predicate, isRoot);
};
var seekRight$1 = function (element, predicate, isRoot) {
return seekRight(universe$3, element, predicate, isRoot);
};
var ancestor$2 = function (scope, predicate, isRoot) {
return ancestor(scope, predicate, isRoot).isSome();
};
var adt$6 = Adt.generate([
{ none: ['message'] },
{ success: [] },
{ failedUp: ['cell'] },
{ failedDown: ['cell'] }
]);
var isOverlapping = function (bridge, before, after) {
var beforeBounds = bridge.getRect(before);
var afterBounds = bridge.getRect(after);
return afterBounds.right > beforeBounds.left && afterBounds.left < beforeBounds.right;
};
var isRow = function (elem) {
return closest$1(elem, 'tr');
};
var verify = function (bridge, before, beforeOffset, after, afterOffset, failure, isRoot) {
return closest$1(after, 'td,th', isRoot).bind(function (afterCell) {
return closest$1(before, 'td,th', isRoot).map(function (beforeCell) {
if (!eq$1(afterCell, beforeCell)) {
return sharedOne$1(isRow, [
afterCell,
beforeCell
]).fold(function () {
return isOverlapping(bridge, beforeCell, afterCell) ? adt$6.success() : failure(beforeCell);
}, function (_sharedRow) {
return failure(beforeCell);
});
} else {
return eq$1(after, afterCell) && getEnd(afterCell) === afterOffset ? failure(beforeCell) : adt$6.none('in same cell');
}
});
}).getOr(adt$6.none('default'));
};
var cata$2 = function (subject, onNone, onSuccess, onFailedUp, onFailedDown) {
return subject.fold(onNone, onSuccess, onFailedUp, onFailedDown);
};
var BeforeAfter = __assign(__assign({}, adt$6), {
verify: verify,
cata: cata$2
});
var inParent = function (parent, children, element, index) {
return {
parent: parent,
children: children,
element: element,
index: index
};
};
var indexInParent = function (element) {
return parent(element).bind(function (parent) {
var children$1 = children(parent);
return indexOf(children$1, element).map(function (index) {
return inParent(parent, children$1, element, index);
});
});
};
var indexOf = function (elements, element) {
return findIndex(elements, curry(eq$1, element));
};
var isBr = function (elem) {
return name(elem) === 'br';
};
var gatherer = function (cand, gather, isRoot) {
return gather(cand, isRoot).bind(function (target) {
return isText(target) && get$4(target).trim().length === 0 ? gatherer(target, gather, isRoot) : Optional.some(target);
});
};
var handleBr = function (isRoot, element, direction) {
return direction.traverse(element).orThunk(function () {
return gatherer(element, direction.gather, isRoot);
}).map(direction.relative);
};
var findBr = function (element, offset) {
return child(element, offset).filter(isBr).orThunk(function () {
return child(element, offset - 1).filter(isBr);
});
};
var handleParent = function (isRoot, element, offset, direction) {
return findBr(element, offset).bind(function (br) {
return direction.traverse(br).fold(function () {
return gatherer(br, direction.gather, isRoot).map(direction.relative);
}, function (adjacent) {
return indexInParent(adjacent).map(function (info) {
return Situ.on(info.parent, info.index);
});
});
});
};
var tryBr = function (isRoot, element, offset, direction) {
var target = isBr(element) ? handleBr(isRoot, element, direction) : handleParent(isRoot, element, offset, direction);
return target.map(function (tgt) {
return {
start: tgt,
finish: tgt
};
});
};
var process = function (analysis) {
return BeforeAfter.cata(analysis, function (_message) {
return Optional.none();
}, function () {
return Optional.none();
}, function (cell) {
return Optional.some(point(cell, 0));
}, function (cell) {
return Optional.some(point(cell, getEnd(cell)));
});
};
var moveDown = function (caret, amount) {
return {
left: caret.left,
top: caret.top + amount,
right: caret.right,
bottom: caret.bottom + amount
};
};
var moveUp = function (caret, amount) {
return {
left: caret.left,
top: caret.top - amount,
right: caret.right,
bottom: caret.bottom - amount
};
};
var translate = function (caret, xDelta, yDelta) {
return {
left: caret.left + xDelta,
top: caret.top + yDelta,
right: caret.right + xDelta,
bottom: caret.bottom + yDelta
};
};
var getTop$1 = function (caret) {
return caret.top;
};
var getBottom = function (caret) {
return caret.bottom;
};
var getPartialBox = function (bridge, element, offset) {
if (offset >= 0 && offset < getEnd(element)) {
return bridge.getRangedRect(element, offset, element, offset + 1);
} else if (offset > 0) {
return bridge.getRangedRect(element, offset - 1, element, offset);
}
return Optional.none();
};
var toCaret = function (rect) {
return {
left: rect.left,
top: rect.top,
right: rect.right,
bottom: rect.bottom
};
};
var getElemBox = function (bridge, element) {
return Optional.some(bridge.getRect(element));
};
var getBoxAt = function (bridge, element, offset) {
if (isElement(element)) {
return getElemBox(bridge, element).map(toCaret);
} else if (isText(element)) {
return getPartialBox(bridge, element, offset).map(toCaret);
} else {
return Optional.none();
}
};
var getEntireBox = function (bridge, element) {
if (isElement(element)) {
return getElemBox(bridge, element).map(toCaret);
} else if (isText(element)) {
return bridge.getRangedRect(element, 0, element, getEnd(element)).map(toCaret);
} else {
return Optional.none();
}
};
var JUMP_SIZE = 5;
var NUM_RETRIES = 100;
var adt$7 = Adt.generate([
{ none: [] },
{ retry: ['caret'] }
]);
var isOutside = function (caret, box) {
return caret.left < box.left || Math.abs(box.right - caret.left) < 1 || caret.left > box.right;
};
var inOutsideBlock = function (bridge, element, caret) {
return closest(element, isBlock$1).fold(never, function (cell) {
return getEntireBox(bridge, cell).exists(function (box) {
return isOutside(caret, box);
});
});
};
var adjustDown = function (bridge, element, guessBox, original, caret) {
var lowerCaret = moveDown(caret, JUMP_SIZE);
if (Math.abs(guessBox.bottom - original.bottom) < 1) {
return adt$7.retry(lowerCaret);
} else if (guessBox.top > caret.bottom) {
return adt$7.retry(lowerCaret);
} else if (guessBox.top === caret.bottom) {
return adt$7.retry(moveDown(caret, 1));
} else {
return inOutsideBlock(bridge, element, caret) ? adt$7.retry(translate(lowerCaret, JUMP_SIZE, 0)) : adt$7.none();
}
};
var adjustUp = function (bridge, element, guessBox, original, caret) {
var higherCaret = moveUp(caret, JUMP_SIZE);
if (Math.abs(guessBox.top - original.top) < 1) {
return adt$7.retry(higherCaret);
} else if (guessBox.bottom < caret.top) {
return adt$7.retry(higherCaret);
} else if (guessBox.bottom === caret.top) {
return adt$7.retry(moveUp(caret, 1));
} else {
return inOutsideBlock(bridge, element, caret) ? adt$7.retry(translate(higherCaret, JUMP_SIZE, 0)) : adt$7.none();
}
};
var upMovement = {
point: getTop$1,
adjuster: adjustUp,
move: moveUp,
gather: before$4
};
var downMovement = {
point: getBottom,
adjuster: adjustDown,
move: moveDown,
gather: after$5
};
var isAtTable = function (bridge, x, y) {
return bridge.elementFromPoint(x, y).filter(function (elm) {
return name(elm) === 'table';
}).isSome();
};
var adjustForTable = function (bridge, movement, original, caret, numRetries) {
return adjustTil(bridge, movement, original, movement.move(caret, JUMP_SIZE), numRetries);
};
var adjustTil = function (bridge, movement, original, caret, numRetries) {
if (numRetries === 0) {
return Optional.some(caret);
}
if (isAtTable(bridge, caret.left, movement.point(caret))) {
return adjustForTable(bridge, movement, original, caret, numRetries - 1);
}
return bridge.situsFromPoint(caret.left, movement.point(caret)).bind(function (guess) {
return guess.start.fold(Optional.none, function (element) {
return getEntireBox(bridge, element).bind(function (guessBox) {
return movement.adjuster(bridge, element, guessBox, original, caret).fold(Optional.none, function (newCaret) {
return adjustTil(bridge, movement, original, newCaret, numRetries - 1);
});
}).orThunk(function () {
return Optional.some(caret);
});
}, Optional.none);
});
};
var ieTryDown = function (bridge, caret) {
return bridge.situsFromPoint(caret.left, caret.bottom + JUMP_SIZE);
};
var ieTryUp = function (bridge, caret) {
return bridge.situsFromPoint(caret.left, caret.top - JUMP_SIZE);
};
var checkScroll = function (movement, adjusted, bridge) {
if (movement.point(adjusted) > bridge.getInnerHeight()) {
return Optional.some(movement.point(adjusted) - bridge.getInnerHeight());
} else if (movement.point(adjusted) < 0) {
return Optional.some(-movement.point(adjusted));
} else {
return Optional.none();
}
};
var retry = function (movement, bridge, caret) {
var moved = movement.move(caret, JUMP_SIZE);
var adjusted = adjustTil(bridge, movement, caret, moved, NUM_RETRIES).getOr(moved);
return checkScroll(movement, adjusted, bridge).fold(function () {
return bridge.situsFromPoint(adjusted.left, movement.point(adjusted));
}, function (delta) {
bridge.scrollBy(0, delta);
return bridge.situsFromPoint(adjusted.left, movement.point(adjusted) - delta);
});
};
var Retries = {
tryUp: curry(retry, upMovement),
tryDown: curry(retry, downMovement),
ieTryUp: ieTryUp,
ieTryDown: ieTryDown,
getJumpSize: constant(JUMP_SIZE)
};
var MAX_RETRIES = 20;
var findSpot = function (bridge, isRoot, direction) {
return bridge.getSelection().bind(function (sel) {
return tryBr(isRoot, sel.finish, sel.foffset, direction).fold(function () {
return Optional.some(point(sel.finish, sel.foffset));
}, function (brNeighbour) {
var range = bridge.fromSitus(brNeighbour);
var analysis = BeforeAfter.verify(bridge, sel.finish, sel.foffset, range.finish, range.foffset, direction.failure, isRoot);
return process(analysis);
});
});
};
var scan$1 = function (bridge, isRoot, element, offset, direction, numRetries) {
if (numRetries === 0) {
return Optional.none();
}
return tryCursor(bridge, isRoot, element, offset, direction).bind(function (situs) {
var range = bridge.fromSitus(situs);
var analysis = BeforeAfter.verify(bridge, element, offset, range.finish, range.foffset, direction.failure, isRoot);
return BeforeAfter.cata(analysis, function () {
return Optional.none();
}, function () {
return Optional.some(situs);
}, function (cell) {
if (eq$1(element, cell) && offset === 0) {
return tryAgain(bridge, element, offset, moveUp, direction);
} else {
return scan$1(bridge, isRoot, cell, 0, direction, numRetries - 1);
}
}, function (cell) {
if (eq$1(element, cell) && offset === getEnd(cell)) {
return tryAgain(bridge, element, offset, moveDown, direction);
} else {
return scan$1(bridge, isRoot, cell, getEnd(cell), direction, numRetries - 1);
}
});
});
};
var tryAgain = function (bridge, element, offset, move, direction) {
return getBoxAt(bridge, element, offset).bind(function (box) {
return tryAt(bridge, direction, move(box, Retries.getJumpSize()));
});
};
var tryAt = function (bridge, direction, box) {
var browser = detect$3().browser;
if (browser.isChrome() || browser.isSafari() || browser.isFirefox() || browser.isEdge()) {
return direction.otherRetry(bridge, box);
} else if (browser.isIE()) {
return direction.ieRetry(bridge, box);
} else {
return Optional.none();
}
};
var tryCursor = function (bridge, isRoot, element, offset, direction) {
return getBoxAt(bridge, element, offset).bind(function (box) {
return tryAt(bridge, direction, box);
});
};
var handle$2 = function (bridge, isRoot, direction) {
return findSpot(bridge, isRoot, direction).bind(function (spot) {
return scan$1(bridge, isRoot, spot.element, spot.offset, direction, MAX_RETRIES).map(bridge.fromSitus);
});
};
var inSameTable = function (elem, table) {
return ancestor$2(elem, function (e) {
return parent(e).exists(function (p) {
return eq$1(p, table);
});
});
};
var simulate = function (bridge, isRoot, direction, initial, anchor) {
return closest$1(initial, 'td,th', isRoot).bind(function (start) {
return closest$1(start, 'table', isRoot).bind(function (table) {
if (!inSameTable(anchor, table)) {
return Optional.none();
}
return handle$2(bridge, isRoot, direction).bind(function (range) {
return closest$1(range.finish, 'td,th', isRoot).map(function (finish) {
return {
start: start,
finish: finish,
range: range
};
});
});
});
});
};
var navigate = function (bridge, isRoot, direction, initial, anchor, precheck) {
if (detect$3().browser.isIE()) {
return Optional.none();
} else {
return precheck(initial, isRoot).orThunk(function () {
return simulate(bridge, isRoot, direction, initial, anchor).map(function (info) {
var range = info.range;
return Response.create(Optional.some(makeSitus(range.start, range.soffset, range.finish, range.foffset)), true);
});
});
}
};
var firstUpCheck = function (initial, isRoot) {
return closest$1(initial, 'tr', isRoot).bind(function (startRow) {
return closest$1(startRow, 'table', isRoot).bind(function (table) {
var rows = descendants$1(table, 'tr');
if (eq$1(startRow, rows[0])) {
return seekLeft$1(table, function (element) {
return last$1(element).isSome();
}, isRoot).map(function (last) {
var lastOffset = getEnd(last);
return Response.create(Optional.some(makeSitus(last, lastOffset, last, lastOffset)), true);
});
} else {
return Optional.none();
}
});
});
};
var lastDownCheck = function (initial, isRoot) {
return closest$1(initial, 'tr', isRoot).bind(function (startRow) {
return closest$1(startRow, 'table', isRoot).bind(function (table) {
var rows = descendants$1(table, 'tr');
if (eq$1(startRow, rows[rows.length - 1])) {
return seekRight$1(table, function (element) {
return first(element).isSome();
}, isRoot).map(function (first) {
return Response.create(Optional.some(makeSitus(first, 0, first, 0)), true);
});
} else {
return Optional.none();
}
});
});
};
var select = function (bridge, container, isRoot, direction, initial, anchor, selectRange) {
return simulate(bridge, isRoot, direction, initial, anchor).bind(function (info) {
return detect$6(container, isRoot, info.start, info.finish, selectRange);
});
};
var value$1 = function () {
var subject = Cell(Optional.none());
var clear = function () {
return subject.set(Optional.none());
};
var set = function (s) {
return subject.set(Optional.some(s));
};
var isSet = function () {
return subject.get().isSome();
};
var on = function (f) {
return subject.get().each(f);
};
return {
clear: clear,
set: set,
isSet: isSet,
on: on
};
};
var findCell = function (target, isRoot) {
return closest$1(target, 'td,th', isRoot);
};
var MouseSelection = function (bridge, container, isRoot, annotations) {
var cursor = value$1();
var clearstate = cursor.clear;
var applySelection = function (event) {
cursor.on(function (start) {
annotations.clearBeforeUpdate(container);
findCell(event.target, isRoot).each(function (finish) {
identify(start, finish, isRoot).each(function (cellSel) {
var boxes = cellSel.boxes.getOr([]);
if (boxes.length > 1 || boxes.length === 1 && !eq$1(start, finish)) {
annotations.selectRange(container, boxes, cellSel.start, cellSel.finish);
bridge.selectContents(finish);
}
});
});
});
};
var mousedown = function (event) {
annotations.clear(container);
findCell(event.target, isRoot).each(cursor.set);
};
var mouseover = function (event) {
applySelection(event);
};
var mouseup = function (event) {
applySelection(event);
clearstate();
};
return {
clearstate: clearstate,
mousedown: mousedown,
mouseover: mouseover,
mouseup: mouseup
};
};
var down = {
traverse: nextSibling,
gather: after$5,
relative: Situ.before,
otherRetry: Retries.tryDown,
ieRetry: Retries.ieTryDown,
failure: BeforeAfter.failedDown
};
var up = {
traverse: prevSibling,
gather: before$4,
relative: Situ.before,
otherRetry: Retries.tryUp,
ieRetry: Retries.ieTryUp,
failure: BeforeAfter.failedUp
};
var isKey = function (key) {
return function (keycode) {
return keycode === key;
};
};
var isUp = isKey(38);
var isDown = isKey(40);
var isNavigation = function (keycode) {
return keycode >= 37 && keycode <= 40;
};
var ltr$2 = {
isBackward: isKey(37),
isForward: isKey(39)
};
var rtl$2 = {
isBackward: isKey(39),
isForward: isKey(37)
};
var get$d = function (_DOC) {
var doc = _DOC !== undefined ? _DOC.dom : document;
var x = doc.body.scrollLeft || doc.documentElement.scrollLeft;
var y = doc.body.scrollTop || doc.documentElement.scrollTop;
return SugarPosition(x, y);
};
var by = function (x, y, _DOC) {
var doc = _DOC !== undefined ? _DOC.dom : document;
var win = doc.defaultView;
if (win) {
win.scrollBy(x, y);
}
};
var WindowBridge = function (win) {
var elementFromPoint = function (x, y) {
return SugarElement.fromPoint(SugarElement.fromDom(win.document), x, y);
};
var getRect = function (element) {
return element.dom.getBoundingClientRect();
};
var getRangedRect = function (start, soffset, finish, foffset) {
var sel = SimSelection.exact(start, soffset, finish, foffset);
return getFirstRect$1(win, sel);
};
var getSelection = function () {
return get$c(win).map(function (exactAdt) {
return convertToRange(win, exactAdt);
});
};
var fromSitus = function (situs) {
var relative = SimSelection.relative(situs.start, situs.finish);
return convertToRange(win, relative);
};
var situsFromPoint = function (x, y) {
return getAtPoint(win, x, y).map(function (exact) {
return Situs.create(exact.start, exact.soffset, exact.finish, exact.foffset);
});
};
var clearSelection = function () {
clear(win);
};
var collapseSelection = function (toStart) {
if (toStart === void 0) {
toStart = false;
}
get$c(win).each(function (sel) {
return sel.fold(function (rng) {
return rng.collapse(toStart);
}, function (startSitu, finishSitu) {
var situ = toStart ? startSitu : finishSitu;
setRelative(win, situ, situ);
}, function (start, soffset, finish, foffset) {
var node = toStart ? start : finish;
var offset = toStart ? soffset : foffset;
setExact(win, node, offset, node, offset);
});
});
};
var selectContents = function (element) {
setToElement(win, element);
};
var setSelection = function (sel) {
setExact(win, sel.start, sel.soffset, sel.finish, sel.foffset);
};
var setRelativeSelection = function (start, finish) {
setRelative(win, start, finish);
};
var getInnerHeight = function () {
return win.innerHeight;
};
var getScrollY = function () {
var pos = get$d(SugarElement.fromDom(win.document));
return pos.top;
};
var scrollBy = function (x, y) {
by(x, y, SugarElement.fromDom(win.document));
};
return {
elementFromPoint: elementFromPoint,
getRect: getRect,
getRangedRect: getRangedRect,
getSelection: getSelection,
fromSitus: fromSitus,
situsFromPoint: situsFromPoint,
clearSelection: clearSelection,
collapseSelection: collapseSelection,
setSelection: setSelection,
setRelativeSelection: setRelativeSelection,
selectContents: selectContents,
getInnerHeight: getInnerHeight,
getScrollY: getScrollY,
scrollBy: scrollBy
};
};
var rc = function (rows, cols) {
return {
rows: rows,
cols: cols
};
};
var mouse = function (win, container, isRoot, annotations) {
var bridge = WindowBridge(win);
var handlers = MouseSelection(bridge, container, isRoot, annotations);
return {
clearstate: handlers.clearstate,
mousedown: handlers.mousedown,
mouseover: handlers.mouseover,
mouseup: handlers.mouseup
};
};
var keyboard = function (win, container, isRoot, annotations) {
var bridge = WindowBridge(win);
var clearToNavigate = function () {
annotations.clear(container);
return Optional.none();
};
var keydown = function (event, start, soffset, finish, foffset, direction) {
var realEvent = event.raw;
var keycode = realEvent.which;
var shiftKey = realEvent.shiftKey === true;
var handler = retrieve(container, annotations.selectedSelector).fold(function () {
if (isDown(keycode) && shiftKey) {
return curry(select, bridge, container, isRoot, down, finish, start, annotations.selectRange);
} else if (isUp(keycode) && shiftKey) {
return curry(select, bridge, container, isRoot, up, finish, start, annotations.selectRange);
} else if (isDown(keycode)) {
return curry(navigate, bridge, isRoot, down, finish, start, lastDownCheck);
} else if (isUp(keycode)) {
return curry(navigate, bridge, isRoot, up, finish, start, firstUpCheck);
} else {
return Optional.none;
}
}, function (selected) {
var update$1 = function (attempts) {
return function () {
var navigation = findMap(attempts, function (delta) {
return update(delta.rows, delta.cols, container, selected, annotations);
});
return navigation.fold(function () {
return getEdges(container, annotations.firstSelectedSelector, annotations.lastSelectedSelector).map(function (edges) {
var relative = isDown(keycode) || direction.isForward(keycode) ? Situ.after : Situ.before;
bridge.setRelativeSelection(Situ.on(edges.first, 0), relative(edges.table));
annotations.clear(container);
return Response.create(Optional.none(), true);
});
}, function (_) {
return Optional.some(Response.create(Optional.none(), true));
});
};
};
if (isDown(keycode) && shiftKey) {
return update$1([rc(+1, 0)]);
} else if (isUp(keycode) && shiftKey) {
return update$1([rc(-1, 0)]);
} else if (direction.isBackward(keycode) && shiftKey) {
return update$1([
rc(0, -1),
rc(-1, 0)
]);
} else if (direction.isForward(keycode) && shiftKey) {
return update$1([
rc(0, +1),
rc(+1, 0)
]);
} else if (isNavigation(keycode) && shiftKey === false) {
return clearToNavigate;
} else {
return Optional.none;
}
});
return handler();
};
var keyup = function (event, start, soffset, finish, foffset) {
return retrieve(container, annotations.selectedSelector).fold(function () {
var realEvent = event.raw;
var keycode = realEvent.which;
var shiftKey = realEvent.shiftKey === true;
if (shiftKey === false) {
return Optional.none();
}
if (isNavigation(keycode)) {
return sync(container, isRoot, start, soffset, finish, foffset, annotations.selectRange);
} else {
return Optional.none();
}
}, Optional.none);
};
return {
keydown: keydown,
keyup: keyup
};
};
var external = function (win, container, isRoot, annotations) {
var bridge = WindowBridge(win);
return function (start, finish) {
annotations.clearBeforeUpdate(container);
identify(start, finish, isRoot).each(function (cellSel) {
var boxes = cellSel.boxes.getOr([]);
annotations.selectRange(container, boxes, cellSel.start, cellSel.finish);
bridge.selectContents(finish);
bridge.collapseSelection();
});
};
};
var remove$7 = function (element, classes) {
each(classes, function (x) {
remove$5(element, x);
});
};
var addClass = function (clazz) {
return function (element) {
add$3(element, clazz);
};
};
var removeClasses = function (classes) {
return function (element) {
remove$7(element, classes);
};
};
var byClass = function (ephemera) {
var addSelectionClass = addClass(ephemera.selected);
var removeSelectionClasses = removeClasses([
ephemera.selected,
ephemera.lastSelected,
ephemera.firstSelected
]);
var clear = function (container) {
var sels = descendants$1(container, ephemera.selectedSelector);
each(sels, removeSelectionClasses);
};
var selectRange = function (container, cells, start, finish) {
clear(container);
each(cells, addSelectionClass);
add$3(start, ephemera.firstSelected);
add$3(finish, ephemera.lastSelected);
};
return {
clearBeforeUpdate: clear,
clear: clear,
selectRange: selectRange,
selectedSelector: ephemera.selectedSelector,
firstSelectedSelector: ephemera.firstSelectedSelector,
lastSelectedSelector: ephemera.lastSelectedSelector
};
};
var byAttr = function (ephemera, onSelection, onClear) {
var removeSelectionAttributes = function (element) {
remove(element, ephemera.selected);
remove(element, ephemera.firstSelected);
remove(element, ephemera.lastSelected);
};
var addSelectionAttribute = function (element) {
set(element, ephemera.selected, '1');
};
var clear = function (container) {
clearBeforeUpdate(container);
onClear();
};
var clearBeforeUpdate = function (container) {
var sels = descendants$1(container, ephemera.selectedSelector);
each(sels, removeSelectionAttributes);
};
var selectRange = function (container, cells, start, finish) {
clear(container);
each(cells, addSelectionAttribute);
set(start, ephemera.firstSelected, '1');
set(finish, ephemera.lastSelected, '1');
onSelection(cells, start, finish);
};
return {
clearBeforeUpdate: clearBeforeUpdate,
clear: clear,
selectRange: selectRange,
selectedSelector: ephemera.selectedSelector,
firstSelectedSelector: ephemera.firstSelectedSelector,
lastSelectedSelector: ephemera.lastSelectedSelector
};
};
var SelectionAnnotation = {
byClass: byClass,
byAttr: byAttr
};
var getUpOrLeftCells = function (grid, selectedCells, generators) {
var upGrid = grid.slice(0, selectedCells[selectedCells.length - 1].row + 1);
var upDetails = toDetailList(upGrid, generators);
return bind(upDetails, function (detail) {
var slicedCells = detail.cells.slice(0, selectedCells[selectedCells.length - 1].column + 1);
return map(slicedCells, function (cell) {
return cell.element;
});
});
};
var getDownOrRightCells = function (grid, selectedCells, generators) {
var downGrid = grid.slice(selectedCells[0].row + selectedCells[0].rowspan - 1, grid.length);
var downDetails = toDetailList(downGrid, generators);
return bind(downDetails, function (detail) {
var slicedCells = detail.cells.slice(selectedCells[0].column + selectedCells[0].colspan - 1, detail.cells.length);
return map(slicedCells, function (cell) {
return cell.element;
});
});
};
var getOtherCells = function (table, target, generators) {
var warehouse = Warehouse.fromTable(table);
var details = onCells(warehouse, target);
return details.map(function (selectedCells) {
var grid = toGrid(warehouse, generators, false);
var upOrLeftCells = getUpOrLeftCells(grid, selectedCells, generators);
var downOrRightCells = getDownOrRightCells(grid, selectedCells, generators);
return {
upOrLeftCells: upOrLeftCells,
downOrRightCells: downOrRightCells
};
});
};
var hasInternalTarget = function (e) {
return has$1(SugarElement.fromDom(e.target), 'ephox-snooker-resizer-bar') === false;
};
function CellSelection (editor, lazyResize, selectionTargets) {
var onSelection = function (cells, start, finish) {
selectionTargets.targets().each(function (targets) {
var tableOpt = table(start);
tableOpt.each(function (table) {
var cloneFormats = getCloneElements(editor);
var generators = cellOperations(noop, SugarElement.fromDom(editor.getDoc()), cloneFormats);
var otherCells = getOtherCells(table, targets, generators);
fireTableSelectionChange(editor, cells, start, finish, otherCells);
});
});
};
var onClear = function () {
return fireTableSelectionClear(editor);
};
var annotations = SelectionAnnotation.byAttr(ephemera, onSelection, onClear);
editor.on('init', function (_e) {
var win = editor.getWin();
var body = getBody$1(editor);
var isRoot = getIsRoot(editor);
var syncSelection = function () {
var sel = editor.selection;
var start = SugarElement.fromDom(sel.getStart());
var end = SugarElement.fromDom(sel.getEnd());
var shared = sharedOne$1(table, [
start,
end
]);
shared.fold(function () {
return annotations.clear(body);
}, noop);
};
var mouseHandlers = mouse(win, body, isRoot, annotations);
var keyHandlers = keyboard(win, body, isRoot, annotations);
var external$1 = external(win, body, isRoot, annotations);
var hasShiftKey = function (event) {
return event.raw.shiftKey === true;
};
editor.on('TableSelectorChange', function (e) {
return external$1(e.start, e.finish);
});
var handleResponse = function (event, response) {
if (!hasShiftKey(event)) {
return;
}
if (response.kill) {
event.kill();
}
response.selection.each(function (ns) {
var relative = SimSelection.relative(ns.start, ns.finish);
var rng = asLtrRange(win, relative);
editor.selection.setRng(rng);
});
};
var keyup = function (event) {
var wrappedEvent = fromRawEvent$1(event);
if (wrappedEvent.raw.shiftKey && isNavigation(wrappedEvent.raw.which)) {
var rng = editor.selection.getRng();
var start = SugarElement.fromDom(rng.startContainer);
var end = SugarElement.fromDom(rng.endContainer);
keyHandlers.keyup(wrappedEvent, start, rng.startOffset, end, rng.endOffset).each(function (response) {
handleResponse(wrappedEvent, response);
});
}
};
var keydown = function (event) {
var wrappedEvent = fromRawEvent$1(event);
lazyResize().each(function (resize) {
return resize.hideBars();
});
var rng = editor.selection.getRng();
var start = SugarElement.fromDom(rng.startContainer);
var end = SugarElement.fromDom(rng.endContainer);
var direction = onDirection(ltr$2, rtl$2)(SugarElement.fromDom(editor.selection.getStart()));
keyHandlers.keydown(wrappedEvent, start, rng.startOffset, end, rng.endOffset, direction).each(function (response) {
handleResponse(wrappedEvent, response);
});
lazyResize().each(function (resize) {
return resize.showBars();
});
};
var isLeftMouse = function (raw) {
return raw.button === 0;
};
var isLeftButtonPressed = function (raw) {
if (raw.buttons === undefined) {
return true;
}
if (global$2.browser.isEdge() && raw.buttons === 0) {
return true;
}
return (raw.buttons & 1) !== 0;
};
var dragStart = function (_e) {
mouseHandlers.clearstate();
};
var mouseDown = function (e) {
if (isLeftMouse(e) && hasInternalTarget(e)) {
mouseHandlers.mousedown(fromRawEvent$1(e));
}
};
var mouseOver = function (e) {
if (isLeftButtonPressed(e) && hasInternalTarget(e)) {
mouseHandlers.mouseover(fromRawEvent$1(e));
}
};
var mouseUp = function (e) {
if (isLeftMouse(e) && hasInternalTarget(e)) {
mouseHandlers.mouseup(fromRawEvent$1(e));
}
};
var getDoubleTap = function () {
var lastTarget = Cell(SugarElement.fromDom(body));
var lastTimeStamp = Cell(0);
var touchEnd = function (t) {
var target = SugarElement.fromDom(t.target);
if (name(target) === 'td' || name(target) === 'th') {
var lT = lastTarget.get();
var lTS = lastTimeStamp.get();
if (eq$1(lT, target) && t.timeStamp - lTS < 300) {
t.preventDefault();
external$1(target, target);
}
}
lastTarget.set(target);
lastTimeStamp.set(t.timeStamp);
};
return { touchEnd: touchEnd };
};
var doubleTap = getDoubleTap();
editor.on('dragstart', dragStart);
editor.on('mousedown', mouseDown);
editor.on('mouseover', mouseOver);
editor.on('mouseup', mouseUp);
editor.on('touchend', doubleTap.touchEnd);
editor.on('keyup', keyup);
editor.on('keydown', keydown);
editor.on('NodeChange', syncSelection);
});
return { clear: annotations.clear };
}
var getSelectionTargets = function (editor, selections) {
var targets = Cell(Optional.none());
var changeHandlers = Cell([]);
var selectionDetails = Optional.none();
var isCaption = isTag('caption');
var isDisabledForSelection = function (key) {
return selectionDetails.forall(function (details) {
return !details[key];
});
};
var findTargets = function () {
return getSelectionStartCellOrCaption(getSelectionStart(editor), getIsRoot(editor)).bind(function (cellOrCaption) {
var table$1 = table(cellOrCaption);
return table$1.map(function (table) {
if (isCaption(cellOrCaption)) {
return noMenu(cellOrCaption);
} else {
return forMenu(selections, table, cellOrCaption);
}
});
});
};
var getExtractedDetails = function (targets) {
var tableOpt = table(targets.element);
return tableOpt.map(function (table) {
var warehouse = Warehouse.fromTable(table);
var selectedCells = onCells(warehouse, targets).getOr([]);
var locked = foldl(selectedCells, function (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: locked
};
});
};
var resetTargets = function () {
targets.set(cached(findTargets)());
selectionDetails = targets.get().bind(getExtractedDetails);
each(changeHandlers.get(), function (handler) {
return handler();
});
};
var onSetup = function (api, isDisabled) {
var handler = function () {
return targets.get().fold(function () {
api.setDisabled(true);
}, function (targets) {
api.setDisabled(isDisabled(targets));
});
};
handler();
changeHandlers.set(changeHandlers.get().concat([handler]));
return function () {
changeHandlers.set(filter(changeHandlers.get(), function (h) {
return h !== handler;
}));
};
};
var isDisabledFromLocked = function (lockedDisable) {
return selectionDetails.exists(function (details) {
return details.locked[lockedDisable];
});
};
var onSetupTable = function (api) {
return onSetup(api, function (_) {
return false;
});
};
var onSetupCellOrRow = function (api) {
return onSetup(api, function (targets) {
return isCaption(targets.element);
});
};
var onSetupColumn = function (lockedDisable) {
return function (api) {
return onSetup(api, function (targets) {
return isCaption(targets.element) || isDisabledFromLocked(lockedDisable);
});
};
};
var onSetupPasteable = function (getClipboardData) {
return function (api) {
return onSetup(api, function (targets) {
return isCaption(targets.element) || getClipboardData().isNone();
});
};
};
var onSetupPasteableColumn = function (getClipboardData, lockedDisable) {
return function (api) {
return onSetup(api, function (targets) {
return isCaption(targets.element) || getClipboardData().isNone() || isDisabledFromLocked(lockedDisable);
});
};
};
var onSetupMergeable = function (api) {
return onSetup(api, function (_targets) {
return isDisabledForSelection('mergeable');
});
};
var onSetupUnmergeable = function (api) {
return onSetup(api, function (_targets) {
return isDisabledForSelection('unmergeable');
});
};
editor.on('NodeChange ExecCommand TableSelectorChange', resetTargets);
return {
onSetupTable: onSetupTable,
onSetupCellOrRow: onSetupCellOrRow,
onSetupColumn: onSetupColumn,
onSetupPasteable: onSetupPasteable,
onSetupPasteableColumn: onSetupPasteableColumn,
onSetupMergeable: onSetupMergeable,
onSetupUnmergeable: onSetupUnmergeable,
resetTargets: resetTargets,
targets: function () {
return targets.get();
}
};
};
var addButtons = function (editor, selectionTargets, clipboard) {
editor.ui.registry.addMenuButton('table', {
tooltip: 'Table',
icon: 'table',
fetch: function (callback) {
return callback('inserttable | cell row column | advtablesort | tableprops deletetable');
}
});
var cmd = function (command) {
return function () {
return editor.execCommand(command);
};
};
editor.ui.registry.addButton('tableprops', {
tooltip: 'Table properties',
onAction: cmd('mceTableProps'),
icon: 'table',
onSetup: selectionTargets.onSetupTable
});
editor.ui.registry.addButton('tabledelete', {
tooltip: 'Delete table',
onAction: cmd('mceTableDelete'),
icon: 'table-delete-table',
onSetup: selectionTargets.onSetupTable
});
editor.ui.registry.addButton('tablecellprops', {
tooltip: 'Cell properties',
onAction: cmd('mceTableCellProps'),
icon: 'table-cell-properties',
onSetup: selectionTargets.onSetupCellOrRow
});
editor.ui.registry.addButton('tablemergecells', {
tooltip: 'Merge cells',
onAction: cmd('mceTableMergeCells'),
icon: 'table-merge-cells',
onSetup: selectionTargets.onSetupMergeable
});
editor.ui.registry.addButton('tablesplitcells', {
tooltip: 'Split cell',
onAction: cmd('mceTableSplitCells'),
icon: 'table-split-cells',
onSetup: selectionTargets.onSetupUnmergeable
});
editor.ui.registry.addButton('tableinsertrowbefore', {
tooltip: 'Insert row before',
onAction: cmd('mceTableInsertRowBefore'),
icon: 'table-insert-row-above',
onSetup: selectionTargets.onSetupCellOrRow
});
editor.ui.registry.addButton('tableinsertrowafter', {
tooltip: 'Insert row after',
onAction: cmd('mceTableInsertRowAfter'),
icon: 'table-insert-row-after',
onSetup: selectionTargets.onSetupCellOrRow
});
editor.ui.registry.addButton('tabledeleterow', {
tooltip: 'Delete row',
onAction: cmd('mceTableDeleteRow'),
icon: 'table-delete-row',
onSetup: selectionTargets.onSetupCellOrRow
});
editor.ui.registry.addButton('tablerowprops', {
tooltip: 'Row properties',
onAction: cmd('mceTableRowProps'),
icon: 'table-row-properties',
onSetup: selectionTargets.onSetupCellOrRow
});
editor.ui.registry.addButton('tableinsertcolbefore', {
tooltip: 'Insert column before',
onAction: cmd('mceTableInsertColBefore'),
icon: 'table-insert-column-before',
onSetup: selectionTargets.onSetupColumn('onFirst')
});
editor.ui.registry.addButton('tableinsertcolafter', {
tooltip: 'Insert column after',
onAction: cmd('mceTableInsertColAfter'),
icon: 'table-insert-column-after',
onSetup: selectionTargets.onSetupColumn('onLast')
});
editor.ui.registry.addButton('tabledeletecol', {
tooltip: 'Delete column',
onAction: cmd('mceTableDeleteCol'),
icon: 'table-delete-column',
onSetup: selectionTargets.onSetupColumn('onAny')
});
editor.ui.registry.addButton('tablecutrow', {
tooltip: 'Cut row',
icon: 'cut-row',
onAction: cmd('mceTableCutRow'),
onSetup: selectionTargets.onSetupCellOrRow
});
editor.ui.registry.addButton('tablecopyrow', {
tooltip: 'Copy row',
icon: 'duplicate-row',
onAction: cmd('mceTableCopyRow'),
onSetup: selectionTargets.onSetupCellOrRow
});
editor.ui.registry.addButton('tablepasterowbefore', {
tooltip: 'Paste row before',
icon: 'paste-row-before',
onAction: cmd('mceTablePasteRowBefore'),
onSetup: selectionTargets.onSetupPasteable(clipboard.getRows)
});
editor.ui.registry.addButton('tablepasterowafter', {
tooltip: 'Paste row after',
icon: 'paste-row-after',
onAction: cmd('mceTablePasteRowAfter'),
onSetup: selectionTargets.onSetupPasteable(clipboard.getRows)
});
editor.ui.registry.addButton('tablecutcol', {
tooltip: 'Cut column',
icon: 'cut-column',
onAction: cmd('mceTableCutCol'),
onSetup: selectionTargets.onSetupColumn('onAny')
});
editor.ui.registry.addButton('tablecopycol', {
tooltip: 'Copy column',
icon: 'duplicate-column',
onAction: cmd('mceTableCopyCol'),
onSetup: selectionTargets.onSetupColumn('onAny')
});
editor.ui.registry.addButton('tablepastecolbefore', {
tooltip: 'Paste column before',
icon: 'paste-column-before',
onAction: cmd('mceTablePasteColBefore'),
onSetup: selectionTargets.onSetupPasteableColumn(clipboard.getColumns, 'onFirst')
});
editor.ui.registry.addButton('tablepastecolafter', {
tooltip: 'Paste column after',
icon: 'paste-column-after',
onAction: cmd('mceTablePasteColAfter'),
onSetup: selectionTargets.onSetupPasteableColumn(clipboard.getColumns, 'onLast')
});
editor.ui.registry.addButton('tableinsertdialog', {
tooltip: 'Insert table',
onAction: cmd('mceInsertTable'),
icon: 'table'
});
};
var addToolbars = function (editor) {
var isTable = function (table) {
return editor.dom.is(table, 'table') && editor.getBody().contains(table);
};
var toolbar = getToolbar(editor);
if (toolbar.length > 0) {
editor.ui.registry.addContextToolbar('table', {
predicate: isTable,
items: toolbar,
scope: 'node',
position: 'node'
});
}
};
var addMenuItems = function (editor, selectionTargets, clipboard) {
var cmd = function (command) {
return function () {
return editor.execCommand(command);
};
};
var insertTableAction = function (data) {
editor.execCommand('mceInsertTable', false, {
rows: data.numRows,
columns: data.numColumns
});
};
var tableProperties = {
text: 'Table properties',
onSetup: selectionTargets.onSetupTable,
onAction: cmd('mceTableProps')
};
var deleteTable = {
text: 'Delete table',
icon: 'table-delete-table',
onSetup: selectionTargets.onSetupTable,
onAction: cmd('mceTableDelete')
};
editor.ui.registry.addMenuItem('tableinsertrowbefore', {
text: 'Insert row before',
icon: 'table-insert-row-above',
onAction: cmd('mceTableInsertRowBefore'),
onSetup: selectionTargets.onSetupCellOrRow
});
editor.ui.registry.addMenuItem('tableinsertrowafter', {
text: 'Insert row after',
icon: 'table-insert-row-after',
onAction: cmd('mceTableInsertRowAfter'),
onSetup: selectionTargets.onSetupCellOrRow
});
editor.ui.registry.addMenuItem('tabledeleterow', {
text: 'Delete row',
icon: 'table-delete-row',
onAction: cmd('mceTableDeleteRow'),
onSetup: selectionTargets.onSetupCellOrRow
});
editor.ui.registry.addMenuItem('tablerowprops', {
text: 'Row properties',
icon: 'table-row-properties',
onAction: cmd('mceTableRowProps'),
onSetup: selectionTargets.onSetupCellOrRow
});
editor.ui.registry.addMenuItem('tablecutrow', {
text: 'Cut row',
icon: 'cut-row',
onAction: cmd('mceTableCutRow'),
onSetup: selectionTargets.onSetupCellOrRow
});
editor.ui.registry.addMenuItem('tablecopyrow', {
text: 'Copy row',
icon: 'duplicate-row',
onAction: cmd('mceTableCopyRow'),
onSetup: selectionTargets.onSetupCellOrRow
});
editor.ui.registry.addMenuItem('tablepasterowbefore', {
text: 'Paste row before',
icon: 'paste-row-before',
onAction: cmd('mceTablePasteRowBefore'),
onSetup: selectionTargets.onSetupPasteable(clipboard.getRows)
});
editor.ui.registry.addMenuItem('tablepasterowafter', {
text: 'Paste row after',
icon: 'paste-row-after',
onAction: cmd('mceTablePasteRowAfter'),
onSetup: selectionTargets.onSetupPasteable(clipboard.getRows)
});
var row = {
type: 'nestedmenuitem',
text: 'Row',
getSubmenuItems: function () {
return 'tableinsertrowbefore tableinsertrowafter tabledeleterow tablerowprops | tablecutrow tablecopyrow tablepasterowbefore tablepasterowafter';
}
};
editor.ui.registry.addMenuItem('tableinsertcolumnbefore', {
text: 'Insert column before',
icon: 'table-insert-column-before',
onAction: cmd('mceTableInsertColBefore'),
onSetup: selectionTargets.onSetupColumn('onFirst')
});
editor.ui.registry.addMenuItem('tableinsertcolumnafter', {
text: 'Insert column after',
icon: 'table-insert-column-after',
onAction: cmd('mceTableInsertColAfter'),
onSetup: selectionTargets.onSetupColumn('onLast')
});
editor.ui.registry.addMenuItem('tabledeletecolumn', {
text: 'Delete column',
icon: 'table-delete-column',
onAction: cmd('mceTableDeleteCol'),
onSetup: selectionTargets.onSetupColumn('onAny')
});
editor.ui.registry.addMenuItem('tablecutcolumn', {
text: 'Cut column',
icon: 'cut-column',
onAction: cmd('mceTableCutCol'),
onSetup: selectionTargets.onSetupColumn('onAny')
});
editor.ui.registry.addMenuItem('tablecopycolumn', {
text: 'Copy column',
icon: 'duplicate-column',
onAction: cmd('mceTableCopyCol'),
onSetup: selectionTargets.onSetupColumn('onAny')
});
editor.ui.registry.addMenuItem('tablepastecolumnbefore', {
text: 'Paste column before',
icon: 'paste-column-before',
onAction: cmd('mceTablePasteColBefore'),
onSetup: selectionTargets.onSetupPasteableColumn(clipboard.getColumns, 'onFirst')
});
editor.ui.registry.addMenuItem('tablepastecolumnafter', {
text: 'Paste column after',
icon: 'paste-column-after',
onAction: cmd('mceTablePasteColAfter'),
onSetup: selectionTargets.onSetupPasteableColumn(clipboard.getColumns, 'onLast')
});
var column = {
type: 'nestedmenuitem',
text: 'Column',
getSubmenuItems: function () {
return 'tableinsertcolumnbefore tableinsertcolumnafter tabledeletecolumn | tablecutcolumn tablecopycolumn tablepastecolumnbefore tablepastecolumnafter';
}
};
editor.ui.registry.addMenuItem('tablecellprops', {
text: 'Cell properties',
icon: 'table-cell-properties',
onAction: cmd('mceTableCellProps'),
onSetup: selectionTargets.onSetupCellOrRow
});
editor.ui.registry.addMenuItem('tablemergecells', {
text: 'Merge cells',
icon: 'table-merge-cells',
onAction: cmd('mceTableMergeCells'),
onSetup: selectionTargets.onSetupMergeable
});
editor.ui.registry.addMenuItem('tablesplitcells', {
text: 'Split cell',
icon: 'table-split-cells',
onAction: cmd('mceTableSplitCells'),
onSetup: selectionTargets.onSetupUnmergeable
});
var cell = {
type: 'nestedmenuitem',
text: 'Cell',
getSubmenuItems: function () {
return 'tablecellprops tablemergecells tablesplitcells';
}
};
if (hasTableGrid(editor) === false) {
editor.ui.registry.addMenuItem('inserttable', {
text: 'Table',
icon: 'table',
onAction: cmd('mceInsertTable')
});
} else {
editor.ui.registry.addNestedMenuItem('inserttable', {
text: 'Table',
icon: 'table',
getSubmenuItems: function () {
return [{
type: 'fancymenuitem',
fancytype: 'inserttable',
onAction: insertTableAction
}];
}
});
}
editor.ui.registry.addMenuItem('inserttabledialog', {
text: 'Insert table',
icon: 'table',
onAction: cmd('mceInsertTable')
});
editor.ui.registry.addMenuItem('tableprops', tableProperties);
editor.ui.registry.addMenuItem('deletetable', deleteTable);
editor.ui.registry.addNestedMenuItem('row', row);
editor.ui.registry.addNestedMenuItem('column', column);
editor.ui.registry.addNestedMenuItem('cell', cell);
editor.ui.registry.addContextMenu('table', {
update: function () {
selectionTargets.resetTargets();
return selectionTargets.targets().fold(function () {
return '';
}, function (targets) {
if (name(targets.element) === 'caption') {
return 'tableprops deletetable';
} else {
return 'cell row column | advtablesort | tableprops deletetable';
}
});
}
});
};
var Plugin = function (editor) {
var selections = Selections(function () {
return getBody$1(editor);
}, function () {
return getSelectionStartCellOrCaption(getSelectionStart(editor));
}, ephemera.selectedSelector);
var selectionTargets = getSelectionTargets(editor, selections);
var resizeHandler = getResizeHandler(editor);
var cellSelection = CellSelection(editor, resizeHandler.lazyResize, selectionTargets);
var actions = TableActions(editor, resizeHandler.lazyWire, selections);
var clipboard = Clipboard();
registerCommands(editor, actions, cellSelection, selections, clipboard);
registerQueryCommands(editor, actions, selections);
registerEvents(editor, selections, actions, cellSelection);
addMenuItems(editor, selectionTargets, clipboard);
addButtons(editor, selectionTargets, clipboard);
addToolbars(editor);
editor.on('PreInit', function () {
editor.serializer.addTempAttr(ephemera.firstSelected);
editor.serializer.addTempAttr(ephemera.lastSelected);
registerFormats(editor);
});
if (hasTabNavigation(editor)) {
editor.on('keydown', function (e) {
handle$1(e, editor, cellSelection);
});
}
editor.on('remove', function () {
resizeHandler.destroy();
});
return getApi(editor, clipboard, resizeHandler, selectionTargets);
};
function Plugin$1 () {
global.add('table', Plugin);
}
Plugin$1();
}());
|
// Download the Node helper library from twilio.com/docs/node/install
// These consts are your accountSid and authToken from https://www.twilio.com/console
// To set up environmental variables, see http://twil.io/secure
const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;
const client = require('twilio')(accountSid, authToken);
client.wireless.sims.list().then(response => {
console.log(response);
});
|
const fs = require('fs');
const path = require('path');
const fetch = require('node-fetch');
const outDir = __dirname;
const includeList = [
"cyclosm",
"osmbe",
"osmbe-fr",
"osmbe-nl",
"osmfr-basque",
"osmfr-breton",
"osmfr-occitan",
"OpenStreetMap-turistautak",
"hu-hillshade",
"Israel_Hiking",
"Israel_MTB",
"mtbmap-no",
"Freemap.sk-Car",
"Freemap.sk-Hiking",
"Freemap.sk-Cyclo",
"opencylemap",
"standard",
"HDM_HOT",
"osmfr",
"osm-mapnik-german_style",
"OpenTopoMap",
"osm-cambodia_laos_thailand_vietnam-bilingual",
"Waymarked_Trails-Hiking",
"Waymarked_Trails-Cycling",
"Waymarked_Trails-MTB",
"wikimedia-map",
"openpt_map"
];
function extract(layersJosm) {
for (let i = 0; i < layersJosm.features.length; i++) {
let layer = layersJosm.features[i];
let props = layer.properties;
let id = props.id;
if (includeList.includes(id)) {
//console.log(`${id}, ${props.name}, ${props.url}`);
props.dataSource = 'JOSM';
const outFileName = path.join(outDir, id + '.geojson');
const data = JSON.stringify(layer, null, 2);
fs.writeFileSync(outFileName, data);
includeList.splice(includeList.indexOf(id), 1);
}
}
if (includeList.length > 0) {
console.warn('Layers not found: ', includeList);
}
}
fetch('https://josm.openstreetmap.de/maps?format=geojson')
.then(res => res.json())
.then(json => extract(json))
.catch(err => console.error(err));
|
/*!
* froala_editor v3.2.3 (https://www.froala.com/wysiwyg-editor)
* License https://froala.com/wysiwyg-editor/terms/
* Copyright 2014-2020 Froala Labs
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('froala-editor')) :
typeof define === 'function' && define.amd ? define(['froala-editor'], factory) :
(factory(global.FroalaEditor));
}(this, (function (FE) { 'use strict';
FE = FE && FE.hasOwnProperty('default') ? FE['default'] : FE;
/**
* Korean
*/
FE.LANGUAGE['ko'] = {
translation: {
// Place holder
'Type something': "\uB0B4\uC6A9\uC744 \uC785\uB825\uD558\uC138\uC694",
// Basic formatting
'Bold': "\uAD75\uAC8C",
'Italic': "\uAE30\uC6B8\uC784\uAF34",
'Underline': "\uBC11\uC904",
'Strikethrough': "\uCDE8\uC18C\uC120",
// Main buttons
'Insert': "\uC0BD\uC785",
'Delete': "\uC0AD\uC81C",
'Cancel': "\uCDE8\uC18C",
'OK': "\uC2B9\uC778",
'Back': "\uB4A4\uB85C",
'Remove': "\uC81C\uAC70",
'More': "\uB354",
'Update': "\uC5C5\uB370\uC774\uD2B8",
'Style': "\uC2A4\uD0C0\uC77C",
// Font
'Font Family': "\uAE00\uAF34",
'Font Size': "\uD3F0\uD2B8 \uD06C\uAE30",
// Colors
'Colors': "\uC0C9\uC0C1",
'Background': "\uBC30\uACBD",
'Text': "\uD14D\uC2A4\uD2B8",
'HEX Color': "\uD5E5\uC2A4 \uC0C9\uC0C1",
// Paragraphs
'Paragraph Format': "\uB2E8\uB77D",
'Normal': "\uD45C\uC900",
'Code': "\uCF54\uB4DC",
'Heading 1': "\uC81C\uBAA9 1",
'Heading 2': "\uC81C\uBAA9 2",
'Heading 3': "\uC81C\uBAA9 3",
'Heading 4': "\uC81C\uBAA9 4",
// Style
'Paragraph Style': "\uB2E8\uB77D \uC2A4\uD0C0\uC77C",
'Inline Style': "\uC778\uB77C\uC778 \uC2A4\uD0C0\uC77C",
// Alignment
'Align': "\uC815\uB82C",
'Align Left': "\uC67C\uCABD\uC815\uB82C",
'Align Center': "\uAC00\uC6B4\uB370\uC815\uB82C",
'Align Right': "\uC624\uB978\uCABD\uC815\uB82C",
'Align Justify': "\uC591\uCABD\uC815\uB82C",
'None': "\uC5C6\uC74C",
// Lists
'Ordered List': "\uC22B\uC790 \uB9AC\uC2A4\uD2B8",
'Unordered List': "\uC810 \uB9AC\uC2A4\uD2B8",
// Indent
'Decrease Indent': "\uB0B4\uC5B4\uC4F0\uAE30",
'Increase Indent': "\uB4E4\uC5EC\uC4F0\uAE30",
// Links
'Insert Link': "\uB9C1\uD06C \uC0BD\uC785",
'Open in new tab': "\uC0C8 \uD0ED\uC5D0\uC11C \uC5F4\uAE30",
'Open Link': "\uB9C1\uD06C \uC5F4\uAE30",
'Edit Link': "\uD3B8\uC9D1 \uB9C1\uD06C",
'Unlink': "\uB9C1\uD06C\uC0AD\uC81C",
'Choose Link': "\uB9C1\uD06C\uB97C \uC120\uD0DD",
// Images
'Insert Image': "\uC774\uBBF8\uC9C0 \uC0BD\uC785",
'Upload Image': "\uC774\uBBF8\uC9C0 \uC5C5\uB85C\uB4DC",
'By URL': "URL \uB85C",
'Browse': "\uAC80\uC0C9",
'Drop image': "\uC774\uBBF8\uC9C0\uB97C \uB4DC\uB798\uADF8&\uB4DC\uB86D",
'or click': "\uB610\uB294 \uD074\uB9AD",
'Manage Images': "\uC774\uBBF8\uC9C0 \uAD00\uB9AC",
'Loading': "\uB85C\uB4DC",
'Deleting': "\uC0AD\uC81C",
'Tags': "\uD0DC\uADF8",
'Are you sure? Image will be deleted.': "\uD655\uC2E4\uD55C\uAC00\uC694? \uC774\uBBF8\uC9C0\uAC00 \uC0AD\uC81C\uB429\uB2C8\uB2E4.",
'Replace': "\uAD50\uCCB4",
'Uploading': "\uC5C5\uB85C\uB4DC",
'Loading image': "\uC774\uBBF8\uC9C0 \uB85C\uB4DC \uC911",
'Display': "\uB514\uC2A4\uD50C\uB808\uC774",
'Inline': "\uC778\uB77C\uC778",
'Break Text': "\uAD6C\uBD84 \uD14D\uC2A4\uD2B8",
'Alternative Text': "\uB300\uCCB4 \uD14D\uC2A4\uD2B8",
'Change Size': "\uD06C\uAE30 \uBCC0\uACBD",
'Width': "\uD3ED",
'Height': "\uB192\uC774",
'Something went wrong. Please try again.': "\uBB38\uC81C\uAC00 \uBC1C\uC0DD\uD588\uC2B5\uB2C8\uB2E4. \uB2E4\uC2DC \uC2DC\uB3C4\uD558\uC2ED\uC2DC\uC624.",
'Image Caption': "\uC774\uBBF8\uC9C0 \uCEA1\uC158",
'Advanced Edit': "\uACE0\uAE09 \uD3B8\uC9D1",
// Video
'Insert Video': "\uB3D9\uC601\uC0C1 \uC0BD\uC785",
'Embedded Code': "\uC784\uBCA0\uB514\uB4DC \uCF54\uB4DC",
'Paste in a video URL': "\uB3D9\uC601\uC0C1 URL\uC5D0 \uBD99\uC5EC \uB123\uAE30",
'Drop video': "\uB3D9\uC601\uC0C1\uC744 \uB4DC\uB798\uADF8&\uB4DC\uB86D",
'Your browser does not support HTML5 video.': "\uADC0\uD558\uC758 \uBE0C\uB77C\uC6B0\uC800\uB294 html5 video\uB97C \uC9C0\uC6D0\uD558\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4.",
'Upload Video': "\uB3D9\uC601\uC0C1 \uC5C5\uB85C\uB4DC",
// Tables
'Insert Table': "\uD45C \uC0BD\uC785",
'Table Header': "\uD45C \uD5E4\uB354",
'Remove Table': "\uD45C \uC81C\uAC70",
'Table Style': "\uD45C \uC2A4\uD0C0\uC77C",
'Horizontal Align': "\uC218\uD3C9 \uC815\uB82C",
'Row': "\uD589",
'Insert row above': "\uC55E\uC5D0 \uD589\uC744 \uC0BD\uC785",
'Insert row below': "\uB4A4\uC5D0 \uD589\uC744 \uC0BD\uC785",
'Delete row': "\uD589 \uC0AD\uC81C",
'Column': "\uC5F4",
'Insert column before': "\uC55E\uC5D0 \uC5F4\uC744 \uC0BD\uC785",
'Insert column after': "\uB4A4\uC5D0 \uC5F4\uC744 \uC0BD\uC785",
'Delete column': "\uC5F4 \uC0AD\uC81C",
'Cell': "\uC140",
'Merge cells': "\uC140 \uD569\uCE58\uAE30",
'Horizontal split': "\uC218\uD3C9 \uBD84\uD560",
'Vertical split': "\uC218\uC9C1 \uBD84\uD560",
'Cell Background': "\uC140 \uBC30\uACBD",
'Vertical Align': "\uC218\uC9C1 \uC815\uB82C",
'Top': "\uC704\uCABD \uC815\uB82C",
'Middle': "\uAC00\uC6B4\uB370 \uC815\uB82C",
'Bottom': "\uC544\uB798\uCABD \uC815\uB82C",
'Align Top': "\uC704\uCABD\uC73C\uB85C \uC815\uB82C\uD569\uB2C8\uB2E4.",
'Align Middle': "\uAC00\uC6B4\uB370\uB85C \uC815\uB82C\uD569\uB2C8\uB2E4.",
'Align Bottom': "\uC544\uB798\uCABD\uC73C\uB85C \uC815\uB82C\uD569\uB2C8\uB2E4.",
'Cell Style': "\uC140 \uC2A4\uD0C0\uC77C",
// Files
'Upload File': "\uD30C\uC77C \uCCA8\uBD80",
'Drop file': "\uD30C\uC77C\uC744 \uB4DC\uB798\uADF8&\uB4DC\uB86D",
// Emoticons
'Emoticons': "\uC774\uBAA8\uD2F0\uCF58",
'Grinning face': "\uC5BC\uAD74 \uC6C3\uAE30\uB9CC",
'Grinning face with smiling eyes': "\uBBF8\uC18C\uB294 \uB208\uC744 \uAC00\uC9C4 \uC5BC\uAD74 \uC6C3\uAE30\uB9CC",
'Face with tears of joy': "\uAE30\uC068\uC758 \uB208\uBB3C\uB85C \uC5BC\uAD74",
'Smiling face with open mouth': "\uC624\uD508 \uC785\uC73C\uB85C \uC6C3\uB294 \uC5BC\uAD74",
'Smiling face with open mouth and smiling eyes': "\uC624\uD508 \uC785\uC73C\uB85C \uC6C3\uB294 \uC5BC\uAD74\uACFC \uB208\uC744 \uBBF8\uC18C",
'Smiling face with open mouth and cold sweat': "\uC785\uC744 \uC5F4\uACE0 \uC2DD\uC740 \uB540\uACFC \uD568\uAED8 \uC6C3\uB294 \uC5BC\uAD74",
'Smiling face with open mouth and tightly-closed eyes': "\uC624\uD508 \uC785\uACFC \uBC00\uC811\uD558\uAC8C \uB2EB\uD78C \uB41C \uB208\uC744 \uAC00\uC9C4 \uC6C3\uB294 \uC5BC\uAD74",
'Smiling face with halo': "\uD6C4\uAD11 \uC6C3\uB294 \uC5BC\uAD74",
'Smiling face with horns': "\uBFD4 \uC6C3\uB294 \uC5BC\uAD74",
'Winking face': "\uC5BC\uAD74 \uC719\uD06C",
'Smiling face with smiling eyes': "\uC6C3\uB294 \uB208\uC73C\uB85C \uC6C3\uB294 \uC5BC\uAD74",
'Face savoring delicious food': "\uB9DB\uC788\uB294 \uC74C\uC2DD\uC744 \uC74C\uBBF8 \uC5BC\uAD74",
'Relieved face': "\uC548\uB3C4 \uC5BC\uAD74",
'Smiling face with heart-shaped eyes': "\uD558\uD2B8 \uBAA8\uC591\uC758 \uB208\uC73C\uB85C \uC6C3\uB294 \uC5BC\uAD74",
'Smiling face with sunglasses': "\uC120\uAE00\uB77C\uC2A4 \uC6C3\uB294 \uC5BC\uAD74",
'Smirking face': "\uB3C8\uC744 \uC9C0\uBD88 \uC5BC\uAD74",
'Neutral face': "\uC911\uB9BD \uC5BC\uAD74",
'Expressionless face': "\uBB34\uD45C\uC815 \uC5BC\uAD74",
'Unamused face': "\uC990\uAC81\uAC8C\uD558\uC9C0 \uC5BC\uAD74",
'Face with cold sweat': "\uC2DD\uC740 \uB540\uACFC \uC5BC\uAD74",
'Pensive face': "\uC7A0\uACA8\uC788\uB294 \uC5BC\uAD74",
'Confused face': "\uD63C\uB780 \uC5BC\uAD74",
'Confounded face': "\uB9DD\uD560 \uAC83 \uC5BC\uAD74",
'Kissing face': "\uC5BC\uAD74\uC744 \uD0A4\uC2A4",
'Face throwing a kiss': "\uD0A4\uC2A4\uB97C \uB358\uC9C0\uACE0 \uC5BC\uAD74",
'Kissing face with smiling eyes': "\uBBF8\uC18C\uB294 \uB208\uC744 \uAC00\uC9C4 \uC5BC\uAD74\uC744 \uD0A4\uC2A4",
'Kissing face with closed eyes': "\uB2EB\uD78C \uB41C \uB208\uC744 \uAC00\uC9C4 \uC5BC\uAD74\uC744 \uD0A4\uC2A4",
'Face with stuck out tongue': "\uB0B4\uBC00 \uD600 \uC5BC\uAD74",
'Face with stuck out tongue and winking eye': "\uB0B4\uBC00 \uD600\uC640 \uC719\uD06C \uB208\uACFC \uC5BC\uAD74",
'Face with stuck out tongue and tightly-closed eyes': "\uBC16\uC73C\uB85C \uBD99\uC5B4 \uD600\uC640 \uBC00\uC811\uD558\uAC8C \uB2EB\uD78C \uB41C \uB208\uC744 \uAC00\uC9C4 \uC5BC\uAD74",
'Disappointed face': "\uC2E4\uB9DD \uC5BC\uAD74",
'Worried face': "\uAC71\uC815 \uC5BC\uAD74",
'Angry face': "\uC131\uB09C \uC5BC\uAD74",
'Pouting face': "\uC5BC\uAD74\uC744 \uC090",
'Crying face': "\uC5BC\uAD74 \uC6B0\uB294",
'Persevering face': "\uC5BC\uAD74\uC744 \uC778\uB0B4",
'Face with look of triumph': "\uC2B9\uB9AC\uC758 \uD45C\uC815\uC73C\uB85C \uC5BC\uAD74",
'Disappointed but relieved face': "\uC2E4\uB9DD\uD558\uC9C0\uB9CC \uC5BC\uAD74\uC744 \uC548\uC2EC",
'Frowning face with open mouth': "\uC624\uD508 \uC785\uC73C\uB85C \uC5BC\uAD74\uC744 \uCC21\uADF8\uB9BC",
'Anguished face': "\uACE0\uB1CC\uC758 \uC5BC\uAD74",
'Fearful face': "\uBB34\uC11C\uC6B4 \uC5BC\uAD74",
'Weary face': "\uC9C0\uCE5C \uC5BC\uAD74",
'Sleepy face': "\uC2AC\uB9AC\uD53C \uC5BC\uAD74",
'Tired face': "\uD53C\uACE4 \uC5BC\uAD74",
'Grimacing face': "\uC5BC\uAD74\uC744 \uCC21\uADF8\uB9B0",
'Loudly crying face': "\uD070 \uC18C\uB9AC\uB85C \uC5BC\uAD74\uC744 \uC6B8\uACE0",
'Face with open mouth': "\uC624\uD508 \uC785\uC73C\uB85C \uC5BC\uAD74",
'Hushed face': "\uC870\uC6A9\uD55C \uC5BC\uAD74",
'Face with open mouth and cold sweat': "\uC785\uC744 \uC5F4\uACE0 \uC2DD\uC740 \uB540\uC73C\uB85C \uC5BC\uAD74",
'Face screaming in fear': "\uACF5\uD3EC\uC5D0 \uBE44\uBA85 \uC5BC\uAD74",
'Astonished face': "\uB180\uB77C \uC5BC\uAD74",
'Flushed face': "\uD50C\uB7EC\uC2DC \uC5BC\uAD74",
'Sleeping face': "\uC5BC\uAD74 \uC7A0\uC790\uB294",
'Dizzy face': "\uB514\uC9C0 \uC5BC\uAD74",
'Face without mouth': "\uC785\uC5C6\uC774 \uC5BC\uAD74",
'Face with medical mask': "\uC758\uB8CC \uB9C8\uC2A4\uD06C\uB85C \uC5BC\uAD74",
// Line breaker
'Break': "\uB2E8\uC808",
// Math
'Subscript': "\uC544\uB798 \uCCA8\uC790",
'Superscript': "\uC704 \uCCA8\uC790",
// Full screen
'Fullscreen': "\uC804\uCCB4 \uD654\uBA74",
// Horizontal line
'Insert Horizontal Line': "\uC218\uD3C9\uC120\uC744 \uC0BD\uC785",
// Clear formatting
'Clear Formatting': "\uC11C\uC2DD \uC81C\uAC70",
// Save
'Save': "\uAD6C\uD558\uB2E4",
// Undo, redo
'Undo': "\uC2E4\uD589 \uCDE8\uC18C",
'Redo': "\uB418\uB3CC\uB9AC\uAE30",
// Select all
'Select All': "\uC804\uCCB4\uC120\uD0DD",
// Code view
'Code View': "\uCF54\uB4DC\uBCF4\uAE30",
// Quote
'Quote': "\uC778\uC6A9",
'Increase': "\uC99D\uAC00",
'Decrease': "\uAC10\uC18C",
// Quick Insert
'Quick Insert': "\uBE60\uB978 \uC0BD\uC785",
// Spcial Characters
'Special Characters': "\uD2B9\uC218 \uBB38\uC790",
'Latin': "\uB77C\uD2F4\uC5B4",
'Greek': "\uADF8\uB9AC\uC2A4\uC5B4",
'Cyrillic': "\uD0A4\uB9B4 \uBB38\uC790",
'Punctuation': "\uBB38\uC7A5\uBD80\uD638",
'Currency': "\uD1B5\uD654",
'Arrows': "\uD654\uC0B4\uD45C",
'Math': "\uC218\uD559",
'Misc': "\uADF8 \uC678",
// Print.
'Print': "\uC778\uC1C4",
// Spell Checker.
'Spell Checker': "\uB9DE\uCDA4\uBC95 \uAC80\uC0AC\uAE30",
// Help
'Help': "\uB3C4\uC6C0\uB9D0",
'Shortcuts': "\uB2E8\uCD95\uD0A4",
'Inline Editor': "\uC778\uB77C\uC778 \uC5D0\uB514\uD130",
'Show the editor': "\uC5D0\uB514\uD130 \uBCF4\uAE30",
'Common actions': "\uC77C\uBC18 \uB3D9\uC791",
'Copy': "\uBCF5\uC0AC\uD558\uAE30",
'Cut': "\uC798\uB77C\uB0B4\uAE30",
'Paste': "\uBD99\uC5EC\uB123\uAE30",
'Basic Formatting': "\uAE30\uBCF8 \uC11C\uC2DD",
'Increase quote level': "\uC778\uC6A9 \uC99D\uAC00",
'Decrease quote level': "\uC778\uC6A9 \uAC10\uC18C",
'Image / Video': "\uC774\uBBF8\uC9C0 / \uB3D9\uC601\uC0C1",
'Resize larger': "\uD06C\uAE30\uB97C \uB354 \uD06C\uAC8C \uC870\uC815",
'Resize smaller': "\uD06C\uAE30\uB97C \uB354 \uC791\uAC8C \uC870\uC815",
'Table': "\uD45C",
'Select table cell': "\uD45C \uC140 \uC120\uD0DD",
'Extend selection one cell': "\uC140\uC758 \uC120\uD0DD \uBC94\uC704\uB97C \uD655\uC7A5",
'Extend selection one row': "\uD589\uC758 \uC120\uD0DD \uBC94\uC704\uB97C \uD655\uC7A5",
'Navigation': "\uB124\uBE44\uAC8C\uC774\uC158",
'Focus popup / toolbar': "\uD31D\uC5C5 / \uD234\uBC14\uB97C \uD3EC\uCEE4\uC2A4",
'Return focus to previous position': "\uC774\uC804 \uC704\uCE58\uB85C \uD3EC\uCEE4\uC2A4 \uB418\uB3CC\uB9AC\uAE30",
// Embed.ly
'Embed URL': "\uC784\uBCA0\uB4DC URL",
'Paste in a URL to embed': "\uC784\uBCA0\uB4DC URL\uC5D0 \uBD99\uC5EC \uB123\uAE30",
// Word Paste.
'The pasted content is coming from a Microsoft Word document. Do you want to keep the format or clean it up?': "\uBD99\uC5EC\uB123\uC740 \uBB38\uC11C\uB294 \uB9C8\uC774\uD06C\uB85C\uC18C\uD504\uD2B8 \uC6CC\uB4DC\uC5D0\uC11C \uAC00\uC838\uC654\uC2B5\uB2C8\uB2E4. \uD3EC\uB9F7\uC744 \uC720\uC9C0\uD558\uAC70\uB098 \uC815\uB9AC \uD558\uC2DC\uACA0\uC2B5\uB2C8\uAE4C?",
'Keep': "\uC720\uC9C0",
'Clean': "\uC815\uB9AC",
'Word Paste Detected': "\uC6CC\uB4DC \uBD99\uC5EC \uB123\uAE30\uAC00 \uAC80\uCD9C \uB418\uC5C8\uC2B5\uB2C8\uB2E4.",
// Character Counter
'Characters': '문자',
// More Buttons
'More Text': '더 본문',
'More Paragraph': '더 절',
'More Rich': '더 풍부한',
'More Misc': '더 기타'
},
direction: 'ltr'
};
})));
//# sourceMappingURL=ko.js.map
|
import ApiBase from "./apiBase.js";
const urlbase = "api/budget/";
export default class BudgetApi extends ApiBase {
static List() {
return super.GET(urlbase + "list", result => result.months);
}
static LoadActive(month) {
return super.GETwithParams(urlbase + "active", { month: month }, result => {
return {
categories: result.categories,
funds: result.funds
};
});
}
static SetActual(month, id, amount) {
return super.POST(urlbase + "actual", {
month: month,
id: id,
amount: amount
}, () => true);
}
static SetActualFund(month, id, amount) {
return super.POST(urlbase + "actualFund", {
month: month,
id: id,
amount: amount
}, () => true);
}
static Suggestions(month) {
return super.GETwithParams(urlbase + "suggestions", { month: month }, result => {
return {
columns: result.columns,
values: result.values
};
});
}
static Create(month, categoryIds, categoryAmounts, fundIds, fundAmounts) {
return super.POST(urlbase + "create", {
month: month,
catids: categoryIds,
catamounts: categoryAmounts,
fundids: fundIds,
fundamounts: fundAmounts
}, () => true);
}
};
|
import { applyMiddleware, compose, createStore } from 'redux';
import rootReducer from '../modules';
import initialState from './initialState';
import middleware from '../middleware';
// ======================================================
// Store Enhancers
// ======================================================
const enhancers = [];
if (__DEBUG__) {
const devToolsExtension = window.devToolsExtension;
if (typeof devToolsExtension === 'function') {
enhancers.push(devToolsExtension());
}
}
// ======================================================
// Store Instantiation and HMR Setup
// ======================================================
const store = createStore(
rootReducer,
initialState,
compose(
applyMiddleware(...middleware),
...enhancers
)
);
if (module.hot) {
module.hot.accept('../modules', () => {
store.replaceReducer(rootReducer);
});
}
export default store;
|
search_result['4700']=["topic_0000000000000B6B.html","VacancyService.GetStage Method",""]; |
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var React = _interopRequireWildcard(require("react"));
var _createSvgIcon = _interopRequireDefault(require("./createSvgIcon"));
/**
* @ignore - internal component.
*/
var _default = (0, _createSvgIcon.default)( /*#__PURE__*/React.createElement("path", {
d: "M19 5v14H5V5h14m0-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2z"
}), 'CheckBoxOutlineBlank');
exports.default = _default; |
export const ADD_TODO = 'ADD_TODO'
export const TOGGLE_TODO = 'TOGGLE_TODO'
export const SET_VISIBILITY_FILTER = 'SET_VISIBILITY_FILTER'
export const VisibilityFilters = {
SHOW_ALL: 'SHOW_ALL',
SHOW_COMPLETED: 'SHOW_COMPLETED',
SHOW_ACTIVE: 'SHOW_ACTIVE',
}
|
/*
* check parsing of a (corrupt?) XML file
*
*/
const fs = require('fs');
const parser = require("xml2json");
var json;
let xml = fs.readFileSync("/tmp/test.rss");
try {
json = parser.toJson(xml);
} catch (error) {
console.error(error);
process.exit(1);
}
console.log(json);
|
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = global || self, factory(global.window = global.window || {}));
}(this, (function (exports) { 'use strict';
function _inheritsLoose(subClass, superClass) {
subClass.prototype = Object.create(superClass.prototype);
subClass.prototype.constructor = subClass;
subClass.__proto__ = superClass;
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
var _doc,
_win,
_docElement,
_body,
_divContainer,
_svgContainer,
_identityMatrix,
_transformProp = "transform",
_transformOriginProp = _transformProp + "Origin",
_hasOffsetBug,
_setDoc = function _setDoc(element) {
var doc = element.ownerDocument || element;
if (!(_transformProp in element.style) && "msTransform" in element.style) {
_transformProp = "msTransform";
_transformOriginProp = _transformProp + "Origin";
}
while (doc.parentNode && (doc = doc.parentNode)) {}
_win = window;
_identityMatrix = new Matrix2D();
if (doc) {
_doc = doc;
_docElement = doc.documentElement;
_body = doc.body;
var d1 = doc.createElement("div"),
d2 = doc.createElement("div");
_body.appendChild(d1);
d1.appendChild(d2);
d1.style.position = "static";
d1.style[_transformProp] = "translate3d(0,0,1px)";
_hasOffsetBug = d2.offsetParent !== d1;
_body.removeChild(d1);
}
return doc;
},
_forceNonZeroScale = function _forceNonZeroScale(e) {
var a, cache;
while (e && e !== _body) {
cache = e._gsap;
cache && cache.uncache && cache.get(e, "x");
if (cache && !cache.scaleX && !cache.scaleY && cache.renderTransform) {
cache.scaleX = cache.scaleY = 1e-4;
cache.renderTransform(1, cache);
a ? a.push(cache) : a = [cache];
}
e = e.parentNode;
}
return a;
},
_svgTemps = [],
_divTemps = [],
_getDocScrollTop = function _getDocScrollTop() {
return _win.pageYOffset || _doc.scrollTop || _docElement.scrollTop || _body.scrollTop || 0;
},
_getDocScrollLeft = function _getDocScrollLeft() {
return _win.pageXOffset || _doc.scrollLeft || _docElement.scrollLeft || _body.scrollLeft || 0;
},
_svgOwner = function _svgOwner(element) {
return element.ownerSVGElement || ((element.tagName + "").toLowerCase() === "svg" ? element : null);
},
_isFixed = function _isFixed(element) {
if (_win.getComputedStyle(element).position === "fixed") {
return true;
}
element = element.parentNode;
if (element && element.nodeType === 1) {
return _isFixed(element);
}
},
_createSibling = function _createSibling(element, i) {
if (element.parentNode && (_doc || _setDoc(element))) {
var svg = _svgOwner(element),
ns = svg ? svg.getAttribute("xmlns") || "http://www.w3.org/2000/svg" : "http://www.w3.org/1999/xhtml",
type = svg ? i ? "rect" : "g" : "div",
x = i !== 2 ? 0 : 100,
y = i === 3 ? 100 : 0,
css = "position:absolute;display:block;pointer-events:none;margin:0;padding:0;",
e = _doc.createElementNS ? _doc.createElementNS(ns.replace(/^https/, "http"), type) : _doc.createElement(type);
if (i) {
if (!svg) {
if (!_divContainer) {
_divContainer = _createSibling(element);
_divContainer.style.cssText = css;
}
e.style.cssText = css + "width:0.1px;height:0.1px;top:" + y + "px;left:" + x + "px";
_divContainer.appendChild(e);
} else {
_svgContainer || (_svgContainer = _createSibling(element));
e.setAttribute("width", 0.01);
e.setAttribute("height", 0.01);
e.setAttribute("transform", "translate(" + x + "," + y + ")");
_svgContainer.appendChild(e);
}
}
return e;
}
throw "Need document and parent.";
},
_consolidate = function _consolidate(m) {
var c = new Matrix2D(),
i = 0;
for (; i < m.numberOfItems; i++) {
c.multiply(m.getItem(i).matrix);
}
return c;
},
_placeSiblings = function _placeSiblings(element, adjustGOffset) {
var svg = _svgOwner(element),
isRootSVG = element === svg,
siblings = svg ? _svgTemps : _divTemps,
parent = element.parentNode,
container,
m,
b,
x,
y,
cs;
if (element === _win) {
return element;
}
siblings.length || siblings.push(_createSibling(element, 1), _createSibling(element, 2), _createSibling(element, 3));
container = svg ? _svgContainer : _divContainer;
if (svg) {
b = isRootSVG ? {
x: 0,
y: 0
} : element.getBBox();
m = element.transform ? element.transform.baseVal : {};
if (m.numberOfItems) {
m = m.numberOfItems > 1 ? _consolidate(m) : m.getItem(0).matrix;
x = m.a * b.x + m.c * b.y;
y = m.b * b.x + m.d * b.y;
} else {
m = _identityMatrix;
x = b.x;
y = b.y;
}
if (adjustGOffset && element.tagName.toLowerCase() === "g") {
x = y = 0;
}
container.setAttribute("transform", "matrix(" + m.a + "," + m.b + "," + m.c + "," + m.d + "," + (m.e + x) + "," + (m.f + y) + ")");
(isRootSVG ? svg : parent).appendChild(container);
} else {
x = y = 0;
if (_hasOffsetBug) {
m = element.offsetParent;
b = element;
while (b && (b = b.parentNode) && b !== m && b.parentNode) {
if ((_win.getComputedStyle(b)[_transformProp] + "").length > 4) {
x = b.offsetLeft;
y = b.offsetTop;
b = 0;
}
}
}
cs = _win.getComputedStyle(element);
if (cs.position !== "absolute") {
m = element.offsetParent;
while (parent !== m) {
x += parent.scrollLeft || 0;
y += parent.scrollTop || 0;
parent = parent.parentNode;
}
}
b = container.style;
b.top = element.offsetTop - y + "px";
b.left = element.offsetLeft - x + "px";
b[_transformProp] = cs[_transformProp];
b[_transformOriginProp] = cs[_transformOriginProp];
b.position = cs.position === "fixed" ? "fixed" : "absolute";
element.parentNode.appendChild(container);
}
return container;
},
_setMatrix = function _setMatrix(m, a, b, c, d, e, f) {
m.a = a;
m.b = b;
m.c = c;
m.d = d;
m.e = e;
m.f = f;
return m;
};
var Matrix2D = function () {
function Matrix2D(a, b, c, d, e, f) {
if (a === void 0) {
a = 1;
}
if (b === void 0) {
b = 0;
}
if (c === void 0) {
c = 0;
}
if (d === void 0) {
d = 1;
}
if (e === void 0) {
e = 0;
}
if (f === void 0) {
f = 0;
}
_setMatrix(this, a, b, c, d, e, f);
}
var _proto = Matrix2D.prototype;
_proto.inverse = function inverse() {
var a = this.a,
b = this.b,
c = this.c,
d = this.d,
e = this.e,
f = this.f,
determinant = a * d - b * c || 1e-10;
return _setMatrix(this, d / determinant, -b / determinant, -c / determinant, a / determinant, (c * f - d * e) / determinant, -(a * f - b * e) / determinant);
};
_proto.multiply = function multiply(matrix) {
var a = this.a,
b = this.b,
c = this.c,
d = this.d,
e = this.e,
f = this.f,
a2 = matrix.a,
b2 = matrix.c,
c2 = matrix.b,
d2 = matrix.d,
e2 = matrix.e,
f2 = matrix.f;
return _setMatrix(this, a2 * a + c2 * c, a2 * b + c2 * d, b2 * a + d2 * c, b2 * b + d2 * d, e + e2 * a + f2 * c, f + e2 * b + f2 * d);
};
_proto.clone = function clone() {
return new Matrix2D(this.a, this.b, this.c, this.d, this.e, this.f);
};
_proto.equals = function equals(matrix) {
var a = this.a,
b = this.b,
c = this.c,
d = this.d,
e = this.e,
f = this.f;
return a === matrix.a && b === matrix.b && c === matrix.c && d === matrix.d && e === matrix.e && f === matrix.f;
};
_proto.apply = function apply(point, decoratee) {
if (decoratee === void 0) {
decoratee = {};
}
var x = point.x,
y = point.y,
a = this.a,
b = this.b,
c = this.c,
d = this.d,
e = this.e,
f = this.f;
decoratee.x = x * a + y * c + e || 0;
decoratee.y = x * b + y * d + f || 0;
return decoratee;
};
return Matrix2D;
}();
function getGlobalMatrix(element, inverse, adjustGOffset, includeScrollInFixed) {
if (!element || !element.parentNode || (_doc || _setDoc(element)).documentElement === element) {
return new Matrix2D();
}
var zeroScales = _forceNonZeroScale(element),
svg = _svgOwner(element),
temps = svg ? _svgTemps : _divTemps,
container = _placeSiblings(element, adjustGOffset),
b1 = temps[0].getBoundingClientRect(),
b2 = temps[1].getBoundingClientRect(),
b3 = temps[2].getBoundingClientRect(),
parent = container.parentNode,
isFixed = !includeScrollInFixed && _isFixed(element),
m = new Matrix2D((b2.left - b1.left) / 100, (b2.top - b1.top) / 100, (b3.left - b1.left) / 100, (b3.top - b1.top) / 100, b1.left + (isFixed ? 0 : _getDocScrollLeft()), b1.top + (isFixed ? 0 : _getDocScrollTop()));
parent.removeChild(container);
if (zeroScales) {
b1 = zeroScales.length;
while (b1--) {
b2 = zeroScales[b1];
b2.scaleX = b2.scaleY = 0;
b2.renderTransform(1, b2);
}
}
return inverse ? m.inverse() : m;
}
var gsap,
_win$1,
_doc$1,
_docElement$1,
_body$1,
_tempDiv,
_placeholderDiv,
_coreInitted,
_checkPrefix,
_toArray,
_supportsPassive,
_isTouchDevice,
_touchEventLookup,
_dragCount,
_isMultiTouching,
_isAndroid,
InertiaPlugin,
_defaultCursor,
_supportsPointer,
_windowExists = function _windowExists() {
return typeof window !== "undefined";
},
_getGSAP = function _getGSAP() {
return gsap || _windowExists() && (gsap = window.gsap) && gsap.registerPlugin && gsap;
},
_isFunction = function _isFunction(value) {
return typeof value === "function";
},
_isObject = function _isObject(value) {
return typeof value === "object";
},
_isUndefined = function _isUndefined(value) {
return typeof value === "undefined";
},
_emptyFunc = function _emptyFunc() {
return false;
},
_transformProp$1 = "transform",
_transformOriginProp$1 = "transformOrigin",
_round = function _round(value) {
return Math.round(value * 10000) / 10000;
},
_isArray = Array.isArray,
_createElement = function _createElement(type, ns) {
var e = _doc$1.createElementNS ? _doc$1.createElementNS((ns || "http://www.w3.org/1999/xhtml").replace(/^https/, "http"), type) : _doc$1.createElement(type);
return e.style ? e : _doc$1.createElement(type);
},
_RAD2DEG = 180 / Math.PI,
_bigNum = 1e20,
_identityMatrix$1 = new Matrix2D(),
_getTime = Date.now || function () {
return new Date().getTime();
},
_renderQueue = [],
_lookup = {},
_lookupCount = 0,
_clickableTagExp = /^(?:a|input|textarea|button|select)$/i,
_lastDragTime = 0,
_temp1 = {},
_windowProxy = {},
_copy = function _copy(obj, factor) {
var copy = {},
p;
for (p in obj) {
copy[p] = factor ? obj[p] * factor : obj[p];
}
return copy;
},
_extend = function _extend(obj, defaults) {
for (var p in defaults) {
if (!(p in obj)) {
obj[p] = defaults[p];
}
}
return obj;
},
_setTouchActionForAllDescendants = function _setTouchActionForAllDescendants(elements, value) {
var i = elements.length,
children;
while (i--) {
value ? elements[i].style.touchAction = value : elements[i].style.removeProperty("touch-action");
children = elements[i].children;
children && children.length && _setTouchActionForAllDescendants(children, value);
}
},
_renderQueueTick = function _renderQueueTick() {
return _renderQueue.forEach(function (func) {
return func();
});
},
_addToRenderQueue = function _addToRenderQueue(func) {
_renderQueue.push(func);
if (_renderQueue.length === 1) {
gsap.ticker.add(_renderQueueTick);
}
},
_renderQueueTimeout = function _renderQueueTimeout() {
return !_renderQueue.length && gsap.ticker.remove(_renderQueueTick);
},
_removeFromRenderQueue = function _removeFromRenderQueue(func) {
var i = _renderQueue.length;
while (i--) {
if (_renderQueue[i] === func) {
_renderQueue.splice(i, 1);
}
}
gsap.to(_renderQueueTimeout, {
overwrite: true,
delay: 15,
duration: 0,
onComplete: _renderQueueTimeout,
data: "_draggable"
});
},
_setDefaults = function _setDefaults(obj, defaults) {
for (var p in defaults) {
if (!(p in obj)) {
obj[p] = defaults[p];
}
}
return obj;
},
_addListener = function _addListener(element, type, func, capture) {
if (element.addEventListener) {
var touchType = _touchEventLookup[type];
capture = capture || (_supportsPassive ? {
passive: false
} : null);
element.addEventListener(touchType || type, func, capture);
touchType && type !== touchType && element.addEventListener(type, func, capture);
}
},
_removeListener = function _removeListener(element, type, func) {
if (element.removeEventListener) {
var touchType = _touchEventLookup[type];
element.removeEventListener(touchType || type, func);
touchType && type !== touchType && element.removeEventListener(type, func);
}
},
_preventDefault = function _preventDefault(event) {
event.preventDefault && event.preventDefault();
event.preventManipulation && event.preventManipulation();
},
_hasTouchID = function _hasTouchID(list, ID) {
var i = list.length;
while (i--) {
if (list[i].identifier === ID) {
return true;
}
}
},
_onMultiTouchDocumentEnd = function _onMultiTouchDocumentEnd(event) {
_isMultiTouching = event.touches && _dragCount < event.touches.length;
_removeListener(event.target, "touchend", _onMultiTouchDocumentEnd);
},
_onMultiTouchDocument = function _onMultiTouchDocument(event) {
_isMultiTouching = event.touches && _dragCount < event.touches.length;
_addListener(event.target, "touchend", _onMultiTouchDocumentEnd);
},
_getDocScrollTop$1 = function _getDocScrollTop(doc) {
return _win$1.pageYOffset || doc.scrollTop || doc.documentElement.scrollTop || doc.body.scrollTop || 0;
},
_getDocScrollLeft$1 = function _getDocScrollLeft(doc) {
return _win$1.pageXOffset || doc.scrollLeft || doc.documentElement.scrollLeft || doc.body.scrollLeft || 0;
},
_addScrollListener = function _addScrollListener(e, callback) {
_addListener(e, "scroll", callback);
if (!_isRoot(e.parentNode)) {
_addScrollListener(e.parentNode, callback);
}
},
_removeScrollListener = function _removeScrollListener(e, callback) {
_removeListener(e, "scroll", callback);
if (!_isRoot(e.parentNode)) {
_removeScrollListener(e.parentNode, callback);
}
},
_isRoot = function _isRoot(e) {
return !!(!e || e === _docElement$1 || e.nodeType === 9 || e === _doc$1.body || e === _win$1 || !e.nodeType || !e.parentNode);
},
_getMaxScroll = function _getMaxScroll(element, axis) {
var dim = axis === "x" ? "Width" : "Height",
scroll = "scroll" + dim,
client = "client" + dim;
return Math.max(0, _isRoot(element) ? Math.max(_docElement$1[scroll], _body$1[scroll]) - (_win$1["inner" + dim] || _docElement$1[client] || _body$1[client]) : element[scroll] - element[client]);
},
_recordMaxScrolls = function _recordMaxScrolls(e, skipCurrent) {
var x = _getMaxScroll(e, "x"),
y = _getMaxScroll(e, "y");
if (_isRoot(e)) {
e = _windowProxy;
} else {
_recordMaxScrolls(e.parentNode, skipCurrent);
}
e._gsMaxScrollX = x;
e._gsMaxScrollY = y;
if (!skipCurrent) {
e._gsScrollX = e.scrollLeft || 0;
e._gsScrollY = e.scrollTop || 0;
}
},
_setStyle = function _setStyle(element, property, value) {
var style = element.style;
if (!style) {
return;
}
if (_isUndefined(style[property])) {
property = _checkPrefix(property, element) || property;
}
if (value == null) {
style.removeProperty && style.removeProperty(property.replace(/([A-Z])/g, "-$1").toLowerCase());
} else {
style[property] = value;
}
},
_getComputedStyle = function _getComputedStyle(element) {
return _win$1.getComputedStyle(element instanceof Element ? element : element.host || (element.parentNode || {}).host || element);
},
_tempRect = {},
_parseRect = function _parseRect(e) {
if (e === _win$1) {
_tempRect.left = _tempRect.top = 0;
_tempRect.width = _tempRect.right = _docElement$1.clientWidth || e.innerWidth || _body$1.clientWidth || 0;
_tempRect.height = _tempRect.bottom = (e.innerHeight || 0) - 20 < _docElement$1.clientHeight ? _docElement$1.clientHeight : e.innerHeight || _body$1.clientHeight || 0;
return _tempRect;
}
var doc = e.ownerDocument || _doc$1,
r = !_isUndefined(e.pageX) ? {
left: e.pageX - _getDocScrollLeft$1(doc),
top: e.pageY - _getDocScrollTop$1(doc),
right: e.pageX - _getDocScrollLeft$1(doc) + 1,
bottom: e.pageY - _getDocScrollTop$1(doc) + 1
} : !e.nodeType && !_isUndefined(e.left) && !_isUndefined(e.top) ? e : _toArray(e)[0].getBoundingClientRect();
if (_isUndefined(r.right) && !_isUndefined(r.width)) {
r.right = r.left + r.width;
r.bottom = r.top + r.height;
} else if (_isUndefined(r.width)) {
r = {
width: r.right - r.left,
height: r.bottom - r.top,
right: r.right,
left: r.left,
bottom: r.bottom,
top: r.top
};
}
return r;
},
_dispatchEvent = function _dispatchEvent(target, type, callbackName) {
var vars = target.vars,
callback = vars[callbackName],
listeners = target._listeners[type],
result;
if (_isFunction(callback)) {
result = callback.apply(vars.callbackScope || target, vars[callbackName + "Params"] || [target.pointerEvent]);
}
if (listeners && target.dispatchEvent(type) === false) {
result = false;
}
return result;
},
_getBounds = function _getBounds(target, context) {
var e = _toArray(target)[0],
top,
left,
offset;
if (!e.nodeType && e !== _win$1) {
if (!_isUndefined(target.left)) {
offset = {
x: 0,
y: 0
};
return {
left: target.left - offset.x,
top: target.top - offset.y,
width: target.width,
height: target.height
};
}
left = target.min || target.minX || target.minRotation || 0;
top = target.min || target.minY || 0;
return {
left: left,
top: top,
width: (target.max || target.maxX || target.maxRotation || 0) - left,
height: (target.max || target.maxY || 0) - top
};
}
return _getElementBounds(e, context);
},
_point1 = {},
_getElementBounds = function _getElementBounds(element, context) {
context = _toArray(context)[0];
var isSVG = element.getBBox && element.ownerSVGElement,
doc = element.ownerDocument || _doc$1,
left,
right,
top,
bottom,
matrix,
p1,
p2,
p3,
p4,
bbox,
width,
height,
cs,
contextParent;
if (element === _win$1) {
top = _getDocScrollTop$1(doc);
left = _getDocScrollLeft$1(doc);
right = left + (doc.documentElement.clientWidth || element.innerWidth || doc.body.clientWidth || 0);
bottom = top + ((element.innerHeight || 0) - 20 < doc.documentElement.clientHeight ? doc.documentElement.clientHeight : element.innerHeight || doc.body.clientHeight || 0);
} else if (context === _win$1 || _isUndefined(context)) {
return element.getBoundingClientRect();
} else {
left = top = 0;
if (isSVG) {
bbox = element.getBBox();
width = bbox.width;
height = bbox.height;
} else {
if (element.viewBox && (bbox = element.viewBox.baseVal)) {
left = bbox.x || 0;
top = bbox.y || 0;
width = bbox.width;
height = bbox.height;
}
if (!width) {
cs = _getComputedStyle(element);
bbox = cs.boxSizing === "border-box";
width = (parseFloat(cs.width) || element.clientWidth || 0) + (bbox ? 0 : parseFloat(cs.borderLeftWidth) + parseFloat(cs.borderRightWidth));
height = (parseFloat(cs.height) || element.clientHeight || 0) + (bbox ? 0 : parseFloat(cs.borderTopWidth) + parseFloat(cs.borderBottomWidth));
}
}
right = width;
bottom = height;
}
if (element === context) {
return {
left: left,
top: top,
width: right - left,
height: bottom - top
};
}
matrix = getGlobalMatrix(context, true).multiply(getGlobalMatrix(element));
p1 = matrix.apply({
x: left,
y: top
});
p2 = matrix.apply({
x: right,
y: top
});
p3 = matrix.apply({
x: right,
y: bottom
});
p4 = matrix.apply({
x: left,
y: bottom
});
left = Math.min(p1.x, p2.x, p3.x, p4.x);
top = Math.min(p1.y, p2.y, p3.y, p4.y);
contextParent = context.parentNode || {};
return {
left: left + (contextParent.scrollLeft || 0),
top: top + (contextParent.scrollTop || 0),
width: Math.max(p1.x, p2.x, p3.x, p4.x) - left,
height: Math.max(p1.y, p2.y, p3.y, p4.y) - top
};
},
_parseInertia = function _parseInertia(draggable, snap, max, min, factor, forceZeroVelocity) {
var vars = {},
a,
i,
l;
if (snap) {
if (factor !== 1 && snap instanceof Array) {
vars.end = a = [];
l = snap.length;
if (_isObject(snap[0])) {
for (i = 0; i < l; i++) {
a[i] = _copy(snap[i], factor);
}
} else {
for (i = 0; i < l; i++) {
a[i] = snap[i] * factor;
}
}
max += 1.1;
min -= 1.1;
} else if (_isFunction(snap)) {
vars.end = function (value) {
var result = snap.call(draggable, value),
copy,
p;
if (factor !== 1) {
if (_isObject(result)) {
copy = {};
for (p in result) {
copy[p] = result[p] * factor;
}
result = copy;
} else {
result *= factor;
}
}
return result;
};
} else {
vars.end = snap;
}
}
if (max || max === 0) {
vars.max = max;
}
if (min || min === 0) {
vars.min = min;
}
if (forceZeroVelocity) {
vars.velocity = 0;
}
return vars;
},
_isClickable = function _isClickable(element) {
var data;
return !element || !element.getAttribute || element === _body$1 ? false : (data = element.getAttribute("data-clickable")) === "true" || data !== "false" && (element.onclick || _clickableTagExp.test(element.nodeName + "") || element.getAttribute("contentEditable") === "true") ? true : _isClickable(element.parentNode);
},
_setSelectable = function _setSelectable(elements, selectable) {
var i = elements.length,
e;
while (i--) {
e = elements[i];
e.ondragstart = e.onselectstart = selectable ? null : _emptyFunc;
gsap.set(e, {
lazy: true,
userSelect: selectable ? "text" : "none"
});
}
},
_isFixed$1 = function _isFixed(element) {
if (_getComputedStyle(element).position === "fixed") {
return true;
}
element = element.parentNode;
if (element && element.nodeType === 1) {
return _isFixed(element);
}
},
_supports3D,
_addPaddingBR,
ScrollProxy = function ScrollProxy(element, vars) {
element = gsap.utils.toArray(element)[0];
vars = vars || {};
var content = document.createElement("div"),
style = content.style,
node = element.firstChild,
offsetTop = 0,
offsetLeft = 0,
prevTop = element.scrollTop,
prevLeft = element.scrollLeft,
scrollWidth = element.scrollWidth,
scrollHeight = element.scrollHeight,
extraPadRight = 0,
maxLeft = 0,
maxTop = 0,
elementWidth,
elementHeight,
contentHeight,
nextNode,
transformStart,
transformEnd;
if (_supports3D && vars.force3D !== false) {
transformStart = "translate3d(";
transformEnd = "px,0px)";
} else if (_transformProp$1) {
transformStart = "translate(";
transformEnd = "px)";
}
this.scrollTop = function (value, force) {
if (!arguments.length) {
return -this.top();
}
this.top(-value, force);
};
this.scrollLeft = function (value, force) {
if (!arguments.length) {
return -this.left();
}
this.left(-value, force);
};
this.left = function (value, force) {
if (!arguments.length) {
return -(element.scrollLeft + offsetLeft);
}
var dif = element.scrollLeft - prevLeft,
oldOffset = offsetLeft;
if ((dif > 2 || dif < -2) && !force) {
prevLeft = element.scrollLeft;
gsap.killTweensOf(this, {
left: 1,
scrollLeft: 1
});
this.left(-prevLeft);
if (vars.onKill) {
vars.onKill();
}
return;
}
value = -value;
if (value < 0) {
offsetLeft = value - 0.5 | 0;
value = 0;
} else if (value > maxLeft) {
offsetLeft = value - maxLeft | 0;
value = maxLeft;
} else {
offsetLeft = 0;
}
if (offsetLeft || oldOffset) {
if (!this._skip) {
style[_transformProp$1] = transformStart + -offsetLeft + "px," + -offsetTop + transformEnd;
}
if (offsetLeft + extraPadRight >= 0) {
style.paddingRight = offsetLeft + extraPadRight + "px";
}
}
element.scrollLeft = value | 0;
prevLeft = element.scrollLeft;
};
this.top = function (value, force) {
if (!arguments.length) {
return -(element.scrollTop + offsetTop);
}
var dif = element.scrollTop - prevTop,
oldOffset = offsetTop;
if ((dif > 2 || dif < -2) && !force) {
prevTop = element.scrollTop;
gsap.killTweensOf(this, {
top: 1,
scrollTop: 1
});
this.top(-prevTop);
if (vars.onKill) {
vars.onKill();
}
return;
}
value = -value;
if (value < 0) {
offsetTop = value - 0.5 | 0;
value = 0;
} else if (value > maxTop) {
offsetTop = value - maxTop | 0;
value = maxTop;
} else {
offsetTop = 0;
}
if (offsetTop || oldOffset) {
if (!this._skip) {
style[_transformProp$1] = transformStart + -offsetLeft + "px," + -offsetTop + transformEnd;
}
}
element.scrollTop = value | 0;
prevTop = element.scrollTop;
};
this.maxScrollTop = function () {
return maxTop;
};
this.maxScrollLeft = function () {
return maxLeft;
};
this.disable = function () {
node = content.firstChild;
while (node) {
nextNode = node.nextSibling;
element.appendChild(node);
node = nextNode;
}
if (element === content.parentNode) {
element.removeChild(content);
}
};
this.enable = function () {
node = element.firstChild;
if (node === content) {
return;
}
while (node) {
nextNode = node.nextSibling;
content.appendChild(node);
node = nextNode;
}
element.appendChild(content);
this.calibrate();
};
this.calibrate = function (force) {
var widthMatches = element.clientWidth === elementWidth,
cs,
x,
y;
prevTop = element.scrollTop;
prevLeft = element.scrollLeft;
if (widthMatches && element.clientHeight === elementHeight && content.offsetHeight === contentHeight && scrollWidth === element.scrollWidth && scrollHeight === element.scrollHeight && !force) {
return;
}
if (offsetTop || offsetLeft) {
x = this.left();
y = this.top();
this.left(-element.scrollLeft);
this.top(-element.scrollTop);
}
cs = _getComputedStyle(element);
if (!widthMatches || force) {
style.display = "block";
style.width = "auto";
style.paddingRight = "0px";
extraPadRight = Math.max(0, element.scrollWidth - element.clientWidth);
if (extraPadRight) {
extraPadRight += parseFloat(cs.paddingLeft) + (_addPaddingBR ? parseFloat(cs.paddingRight) : 0);
}
}
style.display = "inline-block";
style.position = "relative";
style.overflow = "visible";
style.verticalAlign = "top";
style.boxSizing = "content-box";
style.width = "100%";
style.paddingRight = extraPadRight + "px";
if (_addPaddingBR) {
style.paddingBottom = cs.paddingBottom;
}
elementWidth = element.clientWidth;
elementHeight = element.clientHeight;
scrollWidth = element.scrollWidth;
scrollHeight = element.scrollHeight;
maxLeft = element.scrollWidth - elementWidth;
maxTop = element.scrollHeight - elementHeight;
contentHeight = content.offsetHeight;
style.display = "block";
if (x || y) {
this.left(x);
this.top(y);
}
};
this.content = content;
this.element = element;
this._skip = false;
this.enable();
},
_initCore = function _initCore(required) {
if (_windowExists() && document.body) {
var nav = window && window.navigator;
_win$1 = window;
_doc$1 = document;
_docElement$1 = _doc$1.documentElement;
_body$1 = _doc$1.body;
_tempDiv = _createElement("div");
_supportsPointer = !!window.PointerEvent;
_placeholderDiv = _createElement("div");
_placeholderDiv.style.cssText = "visibility:hidden;height:1px;top:-1px;pointer-events:none;position:relative;clear:both;cursor:grab";
_defaultCursor = _placeholderDiv.style.cursor === "grab" ? "grab" : "move";
_isAndroid = nav && nav.userAgent.toLowerCase().indexOf("android") !== -1;
_isTouchDevice = "ontouchstart" in _docElement$1 && "orientation" in _win$1 || nav && (nav.MaxTouchPoints > 0 || nav.msMaxTouchPoints > 0);
_addPaddingBR = function () {
var div = _createElement("div"),
child = _createElement("div"),
childStyle = child.style,
parent = _body$1,
val;
childStyle.display = "inline-block";
childStyle.position = "relative";
div.style.cssText = child.innerHTML = "width:90px;height:40px;padding:10px;overflow:auto;visibility:hidden";
div.appendChild(child);
parent.appendChild(div);
val = child.offsetHeight + 18 > div.scrollHeight;
parent.removeChild(div);
return val;
}();
_touchEventLookup = function (types) {
var standard = types.split(","),
converted = ("onpointerdown" in _tempDiv ? "pointerdown,pointermove,pointerup,pointercancel" : "onmspointerdown" in _tempDiv ? "MSPointerDown,MSPointerMove,MSPointerUp,MSPointerCancel" : types).split(","),
obj = {},
i = 4;
while (--i > -1) {
obj[standard[i]] = converted[i];
obj[converted[i]] = standard[i];
}
try {
_docElement$1.addEventListener("test", null, Object.defineProperty({}, "passive", {
get: function get() {
_supportsPassive = 1;
}
}));
} catch (e) {}
return obj;
}("touchstart,touchmove,touchend,touchcancel");
_addListener(_doc$1, "touchcancel", _emptyFunc);
_addListener(_win$1, "touchmove", _emptyFunc);
_body$1 && _body$1.addEventListener("touchstart", _emptyFunc);
_addListener(_doc$1, "contextmenu", function () {
for (var p in _lookup) {
if (_lookup[p].isPressed) {
_lookup[p].endDrag();
}
}
});
gsap = _coreInitted = _getGSAP();
}
if (gsap) {
InertiaPlugin = gsap.plugins.inertia;
_checkPrefix = gsap.utils.checkPrefix;
_transformProp$1 = _checkPrefix(_transformProp$1);
_transformOriginProp$1 = _checkPrefix(_transformOriginProp$1);
_toArray = gsap.utils.toArray;
_supports3D = !!_checkPrefix("perspective");
} else if (required) {
console.warn("Please gsap.registerPlugin(Draggable)");
}
};
var EventDispatcher = function () {
function EventDispatcher(target) {
this._listeners = {};
this.target = target || this;
}
var _proto = EventDispatcher.prototype;
_proto.addEventListener = function addEventListener(type, callback) {
var list = this._listeners[type] || (this._listeners[type] = []);
if (!~list.indexOf(callback)) {
list.push(callback);
}
};
_proto.removeEventListener = function removeEventListener(type, callback) {
var list = this._listeners[type],
i = list && list.indexOf(callback) || -1;
i > -1 && list.splice(i, 1);
};
_proto.dispatchEvent = function dispatchEvent(type) {
var _this = this;
var result;
(this._listeners[type] || []).forEach(function (callback) {
return callback.call(_this, {
type: type,
target: _this.target
}) === false && (result = false);
});
return result;
};
return EventDispatcher;
}();
var Draggable = function (_EventDispatcher) {
_inheritsLoose(Draggable, _EventDispatcher);
function Draggable(target, vars) {
var _this2;
_this2 = _EventDispatcher.call(this) || this;
if (!gsap) {
_initCore(1);
}
target = _toArray(target)[0];
if (!InertiaPlugin) {
InertiaPlugin = gsap.plugins.inertia;
}
_this2.vars = vars = _copy(vars || {});
_this2.target = target;
_this2.x = _this2.y = _this2.rotation = 0;
_this2.dragResistance = parseFloat(vars.dragResistance) || 0;
_this2.edgeResistance = isNaN(vars.edgeResistance) ? 1 : parseFloat(vars.edgeResistance) || 0;
_this2.lockAxis = vars.lockAxis;
_this2.autoScroll = vars.autoScroll || 0;
_this2.lockedAxis = null;
_this2.allowEventDefault = !!vars.allowEventDefault;
gsap.getProperty(target, "x");
var type = (vars.type || "x,y").toLowerCase(),
xyMode = ~type.indexOf("x") || ~type.indexOf("y"),
rotationMode = type.indexOf("rotation") !== -1,
xProp = rotationMode ? "rotation" : xyMode ? "x" : "left",
yProp = xyMode ? "y" : "top",
allowX = !!(~type.indexOf("x") || ~type.indexOf("left") || type === "scroll"),
allowY = !!(~type.indexOf("y") || ~type.indexOf("top") || type === "scroll"),
minimumMovement = vars.minimumMovement || 2,
self = _assertThisInitialized(_this2),
triggers = _toArray(vars.trigger || vars.handle || target),
killProps = {},
dragEndTime = 0,
checkAutoScrollBounds = false,
autoScrollMarginTop = vars.autoScrollMarginTop || 40,
autoScrollMarginRight = vars.autoScrollMarginRight || 40,
autoScrollMarginBottom = vars.autoScrollMarginBottom || 40,
autoScrollMarginLeft = vars.autoScrollMarginLeft || 40,
isClickable = vars.clickableTest || _isClickable,
clickTime = 0,
gsCache = target._gsap || gsap.core.getCache(target),
isFixed = _isFixed$1(target),
getPropAsNum = function getPropAsNum(property, unit) {
return parseFloat(gsCache.get(target, property, unit));
},
ownerDoc = target.ownerDocument || _doc$1,
enabled,
scrollProxy,
startPointerX,
startPointerY,
startElementX,
startElementY,
hasBounds,
hasDragCallback,
hasMoveCallback,
maxX,
minX,
maxY,
minY,
touch,
touchID,
rotationOrigin,
dirty,
old,
snapX,
snapY,
snapXY,
isClicking,
touchEventTarget,
matrix,
interrupted,
allowNativeTouchScrolling,
touchDragAxis,
isDispatching,
clickDispatch,
trustedClickDispatch,
isPreventingDefault,
onContextMenu = function onContextMenu(e) {
_preventDefault(e);
e.stopImmediatePropagation && e.stopImmediatePropagation();
return false;
},
render = function render(suppressEvents) {
if (self.autoScroll && self.isDragging && (checkAutoScrollBounds || dirty)) {
var e = target,
autoScrollFactor = self.autoScroll * 15,
parent,
isRoot,
rect,
pointerX,
pointerY,
changeX,
changeY,
gap;
checkAutoScrollBounds = false;
_windowProxy.scrollTop = _win$1.pageYOffset != null ? _win$1.pageYOffset : ownerDoc.documentElement.scrollTop != null ? ownerDoc.documentElement.scrollTop : ownerDoc.body.scrollTop;
_windowProxy.scrollLeft = _win$1.pageXOffset != null ? _win$1.pageXOffset : ownerDoc.documentElement.scrollLeft != null ? ownerDoc.documentElement.scrollLeft : ownerDoc.body.scrollLeft;
pointerX = self.pointerX - _windowProxy.scrollLeft;
pointerY = self.pointerY - _windowProxy.scrollTop;
while (e && !isRoot) {
isRoot = _isRoot(e.parentNode);
parent = isRoot ? _windowProxy : e.parentNode;
rect = isRoot ? {
bottom: Math.max(_docElement$1.clientHeight, _win$1.innerHeight || 0),
right: Math.max(_docElement$1.clientWidth, _win$1.innerWidth || 0),
left: 0,
top: 0
} : parent.getBoundingClientRect();
changeX = changeY = 0;
if (allowY) {
gap = parent._gsMaxScrollY - parent.scrollTop;
if (gap < 0) {
changeY = gap;
} else if (pointerY > rect.bottom - autoScrollMarginBottom && gap) {
checkAutoScrollBounds = true;
changeY = Math.min(gap, autoScrollFactor * (1 - Math.max(0, rect.bottom - pointerY) / autoScrollMarginBottom) | 0);
} else if (pointerY < rect.top + autoScrollMarginTop && parent.scrollTop) {
checkAutoScrollBounds = true;
changeY = -Math.min(parent.scrollTop, autoScrollFactor * (1 - Math.max(0, pointerY - rect.top) / autoScrollMarginTop) | 0);
}
if (changeY) {
parent.scrollTop += changeY;
}
}
if (allowX) {
gap = parent._gsMaxScrollX - parent.scrollLeft;
if (gap < 0) {
changeX = gap;
} else if (pointerX > rect.right - autoScrollMarginRight && gap) {
checkAutoScrollBounds = true;
changeX = Math.min(gap, autoScrollFactor * (1 - Math.max(0, rect.right - pointerX) / autoScrollMarginRight) | 0);
} else if (pointerX < rect.left + autoScrollMarginLeft && parent.scrollLeft) {
checkAutoScrollBounds = true;
changeX = -Math.min(parent.scrollLeft, autoScrollFactor * (1 - Math.max(0, pointerX - rect.left) / autoScrollMarginLeft) | 0);
}
if (changeX) {
parent.scrollLeft += changeX;
}
}
if (isRoot && (changeX || changeY)) {
_win$1.scrollTo(parent.scrollLeft, parent.scrollTop);
setPointerPosition(self.pointerX + changeX, self.pointerY + changeY);
}
e = parent;
}
}
if (dirty) {
var x = self.x,
y = self.y;
if (rotationMode) {
self.deltaX = x - parseFloat(gsCache.rotation);
self.rotation = x;
gsCache.rotation = x + "deg";
gsCache.renderTransform(1, gsCache);
} else {
if (scrollProxy) {
if (allowY) {
self.deltaY = y - scrollProxy.top();
scrollProxy.top(y);
}
if (allowX) {
self.deltaX = x - scrollProxy.left();
scrollProxy.left(x);
}
} else if (xyMode) {
if (allowY) {
self.deltaY = y - parseFloat(gsCache.y);
gsCache.y = y + "px";
}
if (allowX) {
self.deltaX = x - parseFloat(gsCache.x);
gsCache.x = x + "px";
}
gsCache.renderTransform(1, gsCache);
} else {
if (allowY) {
self.deltaY = y - parseFloat(target.style.top || 0);
target.style.top = y + "px";
}
if (allowX) {
self.deltaY = x - parseFloat(target.style.left || 0);
target.style.left = x + "px";
}
}
}
if (hasDragCallback && !suppressEvents && !isDispatching) {
isDispatching = true;
if (_dispatchEvent(self, "drag", "onDrag") === false) {
if (allowX) {
self.x -= self.deltaX;
}
if (allowY) {
self.y -= self.deltaY;
}
render(true);
}
isDispatching = false;
}
}
dirty = false;
},
syncXY = function syncXY(skipOnUpdate, skipSnap) {
var x = self.x,
y = self.y,
snappedValue,
cs;
if (!target._gsap) {
gsCache = gsap.core.getCache(target);
}
gsCache.uncache && gsap.getProperty(target, "x");
if (xyMode) {
self.x = parseFloat(gsCache.x);
self.y = parseFloat(gsCache.y);
} else if (rotationMode) {
self.x = self.rotation = parseFloat(gsCache.rotation);
} else if (scrollProxy) {
self.y = scrollProxy.top();
self.x = scrollProxy.left();
} else {
self.y = parseInt(target.style.top || (cs = _getComputedStyle(target)) && cs.top, 10) || 0;
self.x = parseInt(target.style.left || (cs || {}).left, 10) || 0;
}
if ((snapX || snapY || snapXY) && !skipSnap && (self.isDragging || self.isThrowing)) {
if (snapXY) {
_temp1.x = self.x;
_temp1.y = self.y;
snappedValue = snapXY(_temp1);
if (snappedValue.x !== self.x) {
self.x = snappedValue.x;
dirty = true;
}
if (snappedValue.y !== self.y) {
self.y = snappedValue.y;
dirty = true;
}
}
if (snapX) {
snappedValue = snapX(self.x);
if (snappedValue !== self.x) {
self.x = snappedValue;
if (rotationMode) {
self.rotation = snappedValue;
}
dirty = true;
}
}
if (snapY) {
snappedValue = snapY(self.y);
if (snappedValue !== self.y) {
self.y = snappedValue;
}
dirty = true;
}
}
dirty && render(true);
if (!skipOnUpdate) {
self.deltaX = self.x - x;
self.deltaY = self.y - y;
_dispatchEvent(self, "throwupdate", "onThrowUpdate");
}
},
buildSnapFunc = function buildSnapFunc(snap, min, max, factor) {
if (min == null) {
min = -_bigNum;
}
if (max == null) {
max = _bigNum;
}
if (_isFunction(snap)) {
return function (n) {
var edgeTolerance = !self.isPressed ? 1 : 1 - self.edgeResistance;
return snap.call(self, n > max ? max + (n - max) * edgeTolerance : n < min ? min + (n - min) * edgeTolerance : n) * factor;
};
}
if (_isArray(snap)) {
return function (n) {
var i = snap.length,
closest = 0,
absDif = _bigNum,
val,
dif;
while (--i > -1) {
val = snap[i];
dif = val - n;
if (dif < 0) {
dif = -dif;
}
if (dif < absDif && val >= min && val <= max) {
closest = i;
absDif = dif;
}
}
return snap[closest];
};
}
return isNaN(snap) ? function (n) {
return n;
} : function () {
return snap * factor;
};
},
buildPointSnapFunc = function buildPointSnapFunc(snap, minX, maxX, minY, maxY, radius, factor) {
radius = radius && radius < _bigNum ? radius * radius : _bigNum;
if (_isFunction(snap)) {
return function (point) {
var edgeTolerance = !self.isPressed ? 1 : 1 - self.edgeResistance,
x = point.x,
y = point.y,
result,
dx,
dy;
point.x = x = x > maxX ? maxX + (x - maxX) * edgeTolerance : x < minX ? minX + (x - minX) * edgeTolerance : x;
point.y = y = y > maxY ? maxY + (y - maxY) * edgeTolerance : y < minY ? minY + (y - minY) * edgeTolerance : y;
result = snap.call(self, point);
if (result !== point) {
point.x = result.x;
point.y = result.y;
}
if (factor !== 1) {
point.x *= factor;
point.y *= factor;
}
if (radius < _bigNum) {
dx = point.x - x;
dy = point.y - y;
if (dx * dx + dy * dy > radius) {
point.x = x;
point.y = y;
}
}
return point;
};
}
if (_isArray(snap)) {
return function (p) {
var i = snap.length,
closest = 0,
minDist = _bigNum,
x,
y,
point,
dist;
while (--i > -1) {
point = snap[i];
x = point.x - p.x;
y = point.y - p.y;
dist = x * x + y * y;
if (dist < minDist) {
closest = i;
minDist = dist;
}
}
return minDist <= radius ? snap[closest] : p;
};
}
return function (n) {
return n;
};
},
calculateBounds = function calculateBounds() {
var bounds, targetBounds, snap, snapIsRaw;
hasBounds = false;
if (scrollProxy) {
scrollProxy.calibrate();
self.minX = minX = -scrollProxy.maxScrollLeft();
self.minY = minY = -scrollProxy.maxScrollTop();
self.maxX = maxX = self.maxY = maxY = 0;
hasBounds = true;
} else if (!!vars.bounds) {
bounds = _getBounds(vars.bounds, target.parentNode);
if (rotationMode) {
self.minX = minX = bounds.left;
self.maxX = maxX = bounds.left + bounds.width;
self.minY = minY = self.maxY = maxY = 0;
} else if (!_isUndefined(vars.bounds.maxX) || !_isUndefined(vars.bounds.maxY)) {
bounds = vars.bounds;
self.minX = minX = bounds.minX;
self.minY = minY = bounds.minY;
self.maxX = maxX = bounds.maxX;
self.maxY = maxY = bounds.maxY;
} else {
targetBounds = _getBounds(target, target.parentNode);
self.minX = minX = Math.round(getPropAsNum(xProp, "px") + bounds.left - targetBounds.left - 0.5);
self.minY = minY = Math.round(getPropAsNum(yProp, "px") + bounds.top - targetBounds.top - 0.5);
self.maxX = maxX = Math.round(minX + (bounds.width - targetBounds.width));
self.maxY = maxY = Math.round(minY + (bounds.height - targetBounds.height));
}
if (minX > maxX) {
self.minX = maxX;
self.maxX = maxX = minX;
minX = self.minX;
}
if (minY > maxY) {
self.minY = maxY;
self.maxY = maxY = minY;
minY = self.minY;
}
if (rotationMode) {
self.minRotation = minX;
self.maxRotation = maxX;
}
hasBounds = true;
}
if (vars.liveSnap) {
snap = vars.liveSnap === true ? vars.snap || {} : vars.liveSnap;
snapIsRaw = _isArray(snap) || _isFunction(snap);
if (rotationMode) {
snapX = buildSnapFunc(snapIsRaw ? snap : snap.rotation, minX, maxX, 1);
snapY = null;
} else {
if (snap.points) {
snapXY = buildPointSnapFunc(snapIsRaw ? snap : snap.points, minX, maxX, minY, maxY, snap.radius, scrollProxy ? -1 : 1);
} else {
if (allowX) {
snapX = buildSnapFunc(snapIsRaw ? snap : snap.x || snap.left || snap.scrollLeft, minX, maxX, scrollProxy ? -1 : 1);
}
if (allowY) {
snapY = buildSnapFunc(snapIsRaw ? snap : snap.y || snap.top || snap.scrollTop, minY, maxY, scrollProxy ? -1 : 1);
}
}
}
}
},
onThrowComplete = function onThrowComplete() {
self.isThrowing = false;
_dispatchEvent(self, "throwcomplete", "onThrowComplete");
},
onThrowInterrupt = function onThrowInterrupt() {
self.isThrowing = false;
},
animate = function animate(inertia, forceZeroVelocity) {
var snap, snapIsRaw, tween, overshootTolerance;
if (inertia && InertiaPlugin) {
if (inertia === true) {
snap = vars.snap || vars.liveSnap || {};
snapIsRaw = _isArray(snap) || _isFunction(snap);
inertia = {
resistance: (vars.throwResistance || vars.resistance || 1000) / (rotationMode ? 10 : 1)
};
if (rotationMode) {
inertia.rotation = _parseInertia(self, snapIsRaw ? snap : snap.rotation, maxX, minX, 1, forceZeroVelocity);
} else {
if (allowX) {
inertia[xProp] = _parseInertia(self, snapIsRaw ? snap : snap.points || snap.x || snap.left, maxX, minX, scrollProxy ? -1 : 1, forceZeroVelocity || self.lockedAxis === "x");
}
if (allowY) {
inertia[yProp] = _parseInertia(self, snapIsRaw ? snap : snap.points || snap.y || snap.top, maxY, minY, scrollProxy ? -1 : 1, forceZeroVelocity || self.lockedAxis === "y");
}
if (snap.points || _isArray(snap) && _isObject(snap[0])) {
inertia.linkedProps = xProp + "," + yProp;
inertia.radius = snap.radius;
}
}
}
self.isThrowing = true;
overshootTolerance = !isNaN(vars.overshootTolerance) ? vars.overshootTolerance : vars.edgeResistance === 1 ? 0 : 1 - self.edgeResistance + 0.2;
if (!inertia.duration) {
inertia.duration = {
max: Math.max(vars.minDuration || 0, "maxDuration" in vars ? vars.maxDuration : 2),
min: !isNaN(vars.minDuration) ? vars.minDuration : overshootTolerance === 0 || _isObject(inertia) && inertia.resistance > 1000 ? 0 : 0.5,
overshoot: overshootTolerance
};
}
self.tween = tween = gsap.to(scrollProxy || target, {
inertia: inertia,
data: "_draggable",
onComplete: onThrowComplete,
onInterrupt: onThrowInterrupt,
onUpdate: vars.fastMode ? _dispatchEvent : syncXY,
onUpdateParams: vars.fastMode ? [self, "onthrowupdate", "onThrowUpdate"] : snap && snap.radius ? [false, true] : []
});
if (!vars.fastMode) {
if (scrollProxy) {
scrollProxy._skip = true;
}
tween.render(1e9, true, true);
syncXY(true, true);
self.endX = self.x;
self.endY = self.y;
if (rotationMode) {
self.endRotation = self.x;
}
tween.play(0);
syncXY(true, true);
if (scrollProxy) {
scrollProxy._skip = false;
}
}
} else if (hasBounds) {
self.applyBounds();
}
},
updateMatrix = function updateMatrix(shiftStart) {
var start = matrix,
p;
matrix = getGlobalMatrix(target.parentNode, true);
if (shiftStart && self.isPressed && !matrix.equals(start || new Matrix2D())) {
p = start.inverse().apply({
x: startPointerX,
y: startPointerY
});
matrix.apply(p, p);
startPointerX = p.x;
startPointerY = p.y;
}
if (matrix.equals(_identityMatrix$1)) {
matrix = null;
}
},
recordStartPositions = function recordStartPositions() {
var edgeTolerance = 1 - self.edgeResistance,
offsetX = isFixed ? _getDocScrollLeft$1(ownerDoc) : 0,
offsetY = isFixed ? _getDocScrollTop$1(ownerDoc) : 0,
parsedOrigin,
x,
y;
updateMatrix(false);
_point1.x = self.pointerX - offsetX;
_point1.y = self.pointerY - offsetY;
matrix && matrix.apply(_point1, _point1);
startPointerX = _point1.x;
startPointerY = _point1.y;
if (dirty) {
setPointerPosition(self.pointerX, self.pointerY);
render(true);
}
if (scrollProxy) {
calculateBounds();
startElementY = scrollProxy.top();
startElementX = scrollProxy.left();
} else {
if (isTweening()) {
syncXY(true, true);
calculateBounds();
} else {
self.applyBounds();
}
if (rotationMode) {
parsedOrigin = target.ownerSVGElement ? [gsCache.xOrigin - target.getBBox().x, gsCache.yOrigin - target.getBBox().y] : (_getComputedStyle(target)[_transformOriginProp$1] || "0 0").split(" ");
rotationOrigin = self.rotationOrigin = getGlobalMatrix(target).apply({
x: parseFloat(parsedOrigin[0]) || 0,
y: parseFloat(parsedOrigin[1]) || 0
});
syncXY(true, true);
x = self.pointerX - rotationOrigin.x - offsetX;
y = rotationOrigin.y - self.pointerY + offsetY;
startElementX = self.x;
startElementY = self.y = Math.atan2(y, x) * _RAD2DEG;
} else {
startElementY = getPropAsNum(yProp, "px");
startElementX = getPropAsNum(xProp, "px");
}
}
if (hasBounds && edgeTolerance) {
if (startElementX > maxX) {
startElementX = maxX + (startElementX - maxX) / edgeTolerance;
} else if (startElementX < minX) {
startElementX = minX - (minX - startElementX) / edgeTolerance;
}
if (!rotationMode) {
if (startElementY > maxY) {
startElementY = maxY + (startElementY - maxY) / edgeTolerance;
} else if (startElementY < minY) {
startElementY = minY - (minY - startElementY) / edgeTolerance;
}
}
}
self.startX = startElementX;
self.startY = startElementY;
},
isTweening = function isTweening() {
return self.tween && self.tween.isActive();
},
removePlaceholder = function removePlaceholder() {
if (_placeholderDiv.parentNode && !isTweening() && !self.isDragging) {
_placeholderDiv.parentNode.removeChild(_placeholderDiv);
}
},
onPress = function onPress(e, force) {
var i;
if (!enabled || self.isPressed || !e || (e.type === "mousedown" || e.type === "pointerdown") && !force && _getTime() - clickTime < 30 && _touchEventLookup[self.pointerEvent.type]) {
isPreventingDefault && e && enabled && _preventDefault(e);
return;
}
interrupted = isTweening();
self.pointerEvent = e;
if (_touchEventLookup[e.type]) {
touchEventTarget = ~e.type.indexOf("touch") ? e.currentTarget || e.target : ownerDoc;
_addListener(touchEventTarget, "touchend", onRelease);
_addListener(touchEventTarget, "touchmove", onMove);
_addListener(touchEventTarget, "touchcancel", onRelease);
_addListener(ownerDoc, "touchstart", _onMultiTouchDocument);
} else {
touchEventTarget = null;
_addListener(ownerDoc, "mousemove", onMove);
}
touchDragAxis = null;
if (!_supportsPointer || !touchEventTarget) {
_addListener(ownerDoc, "mouseup", onRelease);
e && e.target && _addListener(e.target, "mouseup", onRelease);
}
isClicking = isClickable.call(self, e.target) && vars.dragClickables === false && !force;
if (isClicking) {
_addListener(e.target, "change", onRelease);
_dispatchEvent(self, "pressInit", "onPressInit");
_dispatchEvent(self, "press", "onPress");
_setSelectable(triggers, true);
isPreventingDefault = false;
return;
}
allowNativeTouchScrolling = !touchEventTarget || allowX === allowY || self.vars.allowNativeTouchScrolling === false || self.vars.allowContextMenu && e && (e.ctrlKey || e.which > 2) ? false : allowX ? "y" : "x";
isPreventingDefault = !allowNativeTouchScrolling && !self.allowEventDefault;
if (isPreventingDefault) {
_preventDefault(e);
_addListener(_win$1, "touchforcechange", _preventDefault);
}
if (e.changedTouches) {
e = touch = e.changedTouches[0];
touchID = e.identifier;
} else if (e.pointerId) {
touchID = e.pointerId;
} else {
touch = touchID = null;
}
_dragCount++;
_addToRenderQueue(render);
startPointerY = self.pointerY = e.pageY;
startPointerX = self.pointerX = e.pageX;
_dispatchEvent(self, "pressInit", "onPressInit");
if (allowNativeTouchScrolling || self.autoScroll) {
_recordMaxScrolls(target.parentNode);
}
if (target.parentNode && self.autoScroll && !scrollProxy && !rotationMode && target.parentNode._gsMaxScrollX && !_placeholderDiv.parentNode && !target.getBBox) {
_placeholderDiv.style.width = target.parentNode.scrollWidth + "px";
target.parentNode.appendChild(_placeholderDiv);
}
recordStartPositions();
self.tween && self.tween.kill();
self.isThrowing = false;
gsap.killTweensOf(scrollProxy || target, killProps, true);
scrollProxy && gsap.killTweensOf(target, {
scrollTo: 1
}, true);
self.tween = self.lockedAxis = null;
if (vars.zIndexBoost || !rotationMode && !scrollProxy && vars.zIndexBoost !== false) {
target.style.zIndex = Draggable.zIndex++;
}
self.isPressed = true;
hasDragCallback = !!(vars.onDrag || self._listeners.drag);
hasMoveCallback = !!(vars.onMove || self._listeners.move);
if (!rotationMode && (vars.cursor !== false || vars.activeCursor)) {
i = triggers.length;
while (--i > -1) {
gsap.set(triggers[i], {
cursor: vars.activeCursor || vars.cursor || (_defaultCursor === "grab" ? "grabbing" : _defaultCursor)
});
}
}
_dispatchEvent(self, "press", "onPress");
},
onMove = function onMove(e) {
var originalEvent = e,
touches,
pointerX,
pointerY,
i,
dx,
dy;
if (!enabled || _isMultiTouching || !self.isPressed || !e) {
isPreventingDefault && e && enabled && _preventDefault(e);
return;
}
self.pointerEvent = e;
touches = e.changedTouches;
if (touches) {
e = touches[0];
if (e !== touch && e.identifier !== touchID) {
i = touches.length;
while (--i > -1 && (e = touches[i]).identifier !== touchID && e.target !== target) {}
if (i < 0) {
return;
}
}
} else if (e.pointerId && touchID && e.pointerId !== touchID) {
return;
}
if (touchEventTarget && allowNativeTouchScrolling && !touchDragAxis) {
_point1.x = e.pageX;
_point1.y = e.pageY;
matrix && matrix.apply(_point1, _point1);
pointerX = _point1.x;
pointerY = _point1.y;
dx = Math.abs(pointerX - startPointerX);
dy = Math.abs(pointerY - startPointerY);
if (dx !== dy && (dx > minimumMovement || dy > minimumMovement) || _isAndroid && allowNativeTouchScrolling === touchDragAxis) {
touchDragAxis = dx > dy && allowX ? "x" : "y";
if (allowNativeTouchScrolling && touchDragAxis !== allowNativeTouchScrolling) {
_addListener(_win$1, "touchforcechange", _preventDefault);
}
if (self.vars.lockAxisOnTouchScroll !== false && allowX && allowY) {
self.lockedAxis = touchDragAxis === "x" ? "y" : "x";
_isFunction(self.vars.onLockAxis) && self.vars.onLockAxis.call(self, originalEvent);
}
if (_isAndroid && allowNativeTouchScrolling === touchDragAxis) {
onRelease(originalEvent);
return;
}
}
}
if (!self.allowEventDefault && (!allowNativeTouchScrolling || touchDragAxis && allowNativeTouchScrolling !== touchDragAxis) && originalEvent.cancelable !== false) {
_preventDefault(originalEvent);
isPreventingDefault = true;
} else if (isPreventingDefault) {
isPreventingDefault = false;
}
if (self.autoScroll) {
checkAutoScrollBounds = true;
}
setPointerPosition(e.pageX, e.pageY, hasMoveCallback);
},
setPointerPosition = function setPointerPosition(pointerX, pointerY, invokeOnMove) {
var dragTolerance = 1 - self.dragResistance,
edgeTolerance = 1 - self.edgeResistance,
prevPointerX = self.pointerX,
prevPointerY = self.pointerY,
prevStartElementY = startElementY,
prevX = self.x,
prevY = self.y,
prevEndX = self.endX,
prevEndY = self.endY,
prevEndRotation = self.endRotation,
prevDirty = dirty,
xChange,
yChange,
x,
y,
dif,
temp;
self.pointerX = pointerX;
self.pointerY = pointerY;
if (isFixed) {
pointerX -= _getDocScrollLeft$1(ownerDoc);
pointerY -= _getDocScrollTop$1(ownerDoc);
}
if (rotationMode) {
y = Math.atan2(rotationOrigin.y - pointerY, pointerX - rotationOrigin.x) * _RAD2DEG;
dif = self.y - y;
if (dif > 180) {
startElementY -= 360;
self.y = y;
} else if (dif < -180) {
startElementY += 360;
self.y = y;
}
if (self.x !== startElementX || Math.abs(startElementY - y) > minimumMovement) {
self.y = y;
x = startElementX + (startElementY - y) * dragTolerance;
} else {
x = startElementX;
}
} else {
if (matrix) {
temp = pointerX * matrix.a + pointerY * matrix.c + matrix.e;
pointerY = pointerX * matrix.b + pointerY * matrix.d + matrix.f;
pointerX = temp;
}
yChange = pointerY - startPointerY;
xChange = pointerX - startPointerX;
if (yChange < minimumMovement && yChange > -minimumMovement) {
yChange = 0;
}
if (xChange < minimumMovement && xChange > -minimumMovement) {
xChange = 0;
}
if ((self.lockAxis || self.lockedAxis) && (xChange || yChange)) {
temp = self.lockedAxis;
if (!temp) {
self.lockedAxis = temp = allowX && Math.abs(xChange) > Math.abs(yChange) ? "y" : allowY ? "x" : null;
if (temp && _isFunction(self.vars.onLockAxis)) {
self.vars.onLockAxis.call(self, self.pointerEvent);
}
}
if (temp === "y") {
yChange = 0;
} else if (temp === "x") {
xChange = 0;
}
}
x = _round(startElementX + xChange * dragTolerance);
y = _round(startElementY + yChange * dragTolerance);
}
if ((snapX || snapY || snapXY) && (self.x !== x || self.y !== y && !rotationMode)) {
if (snapXY) {
_temp1.x = x;
_temp1.y = y;
temp = snapXY(_temp1);
x = _round(temp.x);
y = _round(temp.y);
}
if (snapX) {
x = _round(snapX(x));
}
if (snapY) {
y = _round(snapY(y));
}
} else if (hasBounds) {
if (x > maxX) {
x = maxX + Math.round((x - maxX) * edgeTolerance);
} else if (x < minX) {
x = minX + Math.round((x - minX) * edgeTolerance);
}
if (!rotationMode) {
if (y > maxY) {
y = Math.round(maxY + (y - maxY) * edgeTolerance);
} else if (y < minY) {
y = Math.round(minY + (y - minY) * edgeTolerance);
}
}
}
if (self.x !== x || self.y !== y && !rotationMode) {
if (rotationMode) {
self.endRotation = self.x = self.endX = x;
dirty = true;
} else {
if (allowY) {
self.y = self.endY = y;
dirty = true;
}
if (allowX) {
self.x = self.endX = x;
dirty = true;
}
}
if (!invokeOnMove || _dispatchEvent(self, "move", "onMove") !== false) {
if (!self.isDragging && self.isPressed) {
self.isDragging = true;
_dispatchEvent(self, "dragstart", "onDragStart");
}
} else {
self.pointerX = prevPointerX;
self.pointerY = prevPointerY;
startElementY = prevStartElementY;
self.x = prevX;
self.y = prevY;
self.endX = prevEndX;
self.endY = prevEndY;
self.endRotation = prevEndRotation;
dirty = prevDirty;
}
}
},
onRelease = function onRelease(e, force) {
if (!enabled || !self.isPressed || e && touchID != null && !force && (e.pointerId && e.pointerId !== touchID && e.target !== target || e.changedTouches && !_hasTouchID(e.changedTouches, touchID))) {
isPreventingDefault && e && enabled && _preventDefault(e);
return;
}
self.isPressed = false;
var originalEvent = e,
wasDragging = self.isDragging,
isContextMenuRelease = self.vars.allowContextMenu && e && (e.ctrlKey || e.which > 2),
placeholderDelayedCall = gsap.delayedCall(0.001, removePlaceholder),
touches,
i,
syntheticEvent,
eventTarget,
syntheticClick;
if (touchEventTarget) {
_removeListener(touchEventTarget, "touchend", onRelease);
_removeListener(touchEventTarget, "touchmove", onMove);
_removeListener(touchEventTarget, "touchcancel", onRelease);
_removeListener(ownerDoc, "touchstart", _onMultiTouchDocument);
} else {
_removeListener(ownerDoc, "mousemove", onMove);
}
_removeListener(_win$1, "touchforcechange", _preventDefault);
if (!_supportsPointer || !touchEventTarget) {
_removeListener(ownerDoc, "mouseup", onRelease);
e && e.target && _removeListener(e.target, "mouseup", onRelease);
}
dirty = false;
if (isClicking && !isContextMenuRelease) {
if (e) {
_removeListener(e.target, "change", onRelease);
self.pointerEvent = originalEvent;
}
_setSelectable(triggers, false);
_dispatchEvent(self, "release", "onRelease");
_dispatchEvent(self, "click", "onClick");
isClicking = false;
return;
}
_removeFromRenderQueue(render);
if (!rotationMode) {
i = triggers.length;
while (--i > -1) {
_setStyle(triggers[i], "cursor", vars.cursor || (vars.cursor !== false ? _defaultCursor : null));
}
}
if (wasDragging) {
dragEndTime = _lastDragTime = _getTime();
self.isDragging = false;
}
_dragCount--;
if (e) {
touches = e.changedTouches;
if (touches) {
e = touches[0];
if (e !== touch && e.identifier !== touchID) {
i = touches.length;
while (--i > -1 && (e = touches[i]).identifier !== touchID && e.target !== target) {}
if (i < 0) {
return;
}
}
}
self.pointerEvent = originalEvent;
self.pointerX = e.pageX;
self.pointerY = e.pageY;
}
if (isContextMenuRelease && originalEvent) {
_preventDefault(originalEvent);
isPreventingDefault = true;
_dispatchEvent(self, "release", "onRelease");
} else if (originalEvent && !wasDragging) {
isPreventingDefault = false;
if (interrupted && (vars.snap || vars.bounds)) {
animate(vars.inertia || vars.throwProps);
}
_dispatchEvent(self, "release", "onRelease");
if ((!_isAndroid || originalEvent.type !== "touchmove") && originalEvent.type.indexOf("cancel") === -1) {
_dispatchEvent(self, "click", "onClick");
if (_getTime() - clickTime < 300) {
_dispatchEvent(self, "doubleclick", "onDoubleClick");
}
eventTarget = originalEvent.target || target;
clickTime = _getTime();
syntheticClick = function syntheticClick() {
if (clickTime !== clickDispatch && self.enabled() && !self.isPressed && !originalEvent.defaultPrevented) {
if (eventTarget.click) {
eventTarget.click();
} else if (ownerDoc.createEvent) {
syntheticEvent = ownerDoc.createEvent("MouseEvents");
syntheticEvent.initMouseEvent("click", true, true, _win$1, 1, self.pointerEvent.screenX, self.pointerEvent.screenY, self.pointerX, self.pointerY, false, false, false, false, 0, null);
eventTarget.dispatchEvent(syntheticEvent);
}
}
};
if (!_isAndroid && !originalEvent.defaultPrevented) {
gsap.delayedCall(0.05, syntheticClick);
}
}
} else {
animate(vars.inertia || vars.throwProps);
if (!self.allowEventDefault && originalEvent && (vars.dragClickables !== false || !isClickable.call(self, originalEvent.target)) && wasDragging && (!allowNativeTouchScrolling || touchDragAxis && allowNativeTouchScrolling === touchDragAxis) && originalEvent.cancelable !== false) {
isPreventingDefault = true;
_preventDefault(originalEvent);
} else {
isPreventingDefault = false;
}
_dispatchEvent(self, "release", "onRelease");
}
isTweening() && placeholderDelayedCall.duration(self.tween.duration());
wasDragging && _dispatchEvent(self, "dragend", "onDragEnd");
return true;
},
updateScroll = function updateScroll(e) {
if (e && self.isDragging && !scrollProxy) {
var parent = e.target || target.parentNode,
deltaX = parent.scrollLeft - parent._gsScrollX,
deltaY = parent.scrollTop - parent._gsScrollY;
if (deltaX || deltaY) {
if (matrix) {
startPointerX -= deltaX * matrix.a + deltaY * matrix.c;
startPointerY -= deltaY * matrix.d + deltaX * matrix.b;
} else {
startPointerX -= deltaX;
startPointerY -= deltaY;
}
parent._gsScrollX += deltaX;
parent._gsScrollY += deltaY;
setPointerPosition(self.pointerX, self.pointerY);
}
}
},
onClick = function onClick(e) {
var time = _getTime(),
recentlyClicked = time - clickTime < 40,
recentlyDragged = time - dragEndTime < 40,
alreadyDispatched = recentlyClicked && clickDispatch === clickTime,
defaultPrevented = self.pointerEvent && self.pointerEvent.defaultPrevented,
alreadyDispatchedTrusted = recentlyClicked && trustedClickDispatch === clickTime,
trusted = e.isTrusted || e.isTrusted == null && recentlyClicked && alreadyDispatched;
if ((alreadyDispatched || recentlyDragged && self.vars.suppressClickOnDrag !== false) && e.stopImmediatePropagation) {
e.stopImmediatePropagation();
}
if (recentlyClicked && !(self.pointerEvent && self.pointerEvent.defaultPrevented) && (!alreadyDispatched || trusted && !alreadyDispatchedTrusted)) {
if (trusted && alreadyDispatched) {
trustedClickDispatch = clickTime;
}
clickDispatch = clickTime;
return;
}
if (self.isPressed || recentlyDragged || recentlyClicked) {
if (!trusted || !e.detail || !recentlyClicked || defaultPrevented) {
_preventDefault(e);
}
}
if (!recentlyClicked && !recentlyDragged) {
e && e.target && (self.pointerEvent = e);
_dispatchEvent(self, "click", "onClick");
}
},
localizePoint = function localizePoint(p) {
return matrix ? {
x: p.x * matrix.a + p.y * matrix.c + matrix.e,
y: p.x * matrix.b + p.y * matrix.d + matrix.f
} : {
x: p.x,
y: p.y
};
};
old = Draggable.get(target);
old && old.kill();
_this2.startDrag = function (event, align) {
var r1, r2, p1, p2;
onPress(event || self.pointerEvent, true);
if (align && !self.hitTest(event || self.pointerEvent)) {
r1 = _parseRect(event || self.pointerEvent);
r2 = _parseRect(target);
p1 = localizePoint({
x: r1.left + r1.width / 2,
y: r1.top + r1.height / 2
});
p2 = localizePoint({
x: r2.left + r2.width / 2,
y: r2.top + r2.height / 2
});
startPointerX -= p1.x - p2.x;
startPointerY -= p1.y - p2.y;
}
if (!self.isDragging) {
self.isDragging = true;
_dispatchEvent(self, "dragstart", "onDragStart");
}
};
_this2.drag = onMove;
_this2.endDrag = function (e) {
return onRelease(e || self.pointerEvent, true);
};
_this2.timeSinceDrag = function () {
return self.isDragging ? 0 : (_getTime() - dragEndTime) / 1000;
};
_this2.timeSinceClick = function () {
return (_getTime() - clickTime) / 1000;
};
_this2.hitTest = function (target, threshold) {
return Draggable.hitTest(self.target, target, threshold);
};
_this2.getDirection = function (from, diagonalThreshold) {
var mode = from === "velocity" && InertiaPlugin ? from : _isObject(from) && !rotationMode ? "element" : "start",
xChange,
yChange,
ratio,
direction,
r1,
r2;
if (mode === "element") {
r1 = _parseRect(self.target);
r2 = _parseRect(from);
}
xChange = mode === "start" ? self.x - startElementX : mode === "velocity" ? InertiaPlugin.getVelocity(target, xProp) : r1.left + r1.width / 2 - (r2.left + r2.width / 2);
if (rotationMode) {
return xChange < 0 ? "counter-clockwise" : "clockwise";
} else {
diagonalThreshold = diagonalThreshold || 2;
yChange = mode === "start" ? self.y - startElementY : mode === "velocity" ? InertiaPlugin.getVelocity(target, yProp) : r1.top + r1.height / 2 - (r2.top + r2.height / 2);
ratio = Math.abs(xChange / yChange);
direction = ratio < 1 / diagonalThreshold ? "" : xChange < 0 ? "left" : "right";
if (ratio < diagonalThreshold) {
if (direction !== "") {
direction += "-";
}
direction += yChange < 0 ? "up" : "down";
}
}
return direction;
};
_this2.applyBounds = function (newBounds, sticky) {
var x, y, forceZeroVelocity, e, parent, isRoot;
if (newBounds && vars.bounds !== newBounds) {
vars.bounds = newBounds;
return self.update(true, sticky);
}
syncXY(true);
calculateBounds();
if (hasBounds && !isTweening()) {
x = self.x;
y = self.y;
if (x > maxX) {
x = maxX;
} else if (x < minX) {
x = minX;
}
if (y > maxY) {
y = maxY;
} else if (y < minY) {
y = minY;
}
if (self.x !== x || self.y !== y) {
forceZeroVelocity = true;
self.x = self.endX = x;
if (rotationMode) {
self.endRotation = x;
} else {
self.y = self.endY = y;
}
dirty = true;
render(true);
if (self.autoScroll && !self.isDragging) {
_recordMaxScrolls(target.parentNode);
e = target;
_windowProxy.scrollTop = _win$1.pageYOffset != null ? _win$1.pageYOffset : ownerDoc.documentElement.scrollTop != null ? ownerDoc.documentElement.scrollTop : ownerDoc.body.scrollTop;
_windowProxy.scrollLeft = _win$1.pageXOffset != null ? _win$1.pageXOffset : ownerDoc.documentElement.scrollLeft != null ? ownerDoc.documentElement.scrollLeft : ownerDoc.body.scrollLeft;
while (e && !isRoot) {
isRoot = _isRoot(e.parentNode);
parent = isRoot ? _windowProxy : e.parentNode;
if (allowY && parent.scrollTop > parent._gsMaxScrollY) {
parent.scrollTop = parent._gsMaxScrollY;
}
if (allowX && parent.scrollLeft > parent._gsMaxScrollX) {
parent.scrollLeft = parent._gsMaxScrollX;
}
e = parent;
}
}
}
if (self.isThrowing && (forceZeroVelocity || self.endX > maxX || self.endX < minX || self.endY > maxY || self.endY < minY)) {
animate(vars.inertia || vars.throwProps, forceZeroVelocity);
}
}
return self;
};
_this2.update = function (applyBounds, sticky, ignoreExternalChanges) {
var x = self.x,
y = self.y;
updateMatrix(!sticky);
if (applyBounds) {
self.applyBounds();
} else {
dirty && ignoreExternalChanges && render(true);
syncXY(true);
}
if (sticky) {
setPointerPosition(self.pointerX, self.pointerY);
dirty && render(true);
}
if (self.isPressed && !sticky && (allowX && Math.abs(x - self.x) > 0.01 || allowY && Math.abs(y - self.y) > 0.01 && !rotationMode)) {
recordStartPositions();
}
if (self.autoScroll) {
_recordMaxScrolls(target.parentNode, self.isDragging);
checkAutoScrollBounds = self.isDragging;
render(true);
_removeScrollListener(target, updateScroll);
_addScrollListener(target, updateScroll);
}
return self;
};
_this2.enable = function (type) {
var setVars = {
lazy: true
},
id,
i,
trigger;
if (!rotationMode && vars.cursor !== false) {
setVars.cursor = vars.cursor || _defaultCursor;
}
if (gsap.utils.checkPrefix("touchCallout")) {
setVars.touchCallout = "none";
}
if (type !== "soft") {
_setTouchActionForAllDescendants(triggers, allowX === allowY ? "none" : vars.allowNativeTouchScrolling && target.scrollHeight === target.clientHeight === (target.scrollWidth === target.clientHeight) || vars.allowEventDefault ? "manipulation" : allowX ? "pan-y" : "pan-x");
i = triggers.length;
while (--i > -1) {
trigger = triggers[i];
_supportsPointer || _addListener(trigger, "mousedown", onPress);
_addListener(trigger, "touchstart", onPress);
_addListener(trigger, "click", onClick, true);
gsap.set(trigger, setVars);
if (trigger.getBBox && trigger.ownerSVGElement) {
gsap.set(trigger.ownerSVGElement, {
touchAction: allowX === allowY ? "none" : vars.allowNativeTouchScrolling || vars.allowEventDefault ? "manipulation" : allowX ? "pan-y" : "pan-x"
});
}
vars.allowContextMenu || _addListener(trigger, "contextmenu", onContextMenu);
}
_setSelectable(triggers, false);
}
_addScrollListener(target, updateScroll);
enabled = true;
if (InertiaPlugin && type !== "soft") {
InertiaPlugin.track(scrollProxy || target, xyMode ? "x,y" : rotationMode ? "rotation" : "top,left");
}
target._gsDragID = id = "d" + _lookupCount++;
_lookup[id] = self;
if (scrollProxy) {
scrollProxy.enable();
scrollProxy.element._gsDragID = id;
}
(vars.bounds || rotationMode) && recordStartPositions();
vars.bounds && self.applyBounds();
return self;
};
_this2.disable = function (type) {
var dragging = self.isDragging,
i,
trigger;
if (!rotationMode) {
i = triggers.length;
while (--i > -1) {
_setStyle(triggers[i], "cursor", null);
}
}
if (type !== "soft") {
_setTouchActionForAllDescendants(triggers, null);
i = triggers.length;
while (--i > -1) {
trigger = triggers[i];
_setStyle(trigger, "touchCallout", null);
_removeListener(trigger, "mousedown", onPress);
_removeListener(trigger, "touchstart", onPress);
_removeListener(trigger, "click", onClick);
_removeListener(trigger, "contextmenu", onContextMenu);
}
_setSelectable(triggers, true);
if (touchEventTarget) {
_removeListener(touchEventTarget, "touchcancel", onRelease);
_removeListener(touchEventTarget, "touchend", onRelease);
_removeListener(touchEventTarget, "touchmove", onMove);
}
_removeListener(ownerDoc, "mouseup", onRelease);
_removeListener(ownerDoc, "mousemove", onMove);
}
_removeScrollListener(target, updateScroll);
enabled = false;
InertiaPlugin && type !== "soft" && InertiaPlugin.untrack(scrollProxy || target, xyMode ? "x,y" : rotationMode ? "rotation" : "top,left");
scrollProxy && scrollProxy.disable();
_removeFromRenderQueue(render);
self.isDragging = self.isPressed = isClicking = false;
dragging && _dispatchEvent(self, "dragend", "onDragEnd");
return self;
};
_this2.enabled = function (value, type) {
return arguments.length ? value ? self.enable(type) : self.disable(type) : enabled;
};
_this2.kill = function () {
self.isThrowing = false;
self.tween && self.tween.kill();
self.disable();
gsap.set(triggers, {
clearProps: "userSelect"
});
delete _lookup[target._gsDragID];
return self;
};
if (~type.indexOf("scroll")) {
scrollProxy = _this2.scrollProxy = new ScrollProxy(target, _extend({
onKill: function onKill() {
self.isPressed && onRelease(null);
}
}, vars));
target.style.overflowY = allowY && !_isTouchDevice ? "auto" : "hidden";
target.style.overflowX = allowX && !_isTouchDevice ? "auto" : "hidden";
target = scrollProxy.content;
}
if (rotationMode) {
killProps.rotation = 1;
} else {
if (allowX) {
killProps[xProp] = 1;
}
if (allowY) {
killProps[yProp] = 1;
}
}
gsCache.force3D = "force3D" in vars ? vars.force3D : true;
_this2.enable();
return _this2;
}
Draggable.register = function register(core) {
gsap = core;
_initCore();
};
Draggable.create = function create(targets, vars) {
_coreInitted || _initCore(true);
return _toArray(targets).map(function (target) {
return new Draggable(target, vars);
});
};
Draggable.get = function get(target) {
return _lookup[(_toArray(target)[0] || {})._gsDragID];
};
Draggable.timeSinceDrag = function timeSinceDrag() {
return (_getTime() - _lastDragTime) / 1000;
};
Draggable.hitTest = function hitTest(obj1, obj2, threshold) {
if (obj1 === obj2) {
return false;
}
var r1 = _parseRect(obj1),
r2 = _parseRect(obj2),
top = r1.top,
left = r1.left,
right = r1.right,
bottom = r1.bottom,
width = r1.width,
height = r1.height,
isOutside = r2.left > right || r2.right < left || r2.top > bottom || r2.bottom < top,
overlap,
area,
isRatio;
if (isOutside || !threshold) {
return !isOutside;
}
isRatio = (threshold + "").indexOf("%") !== -1;
threshold = parseFloat(threshold) || 0;
overlap = {
left: Math.max(left, r2.left),
top: Math.max(top, r2.top)
};
overlap.width = Math.min(right, r2.right) - overlap.left;
overlap.height = Math.min(bottom, r2.bottom) - overlap.top;
if (overlap.width < 0 || overlap.height < 0) {
return false;
}
if (isRatio) {
threshold *= 0.01;
area = overlap.width * overlap.height;
return area >= width * height * threshold || area >= r2.width * r2.height * threshold;
}
return overlap.width > threshold && overlap.height > threshold;
};
return Draggable;
}(EventDispatcher);
_setDefaults(Draggable.prototype, {
pointerX: 0,
pointerY: 0,
startX: 0,
startY: 0,
deltaX: 0,
deltaY: 0,
isDragging: false,
isPressed: false
});
Draggable.zIndex = 1000;
Draggable.version = "3.6.0";
_getGSAP() && gsap.registerPlugin(Draggable);
exports.Draggable = Draggable;
exports.default = Draggable;
if (typeof(window) === 'undefined' || window !== exports) {Object.defineProperty(exports, '__esModule', { value: true });} else {delete window.default;}
})));
|
/**
* auth0-js v9.11.3
* Author: Auth0
* Date: 2019-08-05
* License: MIT
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = global || self, global.CordovaAuth0Plugin = factory());
}(this, function () { 'use strict';
var version = { raw: '9.11.3' };
var toString = Object.prototype.toString;
function attribute(o, attr, type, text) {
type = type === 'array' ? 'object' : type;
if (o && typeof o[attr] !== type) {
throw new Error(text);
}
}
function variable(o, type, text) {
if (typeof o !== type) {
throw new Error(text);
}
}
function value(o, values, text) {
if (values.indexOf(o) === -1) {
throw new Error(text);
}
}
function check(o, config, attributes) {
if (!config.optional || o) {
variable(o, config.type, config.message);
}
if (config.type === 'object' && attributes) {
var keys = Object.keys(attributes);
for (var index = 0; index < keys.length; index++) {
var a = keys[index];
if (!attributes[a].optional || o[a]) {
if (!attributes[a].condition || attributes[a].condition(o)) {
attribute(o, a, attributes[a].type, attributes[a].message);
if (attributes[a].values) {
value(o[a], attributes[a].values, attributes[a].value_message);
}
}
}
}
}
}
/**
* Wrap `Array.isArray` Polyfill for IE9
* source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray
*
* @param {Array} array
* @private
*/
function isArray(array) {
if (this.supportsIsArray()) {
return Array.isArray(array);
}
return toString.call(array) === '[object Array]';
}
function supportsIsArray() {
return Array.isArray != null;
}
var assert = {
check: check,
attribute: attribute,
variable: variable,
value: value,
isArray: isArray,
supportsIsArray: supportsIsArray
};
/* eslint-disable no-continue */
function get() {
if (!Object.assign) {
return objectAssignPolyfill;
}
return Object.assign;
}
function objectAssignPolyfill(target) {
if (target === undefined || target === null) {
throw new TypeError('Cannot convert first argument to object');
}
var to = Object(target);
for (var i = 1; i < arguments.length; i++) {
var nextSource = arguments[i];
if (nextSource === undefined || nextSource === null) {
continue;
}
var keysArray = Object.keys(Object(nextSource));
for (
var nextIndex = 0, len = keysArray.length;
nextIndex < len;
nextIndex++
) {
var nextKey = keysArray[nextIndex];
var desc = Object.getOwnPropertyDescriptor(nextSource, nextKey);
if (desc !== undefined && desc.enumerable) {
to[nextKey] = nextSource[nextKey];
}
}
}
return to;
}
var objectAssign = {
get: get,
objectAssignPolyfill: objectAssignPolyfill
};
/* eslint-disable no-param-reassign */
function pick(object, keys) {
return keys.reduce(function(prev, key) {
if (object[key]) {
prev[key] = object[key];
}
return prev;
}, {});
}
function getKeysNotIn(obj, allowedKeys) {
var notAllowed = [];
for (var key in obj) {
if (allowedKeys.indexOf(key) === -1) {
notAllowed.push(key);
}
}
return notAllowed;
}
function objectValues(obj) {
var values = [];
for (var key in obj) {
values.push(obj[key]);
}
return values;
}
function extend() {
var params = objectValues(arguments);
params.unshift({});
return objectAssign.get().apply(undefined, params);
}
function merge(object, keys) {
return {
base: keys ? pick(object, keys) : object,
with: function(object2, keys2) {
object2 = keys2 ? pick(object2, keys2) : object2;
return extend(this.base, object2);
}
};
}
function blacklist(object, blacklistedKeys) {
return Object.keys(object).reduce(function(p, key) {
if (blacklistedKeys.indexOf(key) === -1) {
p[key] = object[key];
}
return p;
}, {});
}
function camelToSnake(str) {
var newKey = '';
var index = 0;
var code;
var wasPrevNumber = true;
var wasPrevUppercase = true;
while (index < str.length) {
code = str.charCodeAt(index);
if (
(!wasPrevUppercase && code >= 65 && code <= 90) ||
(!wasPrevNumber && code >= 48 && code <= 57)
) {
newKey += '_';
newKey += str[index].toLowerCase();
} else {
newKey += str[index].toLowerCase();
}
wasPrevNumber = code >= 48 && code <= 57;
wasPrevUppercase = code >= 65 && code <= 90;
index++;
}
return newKey;
}
function snakeToCamel(str) {
var parts = str.split('_');
return parts.reduce(function(p, c) {
return p + c.charAt(0).toUpperCase() + c.slice(1);
}, parts.shift());
}
function toSnakeCase(object, exceptions) {
if (typeof object !== 'object' || assert.isArray(object) || object === null) {
return object;
}
exceptions = exceptions || [];
return Object.keys(object).reduce(function(p, key) {
var newKey = exceptions.indexOf(key) === -1 ? camelToSnake(key) : key;
p[newKey] = toSnakeCase(object[key]);
return p;
}, {});
}
function toCamelCase(object, exceptions, options) {
if (typeof object !== 'object' || assert.isArray(object) || object === null) {
return object;
}
exceptions = exceptions || [];
options = options || {};
return Object.keys(object).reduce(function(p, key) {
var newKey = exceptions.indexOf(key) === -1 ? snakeToCamel(key) : key;
p[newKey] = toCamelCase(object[newKey] || object[key], [], options);
if (options.keepOriginal) {
p[key] = toCamelCase(object[key], [], options);
}
return p;
}, {});
}
function getLocationFromUrl(href) {
var match = href.match(
/^(https?:|file:)\/\/(([^:/?#]*)(?::([0-9]+))?)([/]{0,1}[^?#]*)(\?[^#]*|)(#.*|)$/
);
return (
match && {
href: href,
protocol: match[1],
host: match[2],
hostname: match[3],
port: match[4],
pathname: match[5],
search: match[6],
hash: match[7]
}
);
}
function getOriginFromUrl(url) {
if (!url) {
return undefined;
}
var parsed = getLocationFromUrl(url);
var origin = parsed.protocol + '//' + parsed.hostname;
if (parsed.port) {
origin += ':' + parsed.port;
}
return origin;
}
function trim(options, key) {
var trimmed = extend(options);
if (options[key]) {
trimmed[key] = options[key].trim();
}
return trimmed;
}
function trimMultiple(options, keys) {
return keys.reduce(trim, options);
}
function trimUserDetails(options) {
return trimMultiple(options, ['username', 'email', 'phoneNumber']);
}
var objectHelper = {
toSnakeCase: toSnakeCase,
toCamelCase: toCamelCase,
blacklist: blacklist,
merge: merge,
pick: pick,
getKeysNotIn: getKeysNotIn,
extend: extend,
getOriginFromUrl: getOriginFromUrl,
getLocationFromUrl: getLocationFromUrl,
trimUserDetails: trimUserDetails
};
function redirect(url) {
getWindow().location = url;
}
function getDocument() {
return getWindow().document;
}
function getWindow() {
return window;
}
function getOrigin() {
var location = getWindow().location;
var origin = location.origin;
if (!origin) {
origin = objectHelper.getOriginFromUrl(location.href);
}
return origin;
}
var windowHandler = {
redirect: redirect,
getDocument: getDocument,
getWindow: getWindow,
getOrigin: getOrigin
};
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
function createCommonjsModule(fn, module) {
return module = { exports: {} }, fn(module, module.exports), module.exports;
}
var urlJoin = createCommonjsModule(function (module) {
(function (name, context, definition) {
if ( module.exports) module.exports = definition();
else context[name] = definition();
})('urljoin', commonjsGlobal, function () {
function normalize (strArray) {
var resultArray = [];
if (strArray.length === 0) { return ''; }
if (typeof strArray[0] !== 'string') {
throw new TypeError('Url must be a string. Received ' + strArray[0]);
}
// If the first part is a plain protocol, we combine it with the next part.
if (strArray[0].match(/^[^/:]+:\/*$/) && strArray.length > 1) {
var first = strArray.shift();
strArray[0] = first + strArray[0];
}
// There must be two or three slashes in the file protocol, two slashes in anything else.
if (strArray[0].match(/^file:\/\/\//)) {
strArray[0] = strArray[0].replace(/^([^/:]+):\/*/, '$1:///');
} else {
strArray[0] = strArray[0].replace(/^([^/:]+):\/*/, '$1://');
}
for (var i = 0; i < strArray.length; i++) {
var component = strArray[i];
if (typeof component !== 'string') {
throw new TypeError('Url must be a string. Received ' + component);
}
if (component === '') { continue; }
if (i > 0) {
// Removing the starting slashes for each component but the first.
component = component.replace(/^[\/]+/, '');
}
if (i < strArray.length - 1) {
// Removing the ending slashes for each component but the last.
component = component.replace(/[\/]+$/, '');
} else {
// For the last component we will combine multiple slashes to a single one.
component = component.replace(/[\/]+$/, '/');
}
resultArray.push(component);
}
var str = resultArray.join('/');
// Each input component is now separated by a single slash except the possible first plain protocol part.
// remove trailing slash before parameters or hash
str = str.replace(/\/(\?|&|#[^!])/g, '$1');
// replace ? in parameters with &
var parts = str.split('?');
str = parts.shift() + (parts.length > 0 ? '?': '') + parts.join('&');
return str;
}
return function () {
var input;
if (typeof arguments[0] === 'object') {
input = arguments[0];
} else {
input = [].slice.call(arguments);
}
return normalize(input);
};
});
});
var has = Object.prototype.hasOwnProperty;
var isArray$1 = Array.isArray;
var hexTable = (function () {
var array = [];
for (var i = 0; i < 256; ++i) {
array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase());
}
return array;
}());
var compactQueue = function compactQueue(queue) {
while (queue.length > 1) {
var item = queue.pop();
var obj = item.obj[item.prop];
if (isArray$1(obj)) {
var compacted = [];
for (var j = 0; j < obj.length; ++j) {
if (typeof obj[j] !== 'undefined') {
compacted.push(obj[j]);
}
}
item.obj[item.prop] = compacted;
}
}
};
var arrayToObject = function arrayToObject(source, options) {
var obj = options && options.plainObjects ? Object.create(null) : {};
for (var i = 0; i < source.length; ++i) {
if (typeof source[i] !== 'undefined') {
obj[i] = source[i];
}
}
return obj;
};
var merge$1 = function merge(target, source, options) {
if (!source) {
return target;
}
if (typeof source !== 'object') {
if (isArray$1(target)) {
target.push(source);
} else if (target && typeof target === 'object') {
if ((options && (options.plainObjects || options.allowPrototypes)) || !has.call(Object.prototype, source)) {
target[source] = true;
}
} else {
return [target, source];
}
return target;
}
if (!target || typeof target !== 'object') {
return [target].concat(source);
}
var mergeTarget = target;
if (isArray$1(target) && !isArray$1(source)) {
mergeTarget = arrayToObject(target, options);
}
if (isArray$1(target) && isArray$1(source)) {
source.forEach(function (item, i) {
if (has.call(target, i)) {
var targetItem = target[i];
if (targetItem && typeof targetItem === 'object' && item && typeof item === 'object') {
target[i] = merge(targetItem, item, options);
} else {
target.push(item);
}
} else {
target[i] = item;
}
});
return target;
}
return Object.keys(source).reduce(function (acc, key) {
var value = source[key];
if (has.call(acc, key)) {
acc[key] = merge(acc[key], value, options);
} else {
acc[key] = value;
}
return acc;
}, mergeTarget);
};
var assign = function assignSingleSource(target, source) {
return Object.keys(source).reduce(function (acc, key) {
acc[key] = source[key];
return acc;
}, target);
};
var decode = function (str, decoder, charset) {
var strWithoutPlus = str.replace(/\+/g, ' ');
if (charset === 'iso-8859-1') {
// unescape never throws, no try...catch needed:
return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape);
}
// utf-8
try {
return decodeURIComponent(strWithoutPlus);
} catch (e) {
return strWithoutPlus;
}
};
var encode = function encode(str, defaultEncoder, charset) {
// This code was originally written by Brian White (mscdex) for the io.js core querystring library.
// It has been adapted here for stricter adherence to RFC 3986
if (str.length === 0) {
return str;
}
var string = typeof str === 'string' ? str : String(str);
if (charset === 'iso-8859-1') {
return escape(string).replace(/%u[0-9a-f]{4}/gi, function ($0) {
return '%26%23' + parseInt($0.slice(2), 16) + '%3B';
});
}
var out = '';
for (var i = 0; i < string.length; ++i) {
var c = string.charCodeAt(i);
if (
c === 0x2D // -
|| c === 0x2E // .
|| c === 0x5F // _
|| c === 0x7E // ~
|| (c >= 0x30 && c <= 0x39) // 0-9
|| (c >= 0x41 && c <= 0x5A) // a-z
|| (c >= 0x61 && c <= 0x7A) // A-Z
) {
out += string.charAt(i);
continue;
}
if (c < 0x80) {
out = out + hexTable[c];
continue;
}
if (c < 0x800) {
out = out + (hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]);
continue;
}
if (c < 0xD800 || c >= 0xE000) {
out = out + (hexTable[0xE0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]);
continue;
}
i += 1;
c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF));
out += hexTable[0xF0 | (c >> 18)]
+ hexTable[0x80 | ((c >> 12) & 0x3F)]
+ hexTable[0x80 | ((c >> 6) & 0x3F)]
+ hexTable[0x80 | (c & 0x3F)];
}
return out;
};
var compact = function compact(value) {
var queue = [{ obj: { o: value }, prop: 'o' }];
var refs = [];
for (var i = 0; i < queue.length; ++i) {
var item = queue[i];
var obj = item.obj[item.prop];
var keys = Object.keys(obj);
for (var j = 0; j < keys.length; ++j) {
var key = keys[j];
var val = obj[key];
if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) {
queue.push({ obj: obj, prop: key });
refs.push(val);
}
}
}
compactQueue(queue);
return value;
};
var isRegExp = function isRegExp(obj) {
return Object.prototype.toString.call(obj) === '[object RegExp]';
};
var isBuffer = function isBuffer(obj) {
if (!obj || typeof obj !== 'object') {
return false;
}
return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj));
};
var combine = function combine(a, b) {
return [].concat(a, b);
};
var utils = {
arrayToObject: arrayToObject,
assign: assign,
combine: combine,
compact: compact,
decode: decode,
encode: encode,
isBuffer: isBuffer,
isRegExp: isRegExp,
merge: merge$1
};
var replace = String.prototype.replace;
var percentTwenties = /%20/g;
var formats = {
'default': 'RFC3986',
formatters: {
RFC1738: function (value) {
return replace.call(value, percentTwenties, '+');
},
RFC3986: function (value) {
return value;
}
},
RFC1738: 'RFC1738',
RFC3986: 'RFC3986'
};
var has$1 = Object.prototype.hasOwnProperty;
var arrayPrefixGenerators = {
brackets: function brackets(prefix) { // eslint-disable-line func-name-matching
return prefix + '[]';
},
comma: 'comma',
indices: function indices(prefix, key) { // eslint-disable-line func-name-matching
return prefix + '[' + key + ']';
},
repeat: function repeat(prefix) { // eslint-disable-line func-name-matching
return prefix;
}
};
var isArray$2 = Array.isArray;
var push = Array.prototype.push;
var pushToArray = function (arr, valueOrArray) {
push.apply(arr, isArray$2(valueOrArray) ? valueOrArray : [valueOrArray]);
};
var toISO = Date.prototype.toISOString;
var defaults = {
addQueryPrefix: false,
allowDots: false,
charset: 'utf-8',
charsetSentinel: false,
delimiter: '&',
encode: true,
encoder: utils.encode,
encodeValuesOnly: false,
formatter: formats.formatters[formats['default']],
// deprecated
indices: false,
serializeDate: function serializeDate(date) { // eslint-disable-line func-name-matching
return toISO.call(date);
},
skipNulls: false,
strictNullHandling: false
};
var stringify = function stringify( // eslint-disable-line func-name-matching
object,
prefix,
generateArrayPrefix,
strictNullHandling,
skipNulls,
encoder,
filter,
sort,
allowDots,
serializeDate,
formatter,
encodeValuesOnly,
charset
) {
var obj = object;
if (typeof filter === 'function') {
obj = filter(prefix, obj);
} else if (obj instanceof Date) {
obj = serializeDate(obj);
} else if (generateArrayPrefix === 'comma' && isArray$2(obj)) {
obj = obj.join(',');
}
if (obj === null) {
if (strictNullHandling) {
return encoder && !encodeValuesOnly ? encoder(prefix, defaults.encoder, charset) : prefix;
}
obj = '';
}
if (typeof obj === 'string' || typeof obj === 'number' || typeof obj === 'boolean' || utils.isBuffer(obj)) {
if (encoder) {
var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder, charset);
return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults.encoder, charset))];
}
return [formatter(prefix) + '=' + formatter(String(obj))];
}
var values = [];
if (typeof obj === 'undefined') {
return values;
}
var objKeys;
if (isArray$2(filter)) {
objKeys = filter;
} else {
var keys = Object.keys(obj);
objKeys = sort ? keys.sort(sort) : keys;
}
for (var i = 0; i < objKeys.length; ++i) {
var key = objKeys[i];
if (skipNulls && obj[key] === null) {
continue;
}
if (isArray$2(obj)) {
pushToArray(values, stringify(
obj[key],
typeof generateArrayPrefix === 'function' ? generateArrayPrefix(prefix, key) : prefix,
generateArrayPrefix,
strictNullHandling,
skipNulls,
encoder,
filter,
sort,
allowDots,
serializeDate,
formatter,
encodeValuesOnly,
charset
));
} else {
pushToArray(values, stringify(
obj[key],
prefix + (allowDots ? '.' + key : '[' + key + ']'),
generateArrayPrefix,
strictNullHandling,
skipNulls,
encoder,
filter,
sort,
allowDots,
serializeDate,
formatter,
encodeValuesOnly,
charset
));
}
}
return values;
};
var normalizeStringifyOptions = function normalizeStringifyOptions(opts) {
if (!opts) {
return defaults;
}
if (opts.encoder !== null && opts.encoder !== undefined && typeof opts.encoder !== 'function') {
throw new TypeError('Encoder has to be a function.');
}
var charset = opts.charset || defaults.charset;
if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') {
throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined');
}
var format = formats['default'];
if (typeof opts.format !== 'undefined') {
if (!has$1.call(formats.formatters, opts.format)) {
throw new TypeError('Unknown format option provided.');
}
format = opts.format;
}
var formatter = formats.formatters[format];
var filter = defaults.filter;
if (typeof opts.filter === 'function' || isArray$2(opts.filter)) {
filter = opts.filter;
}
return {
addQueryPrefix: typeof opts.addQueryPrefix === 'boolean' ? opts.addQueryPrefix : defaults.addQueryPrefix,
allowDots: typeof opts.allowDots === 'undefined' ? defaults.allowDots : !!opts.allowDots,
charset: charset,
charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel,
delimiter: typeof opts.delimiter === 'undefined' ? defaults.delimiter : opts.delimiter,
encode: typeof opts.encode === 'boolean' ? opts.encode : defaults.encode,
encoder: typeof opts.encoder === 'function' ? opts.encoder : defaults.encoder,
encodeValuesOnly: typeof opts.encodeValuesOnly === 'boolean' ? opts.encodeValuesOnly : defaults.encodeValuesOnly,
filter: filter,
formatter: formatter,
serializeDate: typeof opts.serializeDate === 'function' ? opts.serializeDate : defaults.serializeDate,
skipNulls: typeof opts.skipNulls === 'boolean' ? opts.skipNulls : defaults.skipNulls,
sort: typeof opts.sort === 'function' ? opts.sort : null,
strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling
};
};
var stringify_1 = function (object, opts) {
var obj = object;
var options = normalizeStringifyOptions(opts);
var objKeys;
var filter;
if (typeof options.filter === 'function') {
filter = options.filter;
obj = filter('', obj);
} else if (isArray$2(options.filter)) {
filter = options.filter;
objKeys = filter;
}
var keys = [];
if (typeof obj !== 'object' || obj === null) {
return '';
}
var arrayFormat;
if (opts && opts.arrayFormat in arrayPrefixGenerators) {
arrayFormat = opts.arrayFormat;
} else if (opts && 'indices' in opts) {
arrayFormat = opts.indices ? 'indices' : 'repeat';
} else {
arrayFormat = 'indices';
}
var generateArrayPrefix = arrayPrefixGenerators[arrayFormat];
if (!objKeys) {
objKeys = Object.keys(obj);
}
if (options.sort) {
objKeys.sort(options.sort);
}
for (var i = 0; i < objKeys.length; ++i) {
var key = objKeys[i];
if (options.skipNulls && obj[key] === null) {
continue;
}
pushToArray(keys, stringify(
obj[key],
key,
generateArrayPrefix,
options.strictNullHandling,
options.skipNulls,
options.encode ? options.encoder : null,
options.filter,
options.sort,
options.allowDots,
options.serializeDate,
options.formatter,
options.encodeValuesOnly,
options.charset
));
}
var joined = keys.join(options.delimiter);
var prefix = options.addQueryPrefix === true ? '?' : '';
if (options.charsetSentinel) {
if (options.charset === 'iso-8859-1') {
// encodeURIComponent('✓'), the "numeric entity" representation of a checkmark
prefix += 'utf8=%26%2310003%3B&';
} else {
// encodeURIComponent('✓')
prefix += 'utf8=%E2%9C%93&';
}
}
return joined.length > 0 ? prefix + joined : '';
};
var has$2 = Object.prototype.hasOwnProperty;
var defaults$1 = {
allowDots: false,
allowPrototypes: false,
arrayLimit: 20,
charset: 'utf-8',
charsetSentinel: false,
comma: false,
decoder: utils.decode,
delimiter: '&',
depth: 5,
ignoreQueryPrefix: false,
interpretNumericEntities: false,
parameterLimit: 1000,
parseArrays: true,
plainObjects: false,
strictNullHandling: false
};
var interpretNumericEntities = function (str) {
return str.replace(/&#(\d+);/g, function ($0, numberStr) {
return String.fromCharCode(parseInt(numberStr, 10));
});
};
// This is what browsers will submit when the ✓ character occurs in an
// application/x-www-form-urlencoded body and the encoding of the page containing
// the form is iso-8859-1, or when the submitted form has an accept-charset
// attribute of iso-8859-1. Presumably also with other charsets that do not contain
// the ✓ character, such as us-ascii.
var isoSentinel = 'utf8=%26%2310003%3B'; // encodeURIComponent('✓')
// These are the percent-encoded utf-8 octets representing a checkmark, indicating that the request actually is utf-8 encoded.
var charsetSentinel = 'utf8=%E2%9C%93'; // encodeURIComponent('✓')
var parseValues = function parseQueryStringValues(str, options) {
var obj = {};
var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, '') : str;
var limit = options.parameterLimit === Infinity ? undefined : options.parameterLimit;
var parts = cleanStr.split(options.delimiter, limit);
var skipIndex = -1; // Keep track of where the utf8 sentinel was found
var i;
var charset = options.charset;
if (options.charsetSentinel) {
for (i = 0; i < parts.length; ++i) {
if (parts[i].indexOf('utf8=') === 0) {
if (parts[i] === charsetSentinel) {
charset = 'utf-8';
} else if (parts[i] === isoSentinel) {
charset = 'iso-8859-1';
}
skipIndex = i;
i = parts.length; // The eslint settings do not allow break;
}
}
}
for (i = 0; i < parts.length; ++i) {
if (i === skipIndex) {
continue;
}
var part = parts[i];
var bracketEqualsPos = part.indexOf(']=');
var pos = bracketEqualsPos === -1 ? part.indexOf('=') : bracketEqualsPos + 1;
var key, val;
if (pos === -1) {
key = options.decoder(part, defaults$1.decoder, charset);
val = options.strictNullHandling ? null : '';
} else {
key = options.decoder(part.slice(0, pos), defaults$1.decoder, charset);
val = options.decoder(part.slice(pos + 1), defaults$1.decoder, charset);
}
if (val && options.interpretNumericEntities && charset === 'iso-8859-1') {
val = interpretNumericEntities(val);
}
if (val && options.comma && val.indexOf(',') > -1) {
val = val.split(',');
}
if (has$2.call(obj, key)) {
obj[key] = utils.combine(obj[key], val);
} else {
obj[key] = val;
}
}
return obj;
};
var parseObject = function (chain, val, options) {
var leaf = val;
for (var i = chain.length - 1; i >= 0; --i) {
var obj;
var root = chain[i];
if (root === '[]' && options.parseArrays) {
obj = [].concat(leaf);
} else {
obj = options.plainObjects ? Object.create(null) : {};
var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root;
var index = parseInt(cleanRoot, 10);
if (!options.parseArrays && cleanRoot === '') {
obj = { 0: leaf };
} else if (
!isNaN(index)
&& root !== cleanRoot
&& String(index) === cleanRoot
&& index >= 0
&& (options.parseArrays && index <= options.arrayLimit)
) {
obj = [];
obj[index] = leaf;
} else {
obj[cleanRoot] = leaf;
}
}
leaf = obj;
}
return leaf;
};
var parseKeys = function parseQueryStringKeys(givenKey, val, options) {
if (!givenKey) {
return;
}
// Transform dot notation to bracket notation
var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, '[$1]') : givenKey;
// The regex chunks
var brackets = /(\[[^[\]]*])/;
var child = /(\[[^[\]]*])/g;
// Get the parent
var segment = brackets.exec(key);
var parent = segment ? key.slice(0, segment.index) : key;
// Stash the parent if it exists
var keys = [];
if (parent) {
// If we aren't using plain objects, optionally prefix keys that would overwrite object prototype properties
if (!options.plainObjects && has$2.call(Object.prototype, parent)) {
if (!options.allowPrototypes) {
return;
}
}
keys.push(parent);
}
// Loop through children appending to the array until we hit depth
var i = 0;
while ((segment = child.exec(key)) !== null && i < options.depth) {
i += 1;
if (!options.plainObjects && has$2.call(Object.prototype, segment[1].slice(1, -1))) {
if (!options.allowPrototypes) {
return;
}
}
keys.push(segment[1]);
}
// If there's a remainder, just add whatever is left
if (segment) {
keys.push('[' + key.slice(segment.index) + ']');
}
return parseObject(keys, val, options);
};
var normalizeParseOptions = function normalizeParseOptions(opts) {
if (!opts) {
return defaults$1;
}
if (opts.decoder !== null && opts.decoder !== undefined && typeof opts.decoder !== 'function') {
throw new TypeError('Decoder has to be a function.');
}
if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') {
throw new Error('The charset option must be either utf-8, iso-8859-1, or undefined');
}
var charset = typeof opts.charset === 'undefined' ? defaults$1.charset : opts.charset;
return {
allowDots: typeof opts.allowDots === 'undefined' ? defaults$1.allowDots : !!opts.allowDots,
allowPrototypes: typeof opts.allowPrototypes === 'boolean' ? opts.allowPrototypes : defaults$1.allowPrototypes,
arrayLimit: typeof opts.arrayLimit === 'number' ? opts.arrayLimit : defaults$1.arrayLimit,
charset: charset,
charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults$1.charsetSentinel,
comma: typeof opts.comma === 'boolean' ? opts.comma : defaults$1.comma,
decoder: typeof opts.decoder === 'function' ? opts.decoder : defaults$1.decoder,
delimiter: typeof opts.delimiter === 'string' || utils.isRegExp(opts.delimiter) ? opts.delimiter : defaults$1.delimiter,
depth: typeof opts.depth === 'number' ? opts.depth : defaults$1.depth,
ignoreQueryPrefix: opts.ignoreQueryPrefix === true,
interpretNumericEntities: typeof opts.interpretNumericEntities === 'boolean' ? opts.interpretNumericEntities : defaults$1.interpretNumericEntities,
parameterLimit: typeof opts.parameterLimit === 'number' ? opts.parameterLimit : defaults$1.parameterLimit,
parseArrays: opts.parseArrays !== false,
plainObjects: typeof opts.plainObjects === 'boolean' ? opts.plainObjects : defaults$1.plainObjects,
strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults$1.strictNullHandling
};
};
var parse = function (str, opts) {
var options = normalizeParseOptions(opts);
if (str === '' || str === null || typeof str === 'undefined') {
return options.plainObjects ? Object.create(null) : {};
}
var tempObj = typeof str === 'string' ? parseValues(str, options) : str;
var obj = options.plainObjects ? Object.create(null) : {};
// Iterate over the keys and setup the new object
var keys = Object.keys(tempObj);
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
var newObj = parseKeys(key, tempObj[key], options);
obj = utils.merge(obj, newObj, options);
}
return utils.compact(obj);
};
var lib = {
formats: formats,
parse: parse,
stringify: stringify_1
};
function PopupHandler(webAuth) {
this.webAuth = webAuth;
this._current_popup = null;
this.options = null;
}
PopupHandler.prototype.preload = function(options) {
var _this = this;
var _window = windowHandler.getWindow();
var url = options.url || 'about:blank';
var popupOptions = options.popupOptions || {};
popupOptions.location = 'yes';
delete popupOptions.width;
delete popupOptions.height;
var windowFeatures = lib.stringify(popupOptions, {
encode: false,
delimiter: ','
});
if (this._current_popup && !this._current_popup.closed) {
return this._current_popup;
}
this._current_popup = _window.open(url, '_blank', windowFeatures);
this._current_popup.kill = function(success) {
_this._current_popup.success = success;
this.close();
_this._current_popup = null;
};
return this._current_popup;
};
PopupHandler.prototype.load = function(url, _, options, cb) {
var _this = this;
this.url = url;
this.options = options;
if (!this._current_popup) {
options.url = url;
this.preload(options);
} else {
this._current_popup.location.href = url;
}
this.transientErrorHandler = function(event) {
_this.errorHandler(event, cb);
};
this.transientStartHandler = function(event) {
_this.startHandler(event, cb);
};
this.transientExitHandler = function() {
_this.exitHandler(cb);
};
this._current_popup.addEventListener('loaderror', this.transientErrorHandler);
this._current_popup.addEventListener('loadstart', this.transientStartHandler);
this._current_popup.addEventListener('exit', this.transientExitHandler);
};
PopupHandler.prototype.errorHandler = function(event, cb) {
if (!this._current_popup) {
return;
}
this._current_popup.kill(true);
cb({ error: 'window_error', errorDescription: event.message });
};
PopupHandler.prototype.unhook = function() {
this._current_popup.removeEventListener(
'loaderror',
this.transientErrorHandler
);
this._current_popup.removeEventListener(
'loadstart',
this.transientStartHandler
);
this._current_popup.removeEventListener('exit', this.transientExitHandler);
};
PopupHandler.prototype.exitHandler = function(cb) {
if (!this._current_popup) {
return;
}
// when the modal is closed, this event is called which ends up removing the
// event listeners. If you move this before closing the modal, it will add ~1 sec
// delay between the user being redirected to the callback and the popup gets closed.
this.unhook();
if (!this._current_popup.success) {
cb({ error: 'window_closed', errorDescription: 'Browser window closed' });
}
};
PopupHandler.prototype.startHandler = function(event, cb) {
var _this = this;
if (!this._current_popup) {
return;
}
var callbackUrl = urlJoin(
'https:',
this.webAuth.baseOptions.domain,
'/mobile'
);
if (event.url && !(event.url.indexOf(callbackUrl + '#') === 0)) {
return;
}
var parts = event.url.split('#');
if (parts.length === 1) {
return;
}
var opts = { hash: parts.pop() };
if (this.options.nonce) {
opts.nonce = this.options.nonce;
}
this.webAuth.parseHash(opts, function(error, result) {
if (error || result) {
_this._current_popup.kill(true);
cb(error, result);
}
});
};
function PluginHandler(webAuth) {
this.webAuth = webAuth;
}
PluginHandler.prototype.processParams = function(params) {
params.redirectUri = urlJoin('https://' + params.domain, 'mobile');
delete params.owp;
return params;
};
PluginHandler.prototype.getPopupHandler = function() {
return new PopupHandler(this.webAuth);
};
function CordovaPlugin() {
this.webAuth = null;
this.version = version.raw;
this.extensibilityPoints = ['popup.authorize', 'popup.getPopupHandler'];
}
CordovaPlugin.prototype.setWebAuth = function(webAuth) {
this.webAuth = webAuth;
};
CordovaPlugin.prototype.supports = function(extensibilityPoint) {
var _window = windowHandler.getWindow();
return (
(!!_window.cordova || !!_window.electron) &&
this.extensibilityPoints.indexOf(extensibilityPoint) > -1
);
};
CordovaPlugin.prototype.init = function() {
return new PluginHandler(this.webAuth);
};
return CordovaPlugin;
}));
|
/*! Select2 4.1.0-beta.0 | https://github.com/select2/select2/blob/master/LICENSE.md */
!function(){if(jQuery&&jQuery.fn&&jQuery.fn.select2&&jQuery.fn.select2.amd)var n=jQuery.fn.select2.amd;n.define("select2/i18n/ja",[],function(){return{errorLoading:function(){return"結果が読み込まれませんでした"},inputTooLong:function(n){return n.input.length-n.maximum+" 文字を削除してください"},inputTooShort:function(n){return"少なくとも "+(n.minimum-n.input.length)+" 文字を入力してください"},loadingMore:function(){return"読み込み中…"},maximumSelected:function(n){return n.maximum+" 件しか選択できません"},noResults:function(){return"対象が見つかりません"},searching:function(){return"検索しています…"},removeAllItems:function(){return"すべてのアイテムを削除"}}}),n.define,n.require}(); |
define(["./PrimitivePipeline-c76ef883","./createTaskProcessorWorker","./Transforms-79117a7b","./Cartesian2-8646c5a1","./Check-24483042","./when-54335d57","./Math-d6182036","./RuntimeError-88a32665","./ComponentDatatype-1a100acd","./WebGLConstants-95ceb4e9","./GeometryAttribute-374f805d","./GeometryAttributes-caa08d6c","./GeometryPipeline-571ff4c9","./AttributeCompression-10c27d9c","./EncodedCartesian3-bf827957","./IndexDatatype-82ceea78","./IntersectionTests-5394f658","./Plane-13ae4b1b","./WebMercatorProjection-66cc0482"],function(i,e,t,r,n,a,o,c,s,m,b,P,p,u,d,f,y,C,l){"use strict";return e(function(e,t){return e=i.PrimitivePipeline.unpackCombineGeometryParameters(e),e=i.PrimitivePipeline.combineGeometry(e),i.PrimitivePipeline.packCombineGeometryResults(e,t)})}); |
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
import _extends from "@babel/runtime/helpers/esm/extends";
import * as React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import { unstable_composeClasses as composeClasses, isHostComponent } from '@material-ui/unstyled';
import { chainPropTypes, elementTypeAcceptingRef } from '@material-ui/utils';
import experimentalStyled from '../styles/experimentalStyled';
import useThemeProps from '../styles/useThemeProps';
import { alpha } from '../styles/colorManipulator';
import ButtonBase from '../ButtonBase';
import isMuiElement from '../utils/isMuiElement';
import useEnhancedEffect from '../utils/useEnhancedEffect';
import useForkRef from '../utils/useForkRef';
import ListContext from '../List/ListContext';
import listItemClasses, { getListItemUtilityClass } from './listItemClasses';
import { jsx as _jsx } from "react/jsx-runtime";
import { jsxs as _jsxs } from "react/jsx-runtime";
export var overridesResolver = function overridesResolver(props, styles) {
var styleProps = props.styleProps;
return _extends({}, styles.root, styleProps.dense && styles.dense, styleProps.alignItems === 'flex-start' && styles.alignItemsFlexStart, styleProps.divider && styles.divider, !styleProps.disableGutters && styles.gutters, styleProps.button && styles.button, styleProps.hasSecondaryAction && styles.secondaryAction);
};
var useUtilityClasses = function useUtilityClasses(styleProps) {
var alignItems = styleProps.alignItems,
button = styleProps.button,
classes = styleProps.classes,
dense = styleProps.dense,
disabled = styleProps.disabled,
disableGutters = styleProps.disableGutters,
divider = styleProps.divider,
hasSecondaryAction = styleProps.hasSecondaryAction,
selected = styleProps.selected;
var slots = {
root: ['root', dense && 'dense', !disableGutters && 'gutters', divider && 'divider', disabled && 'disabled', button && 'button', alignItems === 'flex-start' && 'alignItemsFlexStart', hasSecondaryAction && 'secondaryAction', selected && 'selected'],
container: ['container']
};
return composeClasses(slots, getListItemUtilityClass, classes);
};
export var ListItemRoot = experimentalStyled('div', {
name: 'MuiListItem',
slot: 'Root',
overridesResolver: overridesResolver
})(function (_ref) {
var _extends2;
var theme = _ref.theme,
styleProps = _ref.styleProps;
return _extends((_extends2 = {
display: 'flex',
justifyContent: 'flex-start',
alignItems: 'center',
position: 'relative',
textDecoration: 'none',
width: '100%',
boxSizing: 'border-box',
textAlign: 'left',
paddingTop: 8,
paddingBottom: 8
}, _defineProperty(_extends2, "&.".concat(listItemClasses.focusVisible), {
backgroundColor: theme.palette.action.focus
}), _defineProperty(_extends2, "&.".concat(listItemClasses.selected), _defineProperty({
backgroundColor: alpha(theme.palette.primary.main, theme.palette.action.selectedOpacity)
}, "&.".concat(listItemClasses.focusVisible), {
backgroundColor: alpha(theme.palette.primary.main, theme.palette.action.selectedOpacity + theme.palette.action.focusOpacity)
})), _defineProperty(_extends2, "&.".concat(listItemClasses.disabled), {
opacity: theme.palette.action.disabledOpacity
}), _extends2), styleProps.dense && {
paddingTop: 4,
paddingBottom: 4
}, styleProps.alignItems === 'flex-start' && {
alignItems: 'flex-start'
}, styleProps.divider && {
borderBottom: "1px solid ".concat(theme.palette.divider),
backgroundClip: 'padding-box'
}, !styleProps.disableGutters && {
paddingLeft: 16,
paddingRight: 16
}, styleProps.button && _defineProperty({
transition: theme.transitions.create('background-color', {
duration: theme.transitions.duration.shortest
}),
'&:hover': {
textDecoration: 'none',
backgroundColor: theme.palette.action.hover,
// Reset on touch devices, it doesn't add specificity
'@media (hover: none)': {
backgroundColor: 'transparent'
}
}
}, "&.".concat(listItemClasses.selected, ":hover"), {
backgroundColor: alpha(theme.palette.primary.main, theme.palette.action.selectedOpacity + theme.palette.action.hoverOpacity),
// Reset on touch devices, it doesn't add specificity
'@media (hover: none)': {
backgroundColor: alpha(theme.palette.primary.main, theme.palette.action.selectedOpacity)
}
}), styleProps.hasSecondaryAction && {
// Add some space to avoid collision as `ListItemSecondaryAction`
// is absolutely positioned.
paddingRight: 48
});
});
var ListItemContainer = experimentalStyled('li', {
name: 'MuiListItem',
slot: 'Container',
overridesResolver: function overridesResolver(props, styles) {
return styles.container;
}
})({
position: 'relative'
});
/**
* Uses an additional container component if `ListItemSecondaryAction` is the last child.
*/
var ListItem = /*#__PURE__*/React.forwardRef(function ListItem(inProps, ref) {
var props = useThemeProps({
props: inProps,
name: 'MuiListItem'
});
var _props$alignItems = props.alignItems,
alignItems = _props$alignItems === void 0 ? 'center' : _props$alignItems,
_props$autoFocus = props.autoFocus,
autoFocus = _props$autoFocus === void 0 ? false : _props$autoFocus,
_props$button = props.button,
button = _props$button === void 0 ? false : _props$button,
childrenProp = props.children,
className = props.className,
componentProp = props.component,
_props$components = props.components,
components = _props$components === void 0 ? {} : _props$components,
_props$componentsProp = props.componentsProps,
componentsProps = _props$componentsProp === void 0 ? {} : _props$componentsProp,
_props$ContainerCompo = props.ContainerComponent,
ContainerComponent = _props$ContainerCompo === void 0 ? 'li' : _props$ContainerCompo,
_props$ContainerProps = props.ContainerProps;
_props$ContainerProps = _props$ContainerProps === void 0 ? {} : _props$ContainerProps;
var ContainerClassName = _props$ContainerProps.className,
ContainerProps = _objectWithoutProperties(_props$ContainerProps, ["className"]),
_props$dense = props.dense,
dense = _props$dense === void 0 ? false : _props$dense,
_props$disabled = props.disabled,
disabled = _props$disabled === void 0 ? false : _props$disabled,
_props$disableGutters = props.disableGutters,
disableGutters = _props$disableGutters === void 0 ? false : _props$disableGutters,
_props$divider = props.divider,
divider = _props$divider === void 0 ? false : _props$divider,
focusVisibleClassName = props.focusVisibleClassName,
_props$selected = props.selected,
selected = _props$selected === void 0 ? false : _props$selected,
other = _objectWithoutProperties(props, ["alignItems", "autoFocus", "button", "children", "className", "component", "components", "componentsProps", "ContainerComponent", "ContainerProps", "dense", "disabled", "disableGutters", "divider", "focusVisibleClassName", "selected"]);
var context = React.useContext(ListContext);
var childContext = {
dense: dense || context.dense || false,
alignItems: alignItems,
disableGutters: disableGutters
};
var listItemRef = React.useRef(null);
useEnhancedEffect(function () {
if (autoFocus) {
if (listItemRef.current) {
listItemRef.current.focus();
} else if (process.env.NODE_ENV !== 'production') {
console.error('Material-UI: Unable to set focus to a ListItem whose component has not been rendered.');
}
}
}, [autoFocus]);
var children = React.Children.toArray(childrenProp);
var hasSecondaryAction = children.length && isMuiElement(children[children.length - 1], ['ListItemSecondaryAction']);
var styleProps = _extends({}, props, {
alignItems: alignItems,
autoFocus: autoFocus,
button: button,
dense: childContext.dense,
disabled: disabled,
disableGutters: disableGutters,
divider: divider,
hasSecondaryAction: hasSecondaryAction,
selected: selected
});
var classes = useUtilityClasses(styleProps);
var handleRef = useForkRef(listItemRef, ref);
var Root = components.Root || ListItemRoot;
var rootProps = componentsProps.root || {};
var componentProps = _extends({
className: clsx(classes.root, rootProps.className, className),
disabled: disabled
}, other);
var Component = componentProp || 'li';
if (button) {
componentProps.component = componentProp || 'div';
componentProps.focusVisibleClassName = clsx(listItemClasses.focusVisible, focusVisibleClassName);
Component = ButtonBase;
}
if (hasSecondaryAction) {
// Use div by default.
Component = !componentProps.component && !componentProp ? 'div' : Component; // Avoid nesting of li > li.
if (ContainerComponent === 'li') {
if (Component === 'li') {
Component = 'div';
} else if (componentProps.component === 'li') {
componentProps.component = 'div';
}
}
return /*#__PURE__*/_jsx(ListContext.Provider, {
value: childContext,
children: /*#__PURE__*/_jsxs(ListItemContainer, _extends({
as: ContainerComponent,
className: clsx(classes.container, ContainerClassName),
ref: handleRef,
styleProps: styleProps
}, ContainerProps, {
children: [/*#__PURE__*/_jsx(Root, _extends({}, rootProps, !isHostComponent(Root) && {
as: Component,
styleProps: _extends({}, styleProps, rootProps.styleProps)
}, componentProps, {
children: children
})), children.pop()]
}))
});
}
return /*#__PURE__*/_jsx(ListContext.Provider, {
value: childContext,
children: /*#__PURE__*/_jsx(Root, _extends({}, rootProps, {
as: Component,
ref: handleRef,
styleProps: styleProps
}, !isHostComponent(Root) && {
styleProps: _extends({}, styleProps, rootProps.styleProps)
}, componentProps, {
children: children
}))
});
});
process.env.NODE_ENV !== "production" ? ListItem.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" |
// ----------------------------------------------------------------------
/**
* Defines the `align-items` style property.
* @default 'center'
*/
alignItems: PropTypes.oneOf(['center', 'flex-start']),
/**
* If `true`, the list item is focused during the first mount.
* Focus will also be triggered if the value changes from false to true.
* @default false
*/
autoFocus: PropTypes.bool,
/**
* If `true`, the list item is a button (using `ButtonBase`). Props intended
* for `ButtonBase` can then be applied to `ListItem`.
* @default false
*/
button: PropTypes.bool,
/**
* The content of the component if a `ListItemSecondaryAction` is used it must
* be the last child.
*/
children: chainPropTypes(PropTypes.node, function (props) {
var children = React.Children.toArray(props.children); // React.Children.toArray(props.children).findLastIndex(isListItemSecondaryAction)
var secondaryActionIndex = -1;
for (var i = children.length - 1; i >= 0; i -= 1) {
var child = children[i];
if (isMuiElement(child, ['ListItemSecondaryAction'])) {
secondaryActionIndex = i;
break;
}
} // is ListItemSecondaryAction the last child of ListItem
if (secondaryActionIndex !== -1 && secondaryActionIndex !== children.length - 1) {
return new Error('Material-UI: You used an element after ListItemSecondaryAction. ' + 'For ListItem to detect that it has a secondary action ' + 'you must pass it as the last child to ListItem.');
}
return null;
}),
/**
* Override or extend the styles applied to the component.
*/
classes: PropTypes.object,
/**
* @ignore
*/
className: PropTypes.string,
/**
* The component used for the root node.
* Either a string to use a HTML element or a component.
*/
component: PropTypes.elementType,
/**
* The components used for each slot inside the InputBase.
* Either a string to use a HTML element or a component.
* @default {}
*/
components: PropTypes.shape({
Root: PropTypes.elementType
}),
/**
* The props used for each slot inside the Input.
* @default {}
*/
componentsProps: PropTypes.object,
/**
* The container component used when a `ListItemSecondaryAction` is the last child.
* @default 'li'
*/
ContainerComponent: elementTypeAcceptingRef,
/**
* Props applied to the container component if used.
* @default {}
*/
ContainerProps: PropTypes.object,
/**
* If `true`, compact vertical padding designed for keyboard and mouse input is used.
* The prop defaults to the value inherited from the parent List component.
* @default false
*/
dense: PropTypes.bool,
/**
* If `true`, the component is disabled.
* @default false
*/
disabled: PropTypes.bool,
/**
* If `true`, the left and right padding is removed.
* @default false
*/
disableGutters: PropTypes.bool,
/**
* If `true`, a 1px light border is added to the bottom of the list item.
* @default false
*/
divider: PropTypes.bool,
/**
* @ignore
*/
focusVisibleClassName: PropTypes.string,
/**
* Use to apply selected styling.
* @default false
*/
selected: PropTypes.bool,
/**
* The system prop that allows defining system overrides as well as additional CSS styles.
*/
sx: PropTypes.object
} : void 0;
export default ListItem; |
typeof window !== "undefined" &&
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else if(typeof exports === 'object')
exports["Hls"] = factory();
else
root["Hls"] = factory();
})(this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "/dist/";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = "./src/hls.ts");
/******/ })
/************************************************************************/
/******/ ({
/***/ "./node_modules/eventemitter3/index.js":
/*!*********************************************!*\
!*** ./node_modules/eventemitter3/index.js ***!
\*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var has = Object.prototype.hasOwnProperty
, prefix = '~';
/**
* Constructor to create a storage for our `EE` objects.
* An `Events` instance is a plain object whose properties are event names.
*
* @constructor
* @private
*/
function Events() {}
//
// We try to not inherit from `Object.prototype`. In some engines creating an
// instance in this way is faster than calling `Object.create(null)` directly.
// If `Object.create(null)` is not supported we prefix the event names with a
// character to make sure that the built-in object properties are not
// overridden or used as an attack vector.
//
if (Object.create) {
Events.prototype = Object.create(null);
//
// This hack is needed because the `__proto__` property is still inherited in
// some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.
//
if (!new Events().__proto__) prefix = false;
}
/**
* Representation of a single event listener.
*
* @param {Function} fn The listener function.
* @param {*} context The context to invoke the listener with.
* @param {Boolean} [once=false] Specify if the listener is a one-time listener.
* @constructor
* @private
*/
function EE(fn, context, once) {
this.fn = fn;
this.context = context;
this.once = once || false;
}
/**
* Add a listener for a given event.
*
* @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
* @param {(String|Symbol)} event The event name.
* @param {Function} fn The listener function.
* @param {*} context The context to invoke the listener with.
* @param {Boolean} once Specify if the listener is a one-time listener.
* @returns {EventEmitter}
* @private
*/
function addListener(emitter, event, fn, context, once) {
if (typeof fn !== 'function') {
throw new TypeError('The listener must be a function');
}
var listener = new EE(fn, context || emitter, once)
, evt = prefix ? prefix + event : event;
if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;
else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);
else emitter._events[evt] = [emitter._events[evt], listener];
return emitter;
}
/**
* Clear event by name.
*
* @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
* @param {(String|Symbol)} evt The Event name.
* @private
*/
function clearEvent(emitter, evt) {
if (--emitter._eventsCount === 0) emitter._events = new Events();
else delete emitter._events[evt];
}
/**
* Minimal `EventEmitter` interface that is molded against the Node.js
* `EventEmitter` interface.
*
* @constructor
* @public
*/
function EventEmitter() {
this._events = new Events();
this._eventsCount = 0;
}
/**
* Return an array listing the events for which the emitter has registered
* listeners.
*
* @returns {Array}
* @public
*/
EventEmitter.prototype.eventNames = function eventNames() {
var names = []
, events
, name;
if (this._eventsCount === 0) return names;
for (name in (events = this._events)) {
if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);
}
if (Object.getOwnPropertySymbols) {
return names.concat(Object.getOwnPropertySymbols(events));
}
return names;
};
/**
* Return the listeners registered for a given event.
*
* @param {(String|Symbol)} event The event name.
* @returns {Array} The registered listeners.
* @public
*/
EventEmitter.prototype.listeners = function listeners(event) {
var evt = prefix ? prefix + event : event
, handlers = this._events[evt];
if (!handlers) return [];
if (handlers.fn) return [handlers.fn];
for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
ee[i] = handlers[i].fn;
}
return ee;
};
/**
* Return the number of listeners listening to a given event.
*
* @param {(String|Symbol)} event The event name.
* @returns {Number} The number of listeners.
* @public
*/
EventEmitter.prototype.listenerCount = function listenerCount(event) {
var evt = prefix ? prefix + event : event
, listeners = this._events[evt];
if (!listeners) return 0;
if (listeners.fn) return 1;
return listeners.length;
};
/**
* Calls each of the listeners registered for a given event.
*
* @param {(String|Symbol)} event The event name.
* @returns {Boolean} `true` if the event had listeners, else `false`.
* @public
*/
EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
var evt = prefix ? prefix + event : event;
if (!this._events[evt]) return false;
var listeners = this._events[evt]
, len = arguments.length
, args
, i;
if (listeners.fn) {
if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);
switch (len) {
case 1: return listeners.fn.call(listeners.context), true;
case 2: return listeners.fn.call(listeners.context, a1), true;
case 3: return listeners.fn.call(listeners.context, a1, a2), true;
case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;
case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
}
for (i = 1, args = new Array(len -1); i < len; i++) {
args[i - 1] = arguments[i];
}
listeners.fn.apply(listeners.context, args);
} else {
var length = listeners.length
, j;
for (i = 0; i < length; i++) {
if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);
switch (len) {
case 1: listeners[i].fn.call(listeners[i].context); break;
case 2: listeners[i].fn.call(listeners[i].context, a1); break;
case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;
case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;
default:
if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {
args[j - 1] = arguments[j];
}
listeners[i].fn.apply(listeners[i].context, args);
}
}
}
return true;
};
/**
* Add a listener for a given event.
*
* @param {(String|Symbol)} event The event name.
* @param {Function} fn The listener function.
* @param {*} [context=this] The context to invoke the listener with.
* @returns {EventEmitter} `this`.
* @public
*/
EventEmitter.prototype.on = function on(event, fn, context) {
return addListener(this, event, fn, context, false);
};
/**
* Add a one-time listener for a given event.
*
* @param {(String|Symbol)} event The event name.
* @param {Function} fn The listener function.
* @param {*} [context=this] The context to invoke the listener with.
* @returns {EventEmitter} `this`.
* @public
*/
EventEmitter.prototype.once = function once(event, fn, context) {
return addListener(this, event, fn, context, true);
};
/**
* Remove the listeners of a given event.
*
* @param {(String|Symbol)} event The event name.
* @param {Function} fn Only remove the listeners that match this function.
* @param {*} context Only remove the listeners that have this context.
* @param {Boolean} once Only remove one-time listeners.
* @returns {EventEmitter} `this`.
* @public
*/
EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
var evt = prefix ? prefix + event : event;
if (!this._events[evt]) return this;
if (!fn) {
clearEvent(this, evt);
return this;
}
var listeners = this._events[evt];
if (listeners.fn) {
if (
listeners.fn === fn &&
(!once || listeners.once) &&
(!context || listeners.context === context)
) {
clearEvent(this, evt);
}
} else {
for (var i = 0, events = [], length = listeners.length; i < length; i++) {
if (
listeners[i].fn !== fn ||
(once && !listeners[i].once) ||
(context && listeners[i].context !== context)
) {
events.push(listeners[i]);
}
}
//
// Reset the array, or remove it completely if we have no more listeners.
//
if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;
else clearEvent(this, evt);
}
return this;
};
/**
* Remove all listeners, or those of the specified event.
*
* @param {(String|Symbol)} [event] The event name.
* @returns {EventEmitter} `this`.
* @public
*/
EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
var evt;
if (event) {
evt = prefix ? prefix + event : event;
if (this._events[evt]) clearEvent(this, evt);
} else {
this._events = new Events();
this._eventsCount = 0;
}
return this;
};
//
// Alias methods names because people roll like that.
//
EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
EventEmitter.prototype.addListener = EventEmitter.prototype.on;
//
// Expose the prefix.
//
EventEmitter.prefixed = prefix;
//
// Allow `EventEmitter` to be imported as module namespace.
//
EventEmitter.EventEmitter = EventEmitter;
//
// Expose the module.
//
if (true) {
module.exports = EventEmitter;
}
/***/ }),
/***/ "./node_modules/url-toolkit/src/url-toolkit.js":
/*!*****************************************************!*\
!*** ./node_modules/url-toolkit/src/url-toolkit.js ***!
\*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
// see https://tools.ietf.org/html/rfc1808
(function (root) {
var URL_REGEX = /^((?:[a-zA-Z0-9+\-.]+:)?)(\/\/[^\/?#]*)?((?:[^\/?#]*\/)*[^;?#]*)?(;[^?#]*)?(\?[^#]*)?(#.*)?$/;
var FIRST_SEGMENT_REGEX = /^([^\/?#]*)(.*)$/;
var SLASH_DOT_REGEX = /(?:\/|^)\.(?=\/)/g;
var SLASH_DOT_DOT_REGEX = /(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g;
var URLToolkit = {
// If opts.alwaysNormalize is true then the path will always be normalized even when it starts with / or //
// E.g
// With opts.alwaysNormalize = false (default, spec compliant)
// http://a.com/b/cd + /e/f/../g => http://a.com/e/f/../g
// With opts.alwaysNormalize = true (not spec compliant)
// http://a.com/b/cd + /e/f/../g => http://a.com/e/g
buildAbsoluteURL: function (baseURL, relativeURL, opts) {
opts = opts || {};
// remove any remaining space and CRLF
baseURL = baseURL.trim();
relativeURL = relativeURL.trim();
if (!relativeURL) {
// 2a) If the embedded URL is entirely empty, it inherits the
// entire base URL (i.e., is set equal to the base URL)
// and we are done.
if (!opts.alwaysNormalize) {
return baseURL;
}
var basePartsForNormalise = URLToolkit.parseURL(baseURL);
if (!basePartsForNormalise) {
throw new Error('Error trying to parse base URL.');
}
basePartsForNormalise.path = URLToolkit.normalizePath(
basePartsForNormalise.path
);
return URLToolkit.buildURLFromParts(basePartsForNormalise);
}
var relativeParts = URLToolkit.parseURL(relativeURL);
if (!relativeParts) {
throw new Error('Error trying to parse relative URL.');
}
if (relativeParts.scheme) {
// 2b) If the embedded URL starts with a scheme name, it is
// interpreted as an absolute URL and we are done.
if (!opts.alwaysNormalize) {
return relativeURL;
}
relativeParts.path = URLToolkit.normalizePath(relativeParts.path);
return URLToolkit.buildURLFromParts(relativeParts);
}
var baseParts = URLToolkit.parseURL(baseURL);
if (!baseParts) {
throw new Error('Error trying to parse base URL.');
}
if (!baseParts.netLoc && baseParts.path && baseParts.path[0] !== '/') {
// If netLoc missing and path doesn't start with '/', assume everthing before the first '/' is the netLoc
// This causes 'example.com/a' to be handled as '//example.com/a' instead of '/example.com/a'
var pathParts = FIRST_SEGMENT_REGEX.exec(baseParts.path);
baseParts.netLoc = pathParts[1];
baseParts.path = pathParts[2];
}
if (baseParts.netLoc && !baseParts.path) {
baseParts.path = '/';
}
var builtParts = {
// 2c) Otherwise, the embedded URL inherits the scheme of
// the base URL.
scheme: baseParts.scheme,
netLoc: relativeParts.netLoc,
path: null,
params: relativeParts.params,
query: relativeParts.query,
fragment: relativeParts.fragment,
};
if (!relativeParts.netLoc) {
// 3) If the embedded URL's <net_loc> is non-empty, we skip to
// Step 7. Otherwise, the embedded URL inherits the <net_loc>
// (if any) of the base URL.
builtParts.netLoc = baseParts.netLoc;
// 4) If the embedded URL path is preceded by a slash "/", the
// path is not relative and we skip to Step 7.
if (relativeParts.path[0] !== '/') {
if (!relativeParts.path) {
// 5) If the embedded URL path is empty (and not preceded by a
// slash), then the embedded URL inherits the base URL path
builtParts.path = baseParts.path;
// 5a) if the embedded URL's <params> is non-empty, we skip to
// step 7; otherwise, it inherits the <params> of the base
// URL (if any) and
if (!relativeParts.params) {
builtParts.params = baseParts.params;
// 5b) if the embedded URL's <query> is non-empty, we skip to
// step 7; otherwise, it inherits the <query> of the base
// URL (if any) and we skip to step 7.
if (!relativeParts.query) {
builtParts.query = baseParts.query;
}
}
} else {
// 6) The last segment of the base URL's path (anything
// following the rightmost slash "/", or the entire path if no
// slash is present) is removed and the embedded URL's path is
// appended in its place.
var baseURLPath = baseParts.path;
var newPath =
baseURLPath.substring(0, baseURLPath.lastIndexOf('/') + 1) +
relativeParts.path;
builtParts.path = URLToolkit.normalizePath(newPath);
}
}
}
if (builtParts.path === null) {
builtParts.path = opts.alwaysNormalize
? URLToolkit.normalizePath(relativeParts.path)
: relativeParts.path;
}
return URLToolkit.buildURLFromParts(builtParts);
},
parseURL: function (url) {
var parts = URL_REGEX.exec(url);
if (!parts) {
return null;
}
return {
scheme: parts[1] || '',
netLoc: parts[2] || '',
path: parts[3] || '',
params: parts[4] || '',
query: parts[5] || '',
fragment: parts[6] || '',
};
},
normalizePath: function (path) {
// The following operations are
// then applied, in order, to the new path:
// 6a) All occurrences of "./", where "." is a complete path
// segment, are removed.
// 6b) If the path ends with "." as a complete path segment,
// that "." is removed.
path = path.split('').reverse().join('').replace(SLASH_DOT_REGEX, '');
// 6c) All occurrences of "<segment>/../", where <segment> is a
// complete path segment not equal to "..", are removed.
// Removal of these path segments is performed iteratively,
// removing the leftmost matching pattern on each iteration,
// until no matching pattern remains.
// 6d) If the path ends with "<segment>/..", where <segment> is a
// complete path segment not equal to "..", that
// "<segment>/.." is removed.
while (
path.length !== (path = path.replace(SLASH_DOT_DOT_REGEX, '')).length
) {}
return path.split('').reverse().join('');
},
buildURLFromParts: function (parts) {
return (
parts.scheme +
parts.netLoc +
parts.path +
parts.params +
parts.query +
parts.fragment
);
},
};
if (true)
module.exports = URLToolkit;
else {}
})(this);
/***/ }),
/***/ "./node_modules/webworkify-webpack/index.js":
/*!**************************************************!*\
!*** ./node_modules/webworkify-webpack/index.js ***!
\**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
function webpackBootstrapFunc (modules) {
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // identity function for calling harmony imports with the correct context
/******/ __webpack_require__.i = function(value) { return value; };
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "/";
/******/ // on error function for async loading
/******/ __webpack_require__.oe = function(err) { console.error(err); throw err; };
var f = __webpack_require__(__webpack_require__.s = ENTRY_MODULE)
return f.default || f // try to call default if defined to also support babel esmodule exports
}
var moduleNameReqExp = '[\\.|\\-|\\+|\\w|\/|@]+'
var dependencyRegExp = '\\(\\s*(\/\\*.*?\\*\/)?\\s*.*?(' + moduleNameReqExp + ').*?\\)' // additional chars when output.pathinfo is true
// http://stackoverflow.com/a/2593661/130442
function quoteRegExp (str) {
return (str + '').replace(/[.?*+^$[\]\\(){}|-]/g, '\\$&')
}
function isNumeric(n) {
return !isNaN(1 * n); // 1 * n converts integers, integers as string ("123"), 1e3 and "1e3" to integers and strings to NaN
}
function getModuleDependencies (sources, module, queueName) {
var retval = {}
retval[queueName] = []
var fnString = module.toString()
var wrapperSignature = fnString.match(/^function\s?\w*\(\w+,\s*\w+,\s*(\w+)\)/)
if (!wrapperSignature) return retval
var webpackRequireName = wrapperSignature[1]
// main bundle deps
var re = new RegExp('(\\\\n|\\W)' + quoteRegExp(webpackRequireName) + dependencyRegExp, 'g')
var match
while ((match = re.exec(fnString))) {
if (match[3] === 'dll-reference') continue
retval[queueName].push(match[3])
}
// dll deps
re = new RegExp('\\(' + quoteRegExp(webpackRequireName) + '\\("(dll-reference\\s(' + moduleNameReqExp + '))"\\)\\)' + dependencyRegExp, 'g')
while ((match = re.exec(fnString))) {
if (!sources[match[2]]) {
retval[queueName].push(match[1])
sources[match[2]] = __webpack_require__(match[1]).m
}
retval[match[2]] = retval[match[2]] || []
retval[match[2]].push(match[4])
}
// convert 1e3 back to 1000 - this can be important after uglify-js converted 1000 to 1e3
var keys = Object.keys(retval);
for (var i = 0; i < keys.length; i++) {
for (var j = 0; j < retval[keys[i]].length; j++) {
if (isNumeric(retval[keys[i]][j])) {
retval[keys[i]][j] = 1 * retval[keys[i]][j];
}
}
}
return retval
}
function hasValuesInQueues (queues) {
var keys = Object.keys(queues)
return keys.reduce(function (hasValues, key) {
return hasValues || queues[key].length > 0
}, false)
}
function getRequiredModules (sources, moduleId) {
var modulesQueue = {
main: [moduleId]
}
var requiredModules = {
main: []
}
var seenModules = {
main: {}
}
while (hasValuesInQueues(modulesQueue)) {
var queues = Object.keys(modulesQueue)
for (var i = 0; i < queues.length; i++) {
var queueName = queues[i]
var queue = modulesQueue[queueName]
var moduleToCheck = queue.pop()
seenModules[queueName] = seenModules[queueName] || {}
if (seenModules[queueName][moduleToCheck] || !sources[queueName][moduleToCheck]) continue
seenModules[queueName][moduleToCheck] = true
requiredModules[queueName] = requiredModules[queueName] || []
requiredModules[queueName].push(moduleToCheck)
var newModules = getModuleDependencies(sources, sources[queueName][moduleToCheck], queueName)
var newModulesKeys = Object.keys(newModules)
for (var j = 0; j < newModulesKeys.length; j++) {
modulesQueue[newModulesKeys[j]] = modulesQueue[newModulesKeys[j]] || []
modulesQueue[newModulesKeys[j]] = modulesQueue[newModulesKeys[j]].concat(newModules[newModulesKeys[j]])
}
}
}
return requiredModules
}
module.exports = function (moduleId, options) {
options = options || {}
var sources = {
main: __webpack_require__.m
}
var requiredModules = options.all ? { main: Object.keys(sources.main) } : getRequiredModules(sources, moduleId)
var src = ''
Object.keys(requiredModules).filter(function (m) { return m !== 'main' }).forEach(function (module) {
var entryModule = 0
while (requiredModules[module][entryModule]) {
entryModule++
}
requiredModules[module].push(entryModule)
sources[module][entryModule] = '(function(module, exports, __webpack_require__) { module.exports = __webpack_require__; })'
src = src + 'var ' + module + ' = (' + webpackBootstrapFunc.toString().replace('ENTRY_MODULE', JSON.stringify(entryModule)) + ')({' + requiredModules[module].map(function (id) { return '' + JSON.stringify(id) + ': ' + sources[module][id].toString() }).join(',') + '});\n'
})
src = src + 'new ((' + webpackBootstrapFunc.toString().replace('ENTRY_MODULE', JSON.stringify(moduleId)) + ')({' + requiredModules.main.map(function (id) { return '' + JSON.stringify(id) + ': ' + sources.main[id].toString() }).join(',') + '}))(self);'
var blob = new window.Blob([src], { type: 'text/javascript' })
if (options.bare) { return blob }
var URL = window.URL || window.webkitURL || window.mozURL || window.msURL
var workerUrl = URL.createObjectURL(blob)
var worker = new window.Worker(workerUrl)
worker.objectURL = workerUrl
return worker
}
/***/ }),
/***/ "./src/config.ts":
/*!***********************!*\
!*** ./src/config.ts ***!
\***********************/
/*! exports provided: hlsDefaultConfig, mergeConfig, enableStreamingMode */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hlsDefaultConfig", function() { return hlsDefaultConfig; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mergeConfig", function() { return mergeConfig; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "enableStreamingMode", function() { return enableStreamingMode; });
/* harmony import */ var _controller_abr_controller__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./controller/abr-controller */ "./src/controller/abr-controller.ts");
/* harmony import */ var _controller_audio_stream_controller__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./controller/audio-stream-controller */ "./src/controller/audio-stream-controller.ts");
/* harmony import */ var _controller_audio_track_controller__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./controller/audio-track-controller */ "./src/controller/audio-track-controller.ts");
/* harmony import */ var _controller_subtitle_stream_controller__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./controller/subtitle-stream-controller */ "./src/controller/subtitle-stream-controller.ts");
/* harmony import */ var _controller_subtitle_track_controller__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./controller/subtitle-track-controller */ "./src/controller/subtitle-track-controller.ts");
/* harmony import */ var _controller_buffer_controller__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./controller/buffer-controller */ "./src/controller/buffer-controller.ts");
/* harmony import */ var _controller_timeline_controller__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./controller/timeline-controller */ "./src/controller/timeline-controller.ts");
/* harmony import */ var _controller_cap_level_controller__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./controller/cap-level-controller */ "./src/controller/cap-level-controller.ts");
/* harmony import */ var _controller_fps_controller__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./controller/fps-controller */ "./src/controller/fps-controller.ts");
/* harmony import */ var _controller_eme_controller__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./controller/eme-controller */ "./src/controller/eme-controller.ts");
/* harmony import */ var _utils_xhr_loader__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./utils/xhr-loader */ "./src/utils/xhr-loader.ts");
/* harmony import */ var _utils_fetch_loader__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./utils/fetch-loader */ "./src/utils/fetch-loader.ts");
/* harmony import */ var _utils_cues__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./utils/cues */ "./src/utils/cues.ts");
/* harmony import */ var _utils_mediakeys_helper__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./utils/mediakeys-helper */ "./src/utils/mediakeys-helper.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./utils/logger */ "./src/utils/logger.ts");
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
// If possible, keep hlsDefaultConfig shallow
// It is cloned whenever a new Hls instance is created, by keeping the config
// shallow the properties are cloned, and we don't end up manipulating the default
var hlsDefaultConfig = _objectSpread(_objectSpread({
autoStartLoad: true,
// used by stream-controller
startPosition: -1,
// used by stream-controller
defaultAudioCodec: undefined,
// used by stream-controller
debug: false,
// used by logger
capLevelOnFPSDrop: false,
// used by fps-controller
capLevelToPlayerSize: false,
// used by cap-level-controller
initialLiveManifestSize: 1,
// used by stream-controller
maxBufferLength: 30,
// used by stream-controller
backBufferLength: Infinity,
// used by buffer-controller
maxBufferSize: 60 * 1000 * 1000,
// used by stream-controller
maxBufferHole: 0.1,
// used by stream-controller
highBufferWatchdogPeriod: 2,
// used by stream-controller
nudgeOffset: 0.1,
// used by stream-controller
nudgeMaxRetry: 3,
// used by stream-controller
maxFragLookUpTolerance: 0.25,
// used by stream-controller
liveSyncDurationCount: 3,
// used by latency-controller
liveMaxLatencyDurationCount: Infinity,
// used by latency-controller
liveSyncDuration: undefined,
// used by latency-controller
liveMaxLatencyDuration: undefined,
// used by latency-controller
maxLiveSyncPlaybackRate: 1,
// used by latency-controller
liveDurationInfinity: false,
// used by buffer-controller
liveBackBufferLength: null,
// used by buffer-controller
maxMaxBufferLength: 600,
// used by stream-controller
enableWorker: true,
// used by demuxer
enableSoftwareAES: true,
// used by decrypter
manifestLoadingTimeOut: 10000,
// used by playlist-loader
manifestLoadingMaxRetry: 1,
// used by playlist-loader
manifestLoadingRetryDelay: 1000,
// used by playlist-loader
manifestLoadingMaxRetryTimeout: 64000,
// used by playlist-loader
startLevel: undefined,
// used by level-controller
levelLoadingTimeOut: 10000,
// used by playlist-loader
levelLoadingMaxRetry: 4,
// used by playlist-loader
levelLoadingRetryDelay: 1000,
// used by playlist-loader
levelLoadingMaxRetryTimeout: 64000,
// used by playlist-loader
fragLoadingTimeOut: 20000,
// used by fragment-loader
fragLoadingMaxRetry: 6,
// used by fragment-loader
fragLoadingRetryDelay: 1000,
// used by fragment-loader
fragLoadingMaxRetryTimeout: 64000,
// used by fragment-loader
startFragPrefetch: false,
// used by stream-controller
fpsDroppedMonitoringPeriod: 5000,
// used by fps-controller
fpsDroppedMonitoringThreshold: 0.2,
// used by fps-controller
appendErrorMaxRetry: 3,
// used by buffer-controller
loader: _utils_xhr_loader__WEBPACK_IMPORTED_MODULE_10__["default"],
// loader: FetchLoader,
fLoader: undefined,
// used by fragment-loader
pLoader: undefined,
// used by playlist-loader
xhrSetup: undefined,
// used by xhr-loader
licenseXhrSetup: undefined,
// used by eme-controller
licenseResponseCallback: undefined,
// used by eme-controller
abrController: _controller_abr_controller__WEBPACK_IMPORTED_MODULE_0__["default"],
bufferController: _controller_buffer_controller__WEBPACK_IMPORTED_MODULE_5__["default"],
capLevelController: _controller_cap_level_controller__WEBPACK_IMPORTED_MODULE_7__["default"],
fpsController: _controller_fps_controller__WEBPACK_IMPORTED_MODULE_8__["default"],
stretchShortVideoTrack: false,
// used by mp4-remuxer
maxAudioFramesDrift: 1,
// used by mp4-remuxer
forceKeyFrameOnDiscontinuity: true,
// used by ts-demuxer
abrEwmaFastLive: 3,
// used by abr-controller
abrEwmaSlowLive: 9,
// used by abr-controller
abrEwmaFastVoD: 3,
// used by abr-controller
abrEwmaSlowVoD: 9,
// used by abr-controller
abrEwmaDefaultEstimate: 5e5,
// 500 kbps // used by abr-controller
abrBandWidthFactor: 0.95,
// used by abr-controller
abrBandWidthUpFactor: 0.7,
// used by abr-controller
abrMaxWithRealBitrate: false,
// used by abr-controller
maxStarvationDelay: 4,
// used by abr-controller
maxLoadingDelay: 4,
// used by abr-controller
minAutoBitrate: 0,
// used by hls
emeEnabled: false,
// used by eme-controller
widevineLicenseUrl: undefined,
// used by eme-controller
drmSystemOptions: {},
// used by eme-controller
requestMediaKeySystemAccessFunc: _utils_mediakeys_helper__WEBPACK_IMPORTED_MODULE_13__["requestMediaKeySystemAccess"],
// used by eme-controller
testBandwidth: true,
progressive: false,
lowLatencyMode: true
}, timelineConfig()), {}, {
subtitleStreamController: true ? _controller_subtitle_stream_controller__WEBPACK_IMPORTED_MODULE_3__["SubtitleStreamController"] : undefined,
subtitleTrackController: true ? _controller_subtitle_track_controller__WEBPACK_IMPORTED_MODULE_4__["default"] : undefined,
timelineController: true ? _controller_timeline_controller__WEBPACK_IMPORTED_MODULE_6__["TimelineController"] : undefined,
audioStreamController: true ? _controller_audio_stream_controller__WEBPACK_IMPORTED_MODULE_1__["default"] : undefined,
audioTrackController: true ? _controller_audio_track_controller__WEBPACK_IMPORTED_MODULE_2__["default"] : undefined,
emeController: true ? _controller_eme_controller__WEBPACK_IMPORTED_MODULE_9__["default"] : undefined
});
function timelineConfig() {
return {
cueHandler: _utils_cues__WEBPACK_IMPORTED_MODULE_12__["default"],
// used by timeline-controller
enableCEA708Captions: true,
// used by timeline-controller
enableWebVTT: true,
// used by timeline-controller
enableIMSC1: true,
// used by timeline-controller
captionsTextTrack1Label: 'English',
// used by timeline-controller
captionsTextTrack1LanguageCode: 'en',
// used by timeline-controller
captionsTextTrack2Label: 'Spanish',
// used by timeline-controller
captionsTextTrack2LanguageCode: 'es',
// used by timeline-controller
captionsTextTrack3Label: 'Unknown CC',
// used by timeline-controller
captionsTextTrack3LanguageCode: '',
// used by timeline-controller
captionsTextTrack4Label: 'Unknown CC',
// used by timeline-controller
captionsTextTrack4LanguageCode: '',
// used by timeline-controller
renderTextTracksNatively: true
};
}
function mergeConfig(defaultConfig, userConfig) {
if ((userConfig.liveSyncDurationCount || userConfig.liveMaxLatencyDurationCount) && (userConfig.liveSyncDuration || userConfig.liveMaxLatencyDuration)) {
throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");
}
if (userConfig.liveMaxLatencyDurationCount !== undefined && (userConfig.liveSyncDurationCount === undefined || userConfig.liveMaxLatencyDurationCount <= userConfig.liveSyncDurationCount)) {
throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');
}
if (userConfig.liveMaxLatencyDuration !== undefined && (userConfig.liveSyncDuration === undefined || userConfig.liveMaxLatencyDuration <= userConfig.liveSyncDuration)) {
throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');
}
return _extends({}, defaultConfig, userConfig);
}
function enableStreamingMode(config) {
var currentLoader = config.loader;
if (currentLoader !== _utils_fetch_loader__WEBPACK_IMPORTED_MODULE_11__["default"] && currentLoader !== _utils_xhr_loader__WEBPACK_IMPORTED_MODULE_10__["default"]) {
// If a developer has configured their own loader, respect that choice
_utils_logger__WEBPACK_IMPORTED_MODULE_14__["logger"].log('[config]: Custom loader detected, cannot enable progressive streaming');
config.progressive = false;
} else {
var canStreamProgressively = Object(_utils_fetch_loader__WEBPACK_IMPORTED_MODULE_11__["fetchSupported"])();
if (canStreamProgressively) {
config.loader = _utils_fetch_loader__WEBPACK_IMPORTED_MODULE_11__["default"];
config.progressive = true;
config.enableSoftwareAES = true;
_utils_logger__WEBPACK_IMPORTED_MODULE_14__["logger"].log('[config]: Progressive streaming enabled, using FetchLoader');
}
}
}
/***/ }),
/***/ "./src/controller/abr-controller.ts":
/*!******************************************!*\
!*** ./src/controller/abr-controller.ts ***!
\******************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var _utils_ewma_bandwidth_estimator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/ewma-bandwidth-estimator */ "./src/utils/ewma-bandwidth-estimator.ts");
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/buffer-helper */ "./src/utils/buffer-helper.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
/* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
var AbrController = /*#__PURE__*/function () {
function AbrController(hls) {
this.hls = void 0;
this.lastLoadedFragLevel = 0;
this._nextAutoLevel = -1;
this.timer = void 0;
this.onCheck = this._abandonRulesCheck.bind(this);
this.fragCurrent = null;
this.partCurrent = null;
this.bitrateTestDelay = 0;
this.bwEstimator = void 0;
this.hls = hls;
var config = hls.config;
this.bwEstimator = new _utils_ewma_bandwidth_estimator__WEBPACK_IMPORTED_MODULE_1__["default"](config.abrEwmaSlowVoD, config.abrEwmaFastVoD, config.abrEwmaDefaultEstimate);
this.registerListeners();
}
var _proto = AbrController.prototype;
_proto.registerListeners = function registerListeners() {
var hls = this.hls;
hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_LOADING, this.onFragLoading, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_LOADED, this.onFragLoaded, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_BUFFERED, this.onFragBuffered, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].LEVEL_LOADED, this.onLevelLoaded, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].ERROR, this.onError, this);
};
_proto.unregisterListeners = function unregisterListeners() {
var hls = this.hls;
hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_LOADING, this.onFragLoading, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_LOADED, this.onFragLoaded, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_BUFFERED, this.onFragBuffered, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].LEVEL_LOADED, this.onLevelLoaded, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].ERROR, this.onError, this);
};
_proto.destroy = function destroy() {
this.unregisterListeners();
this.clearTimer(); // @ts-ignore
this.hls = this.onCheck = null;
this.fragCurrent = this.partCurrent = null;
};
_proto.onFragLoading = function onFragLoading(event, data) {
var frag = data.frag;
if (frag.type === _types_loader__WEBPACK_IMPORTED_MODULE_5__["PlaylistLevelType"].MAIN) {
if (!this.timer) {
var _data$part;
this.fragCurrent = frag;
this.partCurrent = (_data$part = data.part) != null ? _data$part : null;
this.timer = self.setInterval(this.onCheck, 100);
}
}
};
_proto.onLevelLoaded = function onLevelLoaded(event, data) {
var config = this.hls.config;
if (data.details.live) {
this.bwEstimator.update(config.abrEwmaSlowLive, config.abrEwmaFastLive);
} else {
this.bwEstimator.update(config.abrEwmaSlowVoD, config.abrEwmaFastVoD);
}
}
/*
This method monitors the download rate of the current fragment, and will downswitch if that fragment will not load
quickly enough to prevent underbuffering
*/
;
_proto._abandonRulesCheck = function _abandonRulesCheck() {
var frag = this.fragCurrent,
part = this.partCurrent,
hls = this.hls;
var autoLevelEnabled = hls.autoLevelEnabled,
config = hls.config,
media = hls.media;
if (!frag || !media) {
return;
}
var stats = part ? part.stats : frag.stats;
var duration = part ? part.duration : frag.duration; // If loading has been aborted and not in lowLatencyMode, stop timer and return
if (stats.aborted) {
_utils_logger__WEBPACK_IMPORTED_MODULE_6__["logger"].warn('frag loader destroy or aborted, disarm abandonRules');
this.clearTimer(); // reset forced auto level value so that next level will be selected
this._nextAutoLevel = -1;
return;
} // This check only runs if we're in ABR mode and actually playing
if (!autoLevelEnabled || media.paused || !media.playbackRate || !media.readyState) {
return;
}
var requestDelay = performance.now() - stats.loading.start;
var playbackRate = Math.abs(media.playbackRate); // In order to work with a stable bandwidth, only begin monitoring bandwidth after half of the fragment has been loaded
if (requestDelay <= 500 * duration / playbackRate) {
return;
}
var levels = hls.levels,
minAutoLevel = hls.minAutoLevel;
var level = levels[frag.level];
var expectedLen = stats.total || Math.max(stats.loaded, Math.round(duration * level.maxBitrate / 8));
var loadRate = Math.max(1, stats.bwEstimate ? stats.bwEstimate / 8 : stats.loaded * 1000 / requestDelay); // fragLoadDelay is an estimate of the time (in seconds) it will take to buffer the entire fragment
var fragLoadedDelay = (expectedLen - stats.loaded) / loadRate;
var pos = media.currentTime; // bufferStarvationDelay is an estimate of the amount time (in seconds) it will take to exhaust the buffer
var bufferStarvationDelay = (_utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].bufferInfo(media, pos, config.maxBufferHole).end - pos) / playbackRate; // Attempt an emergency downswitch only if less than 2 fragment lengths are buffered, and the time to finish loading
// the current fragment is greater than the amount of buffer we have left
if (bufferStarvationDelay >= 2 * duration / playbackRate || fragLoadedDelay <= bufferStarvationDelay) {
return;
}
var fragLevelNextLoadedDelay = Number.POSITIVE_INFINITY;
var nextLoadLevel; // Iterate through lower level and try to find the largest one that avoids rebuffering
for (nextLoadLevel = frag.level - 1; nextLoadLevel > minAutoLevel; nextLoadLevel--) {
// compute time to load next fragment at lower level
// 0.8 : consider only 80% of current bw to be conservative
// 8 = bits per byte (bps/Bps)
var levelNextBitrate = levels[nextLoadLevel].maxBitrate;
fragLevelNextLoadedDelay = duration * levelNextBitrate / (8 * 0.8 * loadRate);
if (fragLevelNextLoadedDelay < bufferStarvationDelay) {
break;
}
} // Only emergency switch down if it takes less time to load a new fragment at lowest level instead of continuing
// to load the current one
if (fragLevelNextLoadedDelay >= fragLoadedDelay) {
return;
}
var bwEstimate = this.bwEstimator.getEstimate();
_utils_logger__WEBPACK_IMPORTED_MODULE_6__["logger"].warn("Fragment " + frag.sn + (part ? ' part ' + part.index : '') + " of level " + frag.level + " is loading too slowly and will cause an underbuffer; aborting and switching to level " + nextLoadLevel + "\n Current BW estimate: " + (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(bwEstimate) ? (bwEstimate / 1024).toFixed(3) : 'Unknown') + " Kb/s\n Estimated load time for current fragment: " + fragLoadedDelay.toFixed(3) + " s\n Estimated load time for the next fragment: " + fragLevelNextLoadedDelay.toFixed(3) + " s\n Time to underbuffer: " + bufferStarvationDelay.toFixed(3) + " s");
hls.nextLoadLevel = nextLoadLevel;
this.bwEstimator.sample(requestDelay, stats.loaded);
this.clearTimer();
if (frag.loader) {
this.fragCurrent = this.partCurrent = null;
frag.loader.abort();
}
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_LOAD_EMERGENCY_ABORTED, {
frag: frag,
part: part,
stats: stats
});
};
_proto.onFragLoaded = function onFragLoaded(event, _ref) {
var frag = _ref.frag,
part = _ref.part;
if (frag.type === _types_loader__WEBPACK_IMPORTED_MODULE_5__["PlaylistLevelType"].MAIN && Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(frag.sn)) {
var stats = part ? part.stats : frag.stats;
var duration = part ? part.duration : frag.duration; // stop monitoring bw once frag loaded
this.clearTimer(); // store level id after successful fragment load
this.lastLoadedFragLevel = frag.level; // reset forced auto level value so that next level will be selected
this._nextAutoLevel = -1; // compute level average bitrate
if (this.hls.config.abrMaxWithRealBitrate) {
var level = this.hls.levels[frag.level];
var loadedBytes = (level.loaded ? level.loaded.bytes : 0) + stats.loaded;
var loadedDuration = (level.loaded ? level.loaded.duration : 0) + duration;
level.loaded = {
bytes: loadedBytes,
duration: loadedDuration
};
level.realBitrate = Math.round(8 * loadedBytes / loadedDuration);
}
if (frag.bitrateTest) {
var fragBufferedData = {
stats: stats,
frag: frag,
part: part,
id: frag.type
};
this.onFragBuffered(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_BUFFERED, fragBufferedData);
frag.bitrateTest = false;
}
}
};
_proto.onFragBuffered = function onFragBuffered(event, data) {
var frag = data.frag,
part = data.part;
var stats = part ? part.stats : frag.stats;
if (stats.aborted) {
return;
} // Only count non-alt-audio frags which were actually buffered in our BW calculations
if (frag.type !== _types_loader__WEBPACK_IMPORTED_MODULE_5__["PlaylistLevelType"].MAIN || frag.sn === 'initSegment') {
return;
} // Use the difference between parsing and request instead of buffering and request to compute fragLoadingProcessing;
// rationale is that buffer appending only happens once media is attached. This can happen when config.startFragPrefetch
// is used. If we used buffering in that case, our BW estimate sample will be very large.
var processingMs = stats.parsing.end - stats.loading.start;
this.bwEstimator.sample(processingMs, stats.loaded);
stats.bwEstimate = this.bwEstimator.getEstimate();
if (frag.bitrateTest) {
this.bitrateTestDelay = processingMs / 1000;
} else {
this.bitrateTestDelay = 0;
}
};
_proto.onError = function onError(event, data) {
// stop timer in case of frag loading error
switch (data.details) {
case _errors__WEBPACK_IMPORTED_MODULE_4__["ErrorDetails"].FRAG_LOAD_ERROR:
case _errors__WEBPACK_IMPORTED_MODULE_4__["ErrorDetails"].FRAG_LOAD_TIMEOUT:
this.clearTimer();
break;
default:
break;
}
};
_proto.clearTimer = function clearTimer() {
self.clearInterval(this.timer);
this.timer = undefined;
} // return next auto level
;
_proto.getNextABRAutoLevel = function getNextABRAutoLevel() {
var fragCurrent = this.fragCurrent,
partCurrent = this.partCurrent,
hls = this.hls;
var maxAutoLevel = hls.maxAutoLevel,
config = hls.config,
minAutoLevel = hls.minAutoLevel,
media = hls.media;
var currentFragDuration = partCurrent ? partCurrent.duration : fragCurrent ? fragCurrent.duration : 0;
var pos = media ? media.currentTime : 0; // playbackRate is the absolute value of the playback rate; if media.playbackRate is 0, we use 1 to load as
// if we're playing back at the normal rate.
var playbackRate = media && media.playbackRate !== 0 ? Math.abs(media.playbackRate) : 1.0;
var avgbw = this.bwEstimator ? this.bwEstimator.getEstimate() : config.abrEwmaDefaultEstimate; // bufferStarvationDelay is the wall-clock time left until the playback buffer is exhausted.
var bufferStarvationDelay = (_utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].bufferInfo(media, pos, config.maxBufferHole).end - pos) / playbackRate; // First, look to see if we can find a level matching with our avg bandwidth AND that could also guarantee no rebuffering at all
var bestLevel = this.findBestLevel(avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, config.abrBandWidthFactor, config.abrBandWidthUpFactor);
if (bestLevel >= 0) {
return bestLevel;
}
_utils_logger__WEBPACK_IMPORTED_MODULE_6__["logger"].trace((bufferStarvationDelay ? 'rebuffering expected' : 'buffer is empty') + ", finding optimal quality level"); // not possible to get rid of rebuffering ... let's try to find level that will guarantee less than maxStarvationDelay of rebuffering
// if no matching level found, logic will return 0
var maxStarvationDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxStarvationDelay) : config.maxStarvationDelay;
var bwFactor = config.abrBandWidthFactor;
var bwUpFactor = config.abrBandWidthUpFactor;
if (!bufferStarvationDelay) {
// in case buffer is empty, let's check if previous fragment was loaded to perform a bitrate test
var bitrateTestDelay = this.bitrateTestDelay;
if (bitrateTestDelay) {
// if it is the case, then we need to adjust our max starvation delay using maxLoadingDelay config value
// max video loading delay used in automatic start level selection :
// in that mode ABR controller will ensure that video loading time (ie the time to fetch the first fragment at lowest quality level +
// the time to fetch the fragment at the appropriate quality level is less than ```maxLoadingDelay``` )
// cap maxLoadingDelay and ensure it is not bigger 'than bitrate test' frag duration
var maxLoadingDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxLoadingDelay) : config.maxLoadingDelay;
maxStarvationDelay = maxLoadingDelay - bitrateTestDelay;
_utils_logger__WEBPACK_IMPORTED_MODULE_6__["logger"].trace("bitrate test took " + Math.round(1000 * bitrateTestDelay) + "ms, set first fragment max fetchDuration to " + Math.round(1000 * maxStarvationDelay) + " ms"); // don't use conservative factor on bitrate test
bwFactor = bwUpFactor = 1;
}
}
bestLevel = this.findBestLevel(avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay + maxStarvationDelay, bwFactor, bwUpFactor);
return Math.max(bestLevel, 0);
};
_proto.findBestLevel = function findBestLevel(currentBw, minAutoLevel, maxAutoLevel, maxFetchDuration, bwFactor, bwUpFactor) {
var _level$details;
var fragCurrent = this.fragCurrent,
partCurrent = this.partCurrent,
currentLevel = this.lastLoadedFragLevel;
var levels = this.hls.levels;
var level = levels[currentLevel];
var live = !!(level !== null && level !== void 0 && (_level$details = level.details) !== null && _level$details !== void 0 && _level$details.live);
var currentCodecSet = level === null || level === void 0 ? void 0 : level.codecSet;
var currentFragDuration = partCurrent ? partCurrent.duration : fragCurrent ? fragCurrent.duration : 0;
for (var i = maxAutoLevel; i >= minAutoLevel; i--) {
var levelInfo = levels[i];
if (!levelInfo || currentCodecSet && levelInfo.codecSet !== currentCodecSet) {
continue;
}
var levelDetails = levelInfo.details;
var avgDuration = (partCurrent ? levelDetails === null || levelDetails === void 0 ? void 0 : levelDetails.partTarget : levelDetails === null || levelDetails === void 0 ? void 0 : levelDetails.averagetargetduration) || currentFragDuration;
var adjustedbw = void 0; // follow algorithm captured from stagefright :
// https://android.googlesource.com/platform/frameworks/av/+/master/media/libstagefright/httplive/LiveSession.cpp
// Pick the highest bandwidth stream below or equal to estimated bandwidth.
// consider only 80% of the available bandwidth, but if we are switching up,
// be even more conservative (70%) to avoid overestimating and immediately
// switching back.
if (i <= currentLevel) {
adjustedbw = bwFactor * currentBw;
} else {
adjustedbw = bwUpFactor * currentBw;
}
var bitrate = levels[i].maxBitrate;
var fetchDuration = bitrate * avgDuration / adjustedbw;
_utils_logger__WEBPACK_IMPORTED_MODULE_6__["logger"].trace("level/adjustedbw/bitrate/avgDuration/maxFetchDuration/fetchDuration: " + i + "/" + Math.round(adjustedbw) + "/" + bitrate + "/" + avgDuration + "/" + maxFetchDuration + "/" + fetchDuration); // if adjusted bw is greater than level bitrate AND
if (adjustedbw > bitrate && ( // fragment fetchDuration unknown OR live stream OR fragment fetchDuration less than max allowed fetch duration, then this level matches
// we don't account for max Fetch Duration for live streams, this is to avoid switching down when near the edge of live sliding window ...
// special case to support startLevel = -1 (bitrateTest) on live streams : in that case we should not exit loop so that findBestLevel will return -1
!fetchDuration || live && !this.bitrateTestDelay || fetchDuration < maxFetchDuration)) {
// as we are looping from highest to lowest, this will return the best achievable quality level
return i;
}
} // not enough time budget even with quality level 0 ... rebuffering might happen
return -1;
};
_createClass(AbrController, [{
key: "nextAutoLevel",
get: function get() {
var forcedAutoLevel = this._nextAutoLevel;
var bwEstimator = this.bwEstimator; // in case next auto level has been forced, and bw not available or not reliable, return forced value
if (forcedAutoLevel !== -1 && (!bwEstimator || !bwEstimator.canEstimate())) {
return forcedAutoLevel;
} // compute next level using ABR logic
var nextABRAutoLevel = this.getNextABRAutoLevel(); // if forced auto level has been defined, use it to cap ABR computed quality level
if (forcedAutoLevel !== -1) {
nextABRAutoLevel = Math.min(forcedAutoLevel, nextABRAutoLevel);
}
return nextABRAutoLevel;
},
set: function set(nextLevel) {
this._nextAutoLevel = nextLevel;
}
}]);
return AbrController;
}();
/* harmony default export */ __webpack_exports__["default"] = (AbrController);
/***/ }),
/***/ "./src/controller/audio-stream-controller.ts":
/*!***************************************************!*\
!*** ./src/controller/audio-stream-controller.ts ***!
\***************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./base-stream-controller */ "./src/controller/base-stream-controller.ts");
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/buffer-helper */ "./src/utils/buffer-helper.ts");
/* harmony import */ var _fragment_tracker__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./fragment-tracker */ "./src/controller/fragment-tracker.ts");
/* harmony import */ var _types_level__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../types/level */ "./src/types/level.ts");
/* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts");
/* harmony import */ var _loader_fragment__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../loader/fragment */ "./src/loader/fragment.ts");
/* harmony import */ var _demux_chunk_cache__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../demux/chunk-cache */ "./src/demux/chunk-cache.ts");
/* harmony import */ var _demux_transmuxer_interface__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../demux/transmuxer-interface */ "./src/demux/transmuxer-interface.ts");
/* harmony import */ var _types_transmuxer__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../types/transmuxer */ "./src/types/transmuxer.ts");
/* harmony import */ var _fragment_finders__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./fragment-finders */ "./src/controller/fragment-finders.ts");
/* harmony import */ var _utils_discontinuities__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../utils/discontinuities */ "./src/utils/discontinuities.ts");
/* harmony import */ var _gap_controller__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./gap-controller */ "./src/controller/gap-controller.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
var TICK_INTERVAL = 100; // how often to tick in ms
var AudioStreamController = /*#__PURE__*/function (_BaseStreamController) {
_inheritsLoose(AudioStreamController, _BaseStreamController);
function AudioStreamController(hls, fragmentTracker) {
var _this;
_this = _BaseStreamController.call(this, hls, fragmentTracker, '[audio-stream-controller]') || this;
_this.videoBuffer = null;
_this.videoTrackCC = -1;
_this.waitingVideoCC = -1;
_this.audioSwitch = false;
_this.trackId = -1;
_this.waitingData = null;
_this.mainDetails = null;
_this._registerListeners();
return _this;
}
var _proto = AudioStreamController.prototype;
_proto.onHandlerDestroying = function onHandlerDestroying() {
this._unregisterListeners();
this.mainDetails = null;
};
_proto._registerListeners = function _registerListeners() {
var hls = this.hls;
hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].MANIFEST_LOADING, this.onManifestLoading, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].LEVEL_LOADED, this.onLevelLoaded, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].AUDIO_TRACKS_UPDATED, this.onAudioTracksUpdated, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].ERROR, this.onError, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].BUFFER_RESET, this.onBufferReset, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].BUFFER_CREATED, this.onBufferCreated, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].BUFFER_FLUSHED, this.onBufferFlushed, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].INIT_PTS_FOUND, this.onInitPtsFound, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_BUFFERED, this.onFragBuffered, this);
};
_proto._unregisterListeners = function _unregisterListeners() {
var hls = this.hls;
hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].MANIFEST_LOADING, this.onManifestLoading, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].LEVEL_LOADED, this.onLevelLoaded, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].AUDIO_TRACKS_UPDATED, this.onAudioTracksUpdated, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].ERROR, this.onError, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].BUFFER_RESET, this.onBufferReset, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].BUFFER_CREATED, this.onBufferCreated, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].BUFFER_FLUSHED, this.onBufferFlushed, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].INIT_PTS_FOUND, this.onInitPtsFound, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_BUFFERED, this.onFragBuffered, this);
} // INIT_PTS_FOUND is triggered when the video track parsed in the stream-controller has a new PTS value
;
_proto.onInitPtsFound = function onInitPtsFound(event, _ref) {
var frag = _ref.frag,
id = _ref.id,
initPTS = _ref.initPTS;
// Always update the new INIT PTS
// Can change due level switch
if (id === 'main') {
var cc = frag.cc;
this.initPTS[frag.cc] = initPTS;
this.log("InitPTS for cc: " + cc + " found from main: " + initPTS);
this.videoTrackCC = cc; // If we are waiting, tick immediately to unblock audio fragment transmuxing
if (this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_INIT_PTS) {
this.tick();
}
}
};
_proto.startLoad = function startLoad(startPosition) {
if (!this.levels) {
this.startPosition = startPosition;
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].STOPPED;
return;
}
var lastCurrentTime = this.lastCurrentTime;
this.stopLoad();
this.setInterval(TICK_INTERVAL);
this.fragLoadError = 0;
if (lastCurrentTime > 0 && startPosition === -1) {
this.log("Override startPosition with lastCurrentTime @" + lastCurrentTime.toFixed(3));
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
} else {
this.loadedmetadata = false;
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_TRACK;
}
this.nextLoadPosition = this.startPosition = this.lastCurrentTime = startPosition;
this.tick();
};
_proto.doTick = function doTick() {
switch (this.state) {
case _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE:
this.doTickIdle();
break;
case _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_TRACK:
{
var _levels$trackId;
var levels = this.levels,
trackId = this.trackId;
var details = levels === null || levels === void 0 ? void 0 : (_levels$trackId = levels[trackId]) === null || _levels$trackId === void 0 ? void 0 : _levels$trackId.details;
if (details) {
if (this.waitForCdnTuneIn(details)) {
break;
}
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_INIT_PTS;
}
break;
}
case _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].FRAG_LOADING_WAITING_RETRY:
{
var _this$media;
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) !== null && _this$media !== void 0 && _this$media.seeking) {
this.log('RetryDate reached, switch back to IDLE state');
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
}
break;
}
case _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_INIT_PTS:
{
// Ensure we don't get stuck in the WAITING_INIT_PTS state if the waiting frag CC doesn't match any initPTS
var waitingData = this.waitingData;
if (waitingData) {
var frag = waitingData.frag,
part = waitingData.part,
cache = waitingData.cache,
complete = waitingData.complete;
if (this.initPTS[frag.cc] !== undefined) {
this.waitingData = null;
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].FRAG_LOADING;
var payload = cache.flush();
var data = {
frag: frag,
part: part,
payload: payload,
networkDetails: null
};
this._handleFragmentLoadProgress(data);
if (complete) {
_BaseStreamController.prototype._handleFragmentLoadComplete.call(this, data);
}
} else if (this.videoTrackCC !== this.waitingVideoCC) {
// Drop waiting fragment if videoTrackCC has changed since waitingFragment was set and initPTS was not found
_utils_logger__WEBPACK_IMPORTED_MODULE_15__["logger"].log("Waiting fragment cc (" + frag.cc + ") cancelled because video is at cc " + this.videoTrackCC);
this.clearWaitingFragment();
} else {
// Drop waiting fragment if an earlier fragment is needed
var bufferInfo = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].bufferInfo(this.mediaBuffer, this.media.currentTime, this.config.maxBufferHole);
var waitingFragmentAtPosition = Object(_fragment_finders__WEBPACK_IMPORTED_MODULE_11__["fragmentWithinToleranceTest"])(bufferInfo.end, this.config.maxFragLookUpTolerance, frag);
if (waitingFragmentAtPosition < 0) {
_utils_logger__WEBPACK_IMPORTED_MODULE_15__["logger"].log("Waiting fragment cc (" + frag.cc + ") @ " + frag.start + " cancelled because another fragment at " + bufferInfo.end + " is needed");
this.clearWaitingFragment();
}
}
} else {
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
}
}
}
this.onTickEnd();
};
_proto.clearWaitingFragment = function clearWaitingFragment() {
var waitingData = this.waitingData;
if (waitingData) {
this.fragmentTracker.removeFragment(waitingData.frag);
this.waitingData = null;
this.waitingVideoCC = -1;
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
}
};
_proto.onTickEnd = function onTickEnd() {
var media = this.media;
if (!media || !media.readyState) {
// Exit early if we don't have media or if the media hasn't buffered anything yet (readyState 0)
return;
}
var mediaBuffer = this.mediaBuffer ? this.mediaBuffer : media;
var buffered = mediaBuffer.buffered;
if (!this.loadedmetadata && buffered.length) {
this.loadedmetadata = true;
}
this.lastCurrentTime = media.currentTime;
};
_proto.doTickIdle = function doTickIdle() {
var _frag$decryptdata, _frag$decryptdata2;
var hls = this.hls,
levels = this.levels,
media = this.media,
trackId = this.trackId;
var config = hls.config;
if (!levels || !levels[trackId]) {
return;
} // if video not attached AND
// start fragment already requested OR start frag prefetch not enabled
// exit loop
// => if media not attached but start frag prefetch is enabled and start frag not requested yet, we will not exit loop
if (!media && (this.startFragRequested || !config.startFragPrefetch)) {
return;
}
var pos = this.getLoadPosition();
if (!Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(pos)) {
return;
}
var levelInfo = levels[trackId];
var trackDetails = levelInfo.details;
if (!trackDetails || trackDetails.live && this.levelLastLoaded !== trackId || this.waitForCdnTuneIn(trackDetails)) {
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_TRACK;
return;
}
var frag = trackDetails.initSegment;
var targetBufferTime = 0;
if (!frag || frag.data) {
var mediaBuffer = this.mediaBuffer ? this.mediaBuffer : this.media;
var videoBuffer = this.videoBuffer ? this.videoBuffer : this.media;
var maxBufferHole = pos < config.maxBufferHole ? Math.max(_gap_controller__WEBPACK_IMPORTED_MODULE_13__["MAX_START_GAP_JUMP"], config.maxBufferHole) : config.maxBufferHole;
var bufferInfo = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].bufferInfo(mediaBuffer, pos, maxBufferHole);
var mainBufferInfo = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].bufferInfo(videoBuffer, pos, maxBufferHole);
var bufferLen = bufferInfo.len;
var maxConfigBuffer = Math.min(config.maxBufferLength, config.maxMaxBufferLength);
var maxBufLen = Math.max(maxConfigBuffer, mainBufferInfo.len);
var audioSwitch = this.audioSwitch; // if buffer length is less than maxBufLen try to load a new fragment
if (bufferLen >= maxBufLen && !audioSwitch) {
return;
}
if (!audioSwitch && this._streamEnded(bufferInfo, trackDetails)) {
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].BUFFER_EOS, {
type: 'audio'
});
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].ENDED;
return;
}
var fragments = trackDetails.fragments;
var start = fragments[0].start;
targetBufferTime = bufferInfo.end;
if (audioSwitch) {
targetBufferTime = pos; // if currentTime (pos) is less than alt audio playlist start time, it means that alt audio is ahead of currentTime
if (trackDetails.PTSKnown && pos < start) {
// if everything is buffered from pos to start or if audio buffer upfront, let's seek to start
if (bufferInfo.end > start || bufferInfo.nextStart) {
this.log('Alt audio track ahead of main track, seek to start of alt audio track');
media.currentTime = start + 0.05;
}
}
}
frag = this.getNextFragment(targetBufferTime, trackDetails);
if (!frag) {
return;
}
}
if (((_frag$decryptdata = frag.decryptdata) === null || _frag$decryptdata === void 0 ? void 0 : _frag$decryptdata.keyFormat) === 'identity' && !((_frag$decryptdata2 = frag.decryptdata) !== null && _frag$decryptdata2 !== void 0 && _frag$decryptdata2.key)) {
this.log("Loading key for " + frag.sn + " of [" + trackDetails.startSN + " ," + trackDetails.endSN + "],track " + trackId);
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].KEY_LOADING;
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].KEY_LOADING, {
frag: frag
});
} else {
this.loadFragment(frag, trackDetails, targetBufferTime);
}
};
_proto.onMediaDetaching = function onMediaDetaching() {
this.videoBuffer = null;
_BaseStreamController.prototype.onMediaDetaching.call(this);
};
_proto.onAudioTracksUpdated = function onAudioTracksUpdated(event, _ref2) {
var audioTracks = _ref2.audioTracks;
this.levels = audioTracks.map(function (mediaPlaylist) {
return new _types_level__WEBPACK_IMPORTED_MODULE_5__["Level"](mediaPlaylist);
});
};
_proto.onAudioTrackSwitching = function onAudioTrackSwitching(event, data) {
// if any URL found on new audio track, it is an alternate audio track
var altAudio = !!data.url;
this.trackId = data.id;
var fragCurrent = this.fragCurrent,
transmuxer = this.transmuxer;
if (fragCurrent !== null && fragCurrent !== void 0 && fragCurrent.loader) {
fragCurrent.loader.abort();
}
this.fragCurrent = null;
this.clearWaitingFragment(); // destroy useless transmuxer when switching audio to main
if (!altAudio) {
if (transmuxer) {
transmuxer.destroy();
this.transmuxer = null;
}
} else {
// switching to audio track, start timer if not already started
this.setInterval(TICK_INTERVAL);
} // should we switch tracks ?
if (altAudio) {
this.audioSwitch = true; // main audio track are handled by stream-controller, just do something if switching to alt audio track
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
} else {
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].STOPPED;
}
this.tick();
};
_proto.onManifestLoading = function onManifestLoading() {
this.mainDetails = null;
this.fragmentTracker.removeAllFragments();
this.startPosition = this.lastCurrentTime = 0;
};
_proto.onLevelLoaded = function onLevelLoaded(event, data) {
if (this.mainDetails === null) {
var mainDetails = this.mainDetails = data.details; // compute start position if we haven't already
var trackId = this.levelLastLoaded;
if (trackId !== null && this.levels && this.startPosition === -1 && mainDetails.live) {
var track = this.levels[trackId];
if (!track.details || !track.details.fragments[0]) {
return;
}
Object(_utils_discontinuities__WEBPACK_IMPORTED_MODULE_12__["alignPDT"])(track.details, mainDetails);
this.setStartPosition(track.details, track.details.fragments[0].start);
}
}
};
_proto.onAudioTrackLoaded = function onAudioTrackLoaded(event, data) {
var _track$details;
var levels = this.levels;
var newDetails = data.details,
trackId = data.id;
if (!levels) {
this.warn("Audio tracks were reset while loading level " + trackId);
return;
}
this.log("Track " + trackId + " loaded [" + newDetails.startSN + "," + newDetails.endSN + "],duration:" + newDetails.totalduration);
var track = levels[trackId];
var sliding = 0;
if (newDetails.live || (_track$details = track.details) !== null && _track$details !== void 0 && _track$details.live) {
var _this$mainDetails;
if (!newDetails.fragments[0]) {
newDetails.deltaUpdateFailed = true;
}
if (newDetails.deltaUpdateFailed) {
return;
}
if (!track.details && (_this$mainDetails = this.mainDetails) !== null && _this$mainDetails !== void 0 && _this$mainDetails.hasProgramDateTime && newDetails.hasProgramDateTime) {
Object(_utils_discontinuities__WEBPACK_IMPORTED_MODULE_12__["alignPDT"])(newDetails, this.mainDetails);
sliding = newDetails.fragments[0].start;
} else {
sliding = this.alignPlaylists(newDetails, track.details);
}
}
track.details = newDetails;
this.levelLastLoaded = trackId; // compute start position if we are aligned with the main playlist
if (!this.startFragRequested && (this.mainDetails || !newDetails.live)) {
this.setStartPosition(track.details, sliding);
} // only switch back to IDLE state if we were waiting for track to start downloading a new fragment
if (this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_TRACK && !this.waitForCdnTuneIn(newDetails)) {
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
} // trigger handler right now
this.tick();
};
_proto._handleFragmentLoadProgress = function _handleFragmentLoadProgress(data) {
var _details$initSegment;
var frag = data.frag,
part = data.part,
payload = data.payload;
var config = this.config,
trackId = this.trackId,
levels = this.levels;
if (!levels) {
this.warn("Audio tracks were reset while fragment load was in progress. Fragment " + frag.sn + " of level " + frag.level + " will not be buffered");
return;
}
var track = levels[trackId];
console.assert(track, 'Audio track is defined on fragment load progress');
var details = track.details;
console.assert(details, 'Audio track details are defined on fragment load progress');
var audioCodec = config.defaultAudioCodec || track.audioCodec || 'mp4a.40.2';
var transmuxer = this.transmuxer;
if (!transmuxer) {
transmuxer = this.transmuxer = new _demux_transmuxer_interface__WEBPACK_IMPORTED_MODULE_9__["default"](this.hls, _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].AUDIO, this._handleTransmuxComplete.bind(this), this._handleTransmuxerFlush.bind(this));
} // Check if we have video initPTS
// If not we need to wait for it
var initPTS = this.initPTS[frag.cc];
var initSegmentData = (_details$initSegment = details.initSegment) === null || _details$initSegment === void 0 ? void 0 : _details$initSegment.data;
if (initPTS !== undefined) {
// this.log(`Transmuxing ${sn} of [${details.startSN} ,${details.endSN}],track ${trackId}`);
// time Offset is accurate if level PTS is known, or if playlist is not sliding (not live)
var accurateTimeOffset = false; // details.PTSKnown || !details.live;
var partIndex = part ? part.index : -1;
var partial = partIndex !== -1;
var chunkMeta = new _types_transmuxer__WEBPACK_IMPORTED_MODULE_10__["ChunkMetadata"](frag.level, frag.sn, frag.stats.chunkCount, payload.byteLength, partIndex, partial);
transmuxer.push(payload, initSegmentData, audioCodec, '', frag, part, details.totalduration, accurateTimeOffset, chunkMeta, initPTS);
} else {
_utils_logger__WEBPACK_IMPORTED_MODULE_15__["logger"].log("Unknown video PTS for cc " + frag.cc + ", waiting for video PTS before demuxing audio frag " + frag.sn + " of [" + details.startSN + " ," + details.endSN + "],track " + trackId);
var _this$waitingData = this.waitingData = this.waitingData || {
frag: frag,
part: part,
cache: new _demux_chunk_cache__WEBPACK_IMPORTED_MODULE_8__["default"](),
complete: false
},
cache = _this$waitingData.cache;
cache.push(new Uint8Array(payload));
this.waitingVideoCC = this.videoTrackCC;
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_INIT_PTS;
}
};
_proto._handleFragmentLoadComplete = function _handleFragmentLoadComplete(fragLoadedData) {
if (this.waitingData) {
this.waitingData.complete = true;
return;
}
_BaseStreamController.prototype._handleFragmentLoadComplete.call(this, fragLoadedData);
};
_proto.onBufferReset = function onBufferReset()
/* event: Events.BUFFER_RESET */
{
// reset reference to sourcebuffers
this.mediaBuffer = this.videoBuffer = null;
this.loadedmetadata = false;
};
_proto.onBufferCreated = function onBufferCreated(event, data) {
var audioTrack = data.tracks.audio;
if (audioTrack) {
this.mediaBuffer = audioTrack.buffer;
}
if (data.tracks.video) {
this.videoBuffer = data.tracks.video.buffer;
}
};
_proto.onFragBuffered = function onFragBuffered(event, data) {
var frag = data.frag,
part = data.part;
if (frag.type !== _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].AUDIO) {
return;
}
if (this.fragContextChanged(frag)) {
// If a level switch was requested while a fragment was buffering, it will emit the FRAG_BUFFERED event upon completion
// Avoid setting state back to IDLE or concluding the audio switch; otherwise, the switched-to track will not buffer
this.warn("Fragment " + frag.sn + (part ? ' p: ' + part.index : '') + " of level " + frag.level + " finished buffering, but was aborted. state: " + this.state + ", audioSwitch: " + this.audioSwitch);
return;
}
if (frag.sn !== 'initSegment') {
this.fragPrevious = frag;
if (this.audioSwitch) {
this.audioSwitch = false;
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].AUDIO_TRACK_SWITCHED, {
id: this.trackId
});
}
}
this.fragBufferedComplete(frag, part);
};
_proto.onError = function onError(event, data) {
switch (data.details) {
case _errors__WEBPACK_IMPORTED_MODULE_14__["ErrorDetails"].FRAG_LOAD_ERROR:
case _errors__WEBPACK_IMPORTED_MODULE_14__["ErrorDetails"].FRAG_LOAD_TIMEOUT:
case _errors__WEBPACK_IMPORTED_MODULE_14__["ErrorDetails"].KEY_LOAD_ERROR:
case _errors__WEBPACK_IMPORTED_MODULE_14__["ErrorDetails"].KEY_LOAD_TIMEOUT:
// TODO: Skip fragments that do not belong to this.fragCurrent audio-group id
this.onFragmentOrKeyLoadError(_types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].AUDIO, data);
break;
case _errors__WEBPACK_IMPORTED_MODULE_14__["ErrorDetails"].AUDIO_TRACK_LOAD_ERROR:
case _errors__WEBPACK_IMPORTED_MODULE_14__["ErrorDetails"].AUDIO_TRACK_LOAD_TIMEOUT:
// when in ERROR state, don't switch back to IDLE state in case a non-fatal error is received
if (this.state !== _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].ERROR && this.state !== _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].STOPPED) {
// if fatal error, stop processing, otherwise move to IDLE to retry loading
this.state = data.fatal ? _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].ERROR : _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
this.warn(data.details + " while loading frag, switching to " + this.state + " state");
}
break;
case _errors__WEBPACK_IMPORTED_MODULE_14__["ErrorDetails"].BUFFER_FULL_ERROR:
// if in appending state
if (data.parent === 'audio' && (this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].PARSING || this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].PARSED)) {
var media = this.mediaBuffer;
var currentTime = this.media.currentTime;
var mediaBuffered = media && _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].isBuffered(media, currentTime) && _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].isBuffered(media, currentTime + 0.5); // reduce max buf len if current position is buffered
if (mediaBuffered) {
this.reduceMaxBufferLength();
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
} else {
// current position is not buffered, but browser is still complaining about buffer full error
// this happens on IE/Edge, refer to https://github.com/video-dev/hls.js/pull/708
// in that case flush the whole audio buffer to recover
this.warn('Buffer full error also media.currentTime is not buffered, flush audio buffer');
this.fragCurrent = null; // flush everything
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].BUFFER_FLUSHING, {
startOffset: 0,
endOffset: Number.POSITIVE_INFINITY,
type: 'audio'
});
}
}
break;
default:
break;
}
};
_proto.onBufferFlushed = function onBufferFlushed(event, _ref3) {
var type = _ref3.type;
if (type === _loader_fragment__WEBPACK_IMPORTED_MODULE_7__["ElementaryStreamTypes"].AUDIO) {
var media = this.mediaBuffer ? this.mediaBuffer : this.media;
this.afterBufferFlushed(media, type);
}
};
_proto._handleTransmuxComplete = function _handleTransmuxComplete(transmuxResult) {
var _id3$samples;
var id = 'audio';
var hls = this.hls;
var remuxResult = transmuxResult.remuxResult,
chunkMeta = transmuxResult.chunkMeta;
var context = this.getCurrentContext(chunkMeta);
if (!context) {
this.warn("The loading context changed while buffering fragment " + chunkMeta.sn + " of level " + chunkMeta.level + ". This chunk will not be buffered.");
this.resetLiveStartWhenNotLoaded(chunkMeta.level);
return;
}
var frag = context.frag,
part = context.part;
var audio = remuxResult.audio,
text = remuxResult.text,
id3 = remuxResult.id3,
initSegment = remuxResult.initSegment; // Check if the current fragment has been aborted. We check this by first seeing if we're still playing the current level.
// If we are, subsequently check if the currently loading fragment (fragCurrent) has changed.
if (this.fragContextChanged(frag)) {
return;
}
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].PARSING;
if (this.audioSwitch && audio) {
this.completeAudioSwitch();
}
if (initSegment !== null && initSegment !== void 0 && initSegment.tracks) {
this._bufferInitSegment(initSegment.tracks, frag, chunkMeta);
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_PARSING_INIT_SEGMENT, {
frag: frag,
id: id,
tracks: initSegment.tracks
}); // Only flush audio from old audio tracks when PTS is known on new audio track
}
if (audio) {
var startPTS = audio.startPTS,
endPTS = audio.endPTS,
startDTS = audio.startDTS,
endDTS = audio.endDTS;
if (part) {
part.elementaryStreams[_loader_fragment__WEBPACK_IMPORTED_MODULE_7__["ElementaryStreamTypes"].AUDIO] = {
startPTS: startPTS,
endPTS: endPTS,
startDTS: startDTS,
endDTS: endDTS
};
}
frag.setElementaryStreamInfo(_loader_fragment__WEBPACK_IMPORTED_MODULE_7__["ElementaryStreamTypes"].AUDIO, startPTS, endPTS, startDTS, endDTS);
this.bufferFragmentData(audio, frag, part, chunkMeta);
}
if (id3 !== null && id3 !== void 0 && (_id3$samples = id3.samples) !== null && _id3$samples !== void 0 && _id3$samples.length) {
var emittedID3 = _extends({
frag: frag,
id: id
}, id3);
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_PARSING_METADATA, emittedID3);
}
if (text) {
var emittedText = _extends({
frag: frag,
id: id
}, text);
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_PARSING_USERDATA, emittedText);
}
};
_proto._bufferInitSegment = function _bufferInitSegment(tracks, frag, chunkMeta) {
if (this.state !== _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].PARSING) {
return;
} // delete any video track found on audio transmuxer
if (tracks.video) {
delete tracks.video;
} // include levelCodec in audio and video tracks
var track = tracks.audio;
if (!track) {
return;
}
track.levelCodec = track.codec;
track.id = 'audio';
this.log("Init audio buffer, container:" + track.container + ", codecs[parsed]=[" + track.codec + "]");
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].BUFFER_CODECS, tracks);
var initSegment = track.initSegment;
if (initSegment !== null && initSegment !== void 0 && initSegment.byteLength) {
var segment = {
type: 'audio',
frag: frag,
part: null,
chunkMeta: chunkMeta,
parent: frag.type,
data: initSegment
};
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].BUFFER_APPENDING, segment);
} // trigger handler right now
this.tick();
};
_proto.loadFragment = function loadFragment(frag, trackDetails, targetBufferTime) {
// only load if fragment is not loaded or if in audio switch
var fragState = this.fragmentTracker.getState(frag);
this.fragCurrent = frag; // we force a frag loading in audio switch as fragment tracker might not have evicted previous frags in case of quick audio switch
if (this.audioSwitch || fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_4__["FragmentState"].NOT_LOADED || fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_4__["FragmentState"].PARTIAL) {
if (frag.sn === 'initSegment') {
this._loadInitSegment(frag);
} else if (trackDetails.live && !Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(this.initPTS[frag.cc])) {
this.log("Waiting for video PTS in continuity counter " + frag.cc + " of live stream before loading audio fragment " + frag.sn + " of level " + this.trackId);
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_INIT_PTS;
} else {
this.startFragRequested = true;
_BaseStreamController.prototype.loadFragment.call(this, frag, trackDetails, targetBufferTime);
}
}
};
_proto.completeAudioSwitch = function completeAudioSwitch() {
var hls = this.hls,
media = this.media,
trackId = this.trackId;
if (media) {
this.log('Switching audio track : flushing all audio');
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].BUFFER_FLUSHING, {
startOffset: 0,
endOffset: Number.POSITIVE_INFINITY,
type: 'audio'
});
}
this.audioSwitch = false;
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].AUDIO_TRACK_SWITCHED, {
id: trackId
});
};
return AudioStreamController;
}(_base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["default"]);
/* harmony default export */ __webpack_exports__["default"] = (AudioStreamController);
/***/ }),
/***/ "./src/controller/audio-track-controller.ts":
/*!**************************************************!*\
!*** ./src/controller/audio-track-controller.ts ***!
\**************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
/* harmony import */ var _base_playlist_controller__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./base-playlist-controller */ "./src/controller/base-playlist-controller.ts");
/* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts");
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
var AudioTrackController = /*#__PURE__*/function (_BasePlaylistControll) {
_inheritsLoose(AudioTrackController, _BasePlaylistControll);
function AudioTrackController(hls) {
var _this;
_this = _BasePlaylistControll.call(this, hls, '[audio-track-controller]') || this;
_this.tracks = [];
_this.groupId = null;
_this.tracksInGroup = [];
_this.trackId = -1;
_this.selectDefaultTrack = true;
_this.registerListeners();
return _this;
}
var _proto = AudioTrackController.prototype;
_proto.registerListeners = function registerListeners() {
var hls = this.hls;
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MANIFEST_LOADING, this.onManifestLoading, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MANIFEST_PARSED, this.onManifestParsed, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].LEVEL_LOADING, this.onLevelLoading, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].LEVEL_SWITCHING, this.onLevelSwitching, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, this.onError, this);
};
_proto.unregisterListeners = function unregisterListeners() {
var hls = this.hls;
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MANIFEST_LOADING, this.onManifestLoading, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MANIFEST_PARSED, this.onManifestParsed, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].LEVEL_LOADING, this.onLevelLoading, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].LEVEL_SWITCHING, this.onLevelSwitching, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, this.onError, this);
};
_proto.destroy = function destroy() {
this.unregisterListeners();
this.tracks.length = 0;
this.tracksInGroup.length = 0;
_BasePlaylistControll.prototype.destroy.call(this);
};
_proto.onManifestLoading = function onManifestLoading() {
this.tracks = [];
this.groupId = null;
this.tracksInGroup = [];
this.trackId = -1;
this.selectDefaultTrack = true;
};
_proto.onManifestParsed = function onManifestParsed(event, data) {
this.tracks = data.audioTracks || [];
};
_proto.onAudioTrackLoaded = function onAudioTrackLoaded(event, data) {
var id = data.id,
details = data.details;
var currentTrack = this.tracksInGroup[id];
if (!currentTrack) {
this.warn("Invalid audio track id " + id);
return;
}
var curDetails = currentTrack.details;
currentTrack.details = data.details;
this.log("audioTrack " + id + " loaded [" + details.startSN + "-" + details.endSN + "]");
if (id === this.trackId) {
this.retryCount = 0;
this.playlistLoaded(id, data, curDetails);
}
};
_proto.onLevelLoading = function onLevelLoading(event, data) {
this.switchLevel(data.level);
};
_proto.onLevelSwitching = function onLevelSwitching(event, data) {
this.switchLevel(data.level);
};
_proto.switchLevel = function switchLevel(levelIndex) {
var levelInfo = this.hls.levels[levelIndex];
if (!(levelInfo !== null && levelInfo !== void 0 && levelInfo.audioGroupIds)) {
return;
}
var audioGroupId = levelInfo.audioGroupIds[levelInfo.urlId];
if (this.groupId !== audioGroupId) {
this.groupId = audioGroupId;
var audioTracks = this.tracks.filter(function (track) {
return !audioGroupId || track.groupId === audioGroupId;
}); // Disable selectDefaultTrack if there are no default tracks
if (this.selectDefaultTrack && !audioTracks.some(function (track) {
return track.default;
})) {
this.selectDefaultTrack = false;
}
this.tracksInGroup = audioTracks;
var audioTracksUpdated = {
audioTracks: audioTracks
};
this.log("Updating audio tracks, " + audioTracks.length + " track(s) found in \"" + audioGroupId + "\" group-id");
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].AUDIO_TRACKS_UPDATED, audioTracksUpdated);
this.selectInitialTrack();
}
};
_proto.onError = function onError(event, data) {
_BasePlaylistControll.prototype.onError.call(this, event, data);
if (data.fatal || !data.context) {
return;
}
if (data.context.type === _types_loader__WEBPACK_IMPORTED_MODULE_3__["PlaylistContextType"].AUDIO_TRACK && data.context.id === this.trackId && data.context.groupId === this.groupId) {
this.retryLoadingOrFail(data);
}
};
_proto.setAudioTrack = function setAudioTrack(newId) {
var _tracks$newId;
var tracks = this.tracksInGroup; // noop on same audio track id as already set
if (this.trackId === newId && (_tracks$newId = tracks[newId]) !== null && _tracks$newId !== void 0 && _tracks$newId.details) {
return;
} // check if level idx is valid
if (newId < 0 || newId >= tracks.length) {
this.warn('Invalid id passed to audio-track controller');
return;
} // stopping live reloading timer if any
this.clearTimer();
var lastTrack = tracks[this.trackId];
var track = tracks[newId];
this.log("Now switching to audio-track index " + newId);
this.trackId = newId;
var url = track.url,
type = track.type,
id = track.id;
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].AUDIO_TRACK_SWITCHING, {
id: id,
type: type,
url: url
});
var hlsUrlParameters = this.switchParams(track.url, lastTrack === null || lastTrack === void 0 ? void 0 : lastTrack.details);
this.loadPlaylist(hlsUrlParameters);
};
_proto.selectInitialTrack = function selectInitialTrack() {
var _audioTracks$this$tra;
var audioTracks = this.tracksInGroup;
console.assert(audioTracks.length, 'Initial audio track should be selected when tracks are known');
var currentAudioTrackName = (_audioTracks$this$tra = audioTracks[this.trackId]) === null || _audioTracks$this$tra === void 0 ? void 0 : _audioTracks$this$tra.name;
var trackId = this.findTrackId(currentAudioTrackName) || this.findTrackId();
if (trackId !== -1) {
this.setAudioTrack(trackId);
} else {
this.warn("No track found for running audio group-ID: " + this.groupId);
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].MEDIA_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].AUDIO_TRACK_LOAD_ERROR,
fatal: true
});
}
};
_proto.findTrackId = function findTrackId(name) {
var audioTracks = this.tracksInGroup;
for (var i = 0; i < audioTracks.length; i++) {
var track = audioTracks[i];
if (!this.selectDefaultTrack || track.default) {
if (!name || name === track.name) {
return track.id;
}
}
}
return -1;
};
_proto.loadPlaylist = function loadPlaylist(hlsUrlParameters) {
var audioTrack = this.tracksInGroup[this.trackId];
if (this.shouldLoadTrack(audioTrack)) {
var id = audioTrack.id;
var groupId = audioTrack.groupId;
var url = audioTrack.url;
if (hlsUrlParameters) {
try {
url = hlsUrlParameters.addDirectives(url);
} catch (error) {
this.warn("Could not construct new URL with HLS Delivery Directives: " + error);
}
} // track not retrieved yet, or live playlist we need to (re)load it
this.log("loading audio-track playlist for id: " + id);
this.clearTimer();
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].AUDIO_TRACK_LOADING, {
url: url,
id: id,
groupId: groupId,
deliveryDirectives: hlsUrlParameters || null
});
}
};
_createClass(AudioTrackController, [{
key: "audioTracks",
get: function get() {
return this.tracksInGroup;
}
}, {
key: "audioTrack",
get: function get() {
return this.trackId;
},
set: function set(newId) {
// If audio track is selected from API then don't choose from the manifest default track
this.selectDefaultTrack = false;
this.setAudioTrack(newId);
}
}]);
return AudioTrackController;
}(_base_playlist_controller__WEBPACK_IMPORTED_MODULE_2__["default"]);
/* harmony default export */ __webpack_exports__["default"] = (AudioTrackController);
/***/ }),
/***/ "./src/controller/base-playlist-controller.ts":
/*!****************************************************!*\
!*** ./src/controller/base-playlist-controller.ts ***!
\****************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return BasePlaylistController; });
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var _types_level__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../types/level */ "./src/types/level.ts");
/* harmony import */ var _level_helper__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./level-helper */ "./src/controller/level-helper.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
var BasePlaylistController = /*#__PURE__*/function () {
function BasePlaylistController(hls, logPrefix) {
this.hls = void 0;
this.timer = -1;
this.canLoad = false;
this.retryCount = 0;
this.log = void 0;
this.warn = void 0;
this.log = _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].log.bind(_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"], logPrefix + ":");
this.warn = _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn.bind(_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"], logPrefix + ":");
this.hls = hls;
}
var _proto = BasePlaylistController.prototype;
_proto.destroy = function destroy() {
this.clearTimer(); // @ts-ignore
this.hls = this.log = this.warn = null;
};
_proto.onError = function onError(event, data) {
if (data.fatal && data.type === _errors__WEBPACK_IMPORTED_MODULE_4__["ErrorTypes"].NETWORK_ERROR) {
this.clearTimer();
}
};
_proto.clearTimer = function clearTimer() {
clearTimeout(this.timer);
this.timer = -1;
};
_proto.startLoad = function startLoad() {
this.canLoad = true;
this.retryCount = 0;
this.loadPlaylist();
};
_proto.stopLoad = function stopLoad() {
this.canLoad = false;
this.clearTimer();
};
_proto.switchParams = function switchParams(playlistUri, previous) {
var renditionReports = previous === null || previous === void 0 ? void 0 : previous.renditionReports;
if (renditionReports) {
for (var i = 0; i < renditionReports.length; i++) {
var attr = renditionReports[i];
var uri = '' + attr.URI;
if (uri === playlistUri.substr(-uri.length)) {
var msn = parseInt(attr['LAST-MSN']);
var part = parseInt(attr['LAST-PART']);
if (previous && this.hls.config.lowLatencyMode) {
var currentGoal = Math.min(previous.age - previous.partTarget, previous.targetduration);
if (part !== undefined && currentGoal > previous.partTarget) {
part += 1;
}
}
if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(msn)) {
return new _types_level__WEBPACK_IMPORTED_MODULE_1__["HlsUrlParameters"](msn, Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(part) ? part : undefined, _types_level__WEBPACK_IMPORTED_MODULE_1__["HlsSkip"].No);
}
}
}
}
};
_proto.loadPlaylist = function loadPlaylist(hlsUrlParameters) {};
_proto.shouldLoadTrack = function shouldLoadTrack(track) {
return this.canLoad && track && !!track.url && (!track.details || track.details.live);
};
_proto.playlistLoaded = function playlistLoaded(index, data, previousDetails) {
var _this = this;
var details = data.details,
stats = data.stats; // Set last updated date-time
var elapsed = stats.loading.end ? Math.max(0, self.performance.now() - stats.loading.end) : 0;
details.advancedDateTime = Date.now() - elapsed; // if current playlist is a live playlist, arm a timer to reload it
if (details.live || previousDetails !== null && previousDetails !== void 0 && previousDetails.live) {
details.reloaded(previousDetails);
if (previousDetails) {
this.log("live playlist " + index + " " + (details.advanced ? 'REFRESHED ' + details.lastPartSn + '-' + details.lastPartIndex : 'MISSED'));
} // Merge live playlists to adjust fragment starts and fill in delta playlist skipped segments
if (previousDetails && details.fragments.length > 0) {
_level_helper__WEBPACK_IMPORTED_MODULE_2__["mergeDetails"](previousDetails, details);
if (!details.advanced) {
details.advancedDateTime = previousDetails.advancedDateTime;
}
}
if (!this.canLoad || !details.live) {
return;
}
if (details.canBlockReload && details.endSN && details.advanced) {
var _data$deliveryDirecti;
// Load level with LL-HLS delivery directives
var lowLatencyMode = this.hls.config.lowLatencyMode;
var lastPartIndex = details.lastPartIndex;
var msn;
var part;
if (lowLatencyMode) {
msn = lastPartIndex !== -1 ? details.lastPartSn : details.endSN + 1;
part = lastPartIndex !== -1 ? lastPartIndex + 1 : undefined;
} else {
// This playlist update will be late by one part (0). There is no way to know the last part number,
// or request just the next sn without a part in most implementations.
msn = lastPartIndex !== -1 ? details.lastPartSn + 1 : details.endSN + 1;
part = lastPartIndex !== -1 ? 0 : undefined;
} // Low-Latency CDN Tune-in: "age" header and time since load indicates we're behind by more than one part
// Update directives to obtain the Playlist that has the estimated additional duration of media
var lastAdvanced = details.age;
var cdnAge = lastAdvanced + details.ageHeader;
var currentGoal = Math.min(cdnAge - details.partTarget, details.targetduration * 1.5);
if (currentGoal > 0) {
if (previousDetails && currentGoal > previousDetails.tuneInGoal) {
// If we attempted to get the next or latest playlist update, but currentGoal increased,
// then we either can't catchup, or the "age" header cannot be trusted.
this.warn("CDN Tune-in goal increased from: " + previousDetails.tuneInGoal + " to: " + currentGoal + " with playlist age: " + details.age);
currentGoal = 0;
} else {
var segments = Math.floor(currentGoal / details.targetduration);
msn += segments;
if (part !== undefined) {
var parts = Math.round(currentGoal % details.targetduration / details.partTarget);
part += parts;
}
this.log("CDN Tune-in age: " + details.ageHeader + "s last advanced " + lastAdvanced.toFixed(2) + "s goal: " + currentGoal + " skip sn " + segments + " to part " + part);
}
details.tuneInGoal = currentGoal;
}
var skip = Object(_types_level__WEBPACK_IMPORTED_MODULE_1__["getSkipValue"])(details, msn);
if ((_data$deliveryDirecti = data.deliveryDirectives) !== null && _data$deliveryDirecti !== void 0 && _data$deliveryDirecti.skip) {
if (details.deltaUpdateFailed) {
msn = data.deliveryDirectives.msn;
part = data.deliveryDirectives.part;
skip = _types_level__WEBPACK_IMPORTED_MODULE_1__["HlsSkip"].No;
}
}
this.loadPlaylist(new _types_level__WEBPACK_IMPORTED_MODULE_1__["HlsUrlParameters"](msn, part, skip));
return;
}
var reloadInterval = Object(_level_helper__WEBPACK_IMPORTED_MODULE_2__["computeReloadInterval"])(details, stats);
this.log("reload live playlist " + index + " in " + Math.round(reloadInterval) + " ms");
this.timer = self.setTimeout(function () {
return _this.loadPlaylist();
}, reloadInterval);
} else {
this.clearTimer();
}
};
_proto.retryLoadingOrFail = function retryLoadingOrFail(errorEvent) {
var _this2 = this;
var config = this.hls.config;
var retry = this.retryCount < config.levelLoadingMaxRetry;
if (retry) {
var _errorEvent$context;
this.retryCount++;
if (errorEvent.details.indexOf('LoadTimeOut') > -1 && (_errorEvent$context = errorEvent.context) !== null && _errorEvent$context !== void 0 && _errorEvent$context.deliveryDirectives) {
// The LL-HLS request already timed out so retry immediately
this.warn("retry playlist loading #" + this.retryCount + " after \"" + errorEvent.details + "\"");
this.loadPlaylist();
} else {
// exponential backoff capped to max retry timeout
var delay = Math.min(Math.pow(2, this.retryCount) * config.levelLoadingRetryDelay, config.levelLoadingMaxRetryTimeout); // Schedule level/track reload
this.timer = self.setTimeout(function () {
return _this2.loadPlaylist();
}, delay);
this.warn("retry playlist loading #" + this.retryCount + " in " + delay + " ms after \"" + errorEvent.details + "\"");
}
} else {
this.warn("cannot recover from error \"" + errorEvent.details + "\""); // stopping live reloading timer if any
this.clearTimer(); // switch error to fatal
errorEvent.fatal = true;
}
return retry;
};
return BasePlaylistController;
}();
/***/ }),
/***/ "./src/controller/base-stream-controller.ts":
/*!**************************************************!*\
!*** ./src/controller/base-stream-controller.ts ***!
\**************************************************/
/*! exports provided: State, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "State", function() { return State; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return BaseStreamController; });
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var _task_loop__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../task-loop */ "./src/task-loop.ts");
/* harmony import */ var _fragment_tracker__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./fragment-tracker */ "./src/controller/fragment-tracker.ts");
/* harmony import */ var _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/buffer-helper */ "./src/utils/buffer-helper.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
/* harmony import */ var _level_helper__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./level-helper */ "./src/controller/level-helper.ts");
/* harmony import */ var _types_transmuxer__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../types/transmuxer */ "./src/types/transmuxer.ts");
/* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../utils/mp4-tools */ "./src/utils/mp4-tools.ts");
/* harmony import */ var _utils_discontinuities__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../utils/discontinuities */ "./src/utils/discontinuities.ts");
/* harmony import */ var _fragment_finders__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./fragment-finders */ "./src/controller/fragment-finders.ts");
/* harmony import */ var _loader_fragment_loader__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../loader/fragment-loader */ "./src/loader/fragment-loader.ts");
/* harmony import */ var _crypt_decrypter__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../crypt/decrypter */ "./src/crypt/decrypter.ts");
/* harmony import */ var _utils_time_ranges__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../utils/time-ranges */ "./src/utils/time-ranges.ts");
/* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts");
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
var State = {
STOPPED: 'STOPPED',
IDLE: 'IDLE',
KEY_LOADING: 'KEY_LOADING',
FRAG_LOADING: 'FRAG_LOADING',
FRAG_LOADING_WAITING_RETRY: 'FRAG_LOADING_WAITING_RETRY',
WAITING_TRACK: 'WAITING_TRACK',
PARSING: 'PARSING',
PARSED: 'PARSED',
BACKTRACKING: 'BACKTRACKING',
ENDED: 'ENDED',
ERROR: 'ERROR',
WAITING_INIT_PTS: 'WAITING_INIT_PTS',
WAITING_LEVEL: 'WAITING_LEVEL'
};
var BaseStreamController = /*#__PURE__*/function (_TaskLoop) {
_inheritsLoose(BaseStreamController, _TaskLoop);
function BaseStreamController(hls, fragmentTracker, logPrefix) {
var _this;
_this = _TaskLoop.call(this) || this;
_this.hls = void 0;
_this.fragPrevious = null;
_this.fragCurrent = null;
_this.fragmentTracker = void 0;
_this.transmuxer = null;
_this._state = State.STOPPED;
_this.media = void 0;
_this.mediaBuffer = void 0;
_this.config = void 0;
_this.bitrateTest = false;
_this.lastCurrentTime = 0;
_this.nextLoadPosition = 0;
_this.startPosition = 0;
_this.loadedmetadata = false;
_this.fragLoadError = 0;
_this.retryDate = 0;
_this.levels = null;
_this.fragmentLoader = void 0;
_this.levelLastLoaded = null;
_this.startFragRequested = false;
_this.decrypter = void 0;
_this.initPTS = [];
_this.onvseeking = null;
_this.onvended = null;
_this.logPrefix = '';
_this.log = void 0;
_this.warn = void 0;
_this.logPrefix = logPrefix;
_this.log = _utils_logger__WEBPACK_IMPORTED_MODULE_4__["logger"].log.bind(_utils_logger__WEBPACK_IMPORTED_MODULE_4__["logger"], logPrefix + ":");
_this.warn = _utils_logger__WEBPACK_IMPORTED_MODULE_4__["logger"].warn.bind(_utils_logger__WEBPACK_IMPORTED_MODULE_4__["logger"], logPrefix + ":");
_this.hls = hls;
_this.fragmentLoader = new _loader_fragment_loader__WEBPACK_IMPORTED_MODULE_12__["default"](hls.config);
_this.fragmentTracker = fragmentTracker;
_this.config = hls.config;
_this.decrypter = new _crypt_decrypter__WEBPACK_IMPORTED_MODULE_13__["default"](hls, hls.config);
hls.on(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].KEY_LOADED, _this.onKeyLoaded, _assertThisInitialized(_this));
return _this;
}
var _proto = BaseStreamController.prototype;
_proto.doTick = function doTick() {
this.onTickEnd();
};
_proto.onTickEnd = function onTickEnd() {} // eslint-disable-next-line @typescript-eslint/no-unused-vars
;
_proto.startLoad = function startLoad(startPosition) {};
_proto.stopLoad = function stopLoad() {
this.fragmentLoader.abort();
var frag = this.fragCurrent;
if (frag) {
this.fragmentTracker.removeFragment(frag);
}
if (this.transmuxer) {
this.transmuxer.destroy();
this.transmuxer = null;
}
this.fragCurrent = null;
this.fragPrevious = null;
this.clearInterval();
this.clearNextTick();
this.state = State.STOPPED;
};
_proto._streamEnded = function _streamEnded(bufferInfo, levelDetails) {
var fragCurrent = this.fragCurrent,
fragmentTracker = this.fragmentTracker; // we just got done loading the final fragment and there is no other buffered range after ...
// rationale is that in case there are any buffered ranges after, it means that there are unbuffered portion in between
// so we should not switch to ENDED in that case, to be able to buffer them
if (!levelDetails.live && fragCurrent && fragCurrent.sn === levelDetails.endSN && !bufferInfo.nextStart) {
var fragState = fragmentTracker.getState(fragCurrent);
return fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_2__["FragmentState"].PARTIAL || fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_2__["FragmentState"].OK;
}
return false;
};
_proto.onMediaAttached = function onMediaAttached(event, data) {
var media = this.media = this.mediaBuffer = data.media;
this.onvseeking = this.onMediaSeeking.bind(this);
this.onvended = this.onMediaEnded.bind(this);
media.addEventListener('seeking', this.onvseeking);
media.addEventListener('ended', this.onvended);
var config = this.config;
if (this.levels && config.autoStartLoad && this.state === State.STOPPED) {
this.startLoad(config.startPosition);
}
};
_proto.onMediaDetaching = function onMediaDetaching() {
var media = this.media;
if (media !== null && media !== void 0 && media.ended) {
this.log('MSE detaching and video ended, reset startPosition');
this.startPosition = this.lastCurrentTime = 0;
} // remove video listeners
if (media) {
media.removeEventListener('seeking', this.onvseeking);
media.removeEventListener('ended', this.onvended);
this.onvseeking = this.onvended = null;
}
this.media = this.mediaBuffer = null;
this.loadedmetadata = false;
this.fragmentTracker.removeAllFragments();
this.stopLoad();
};
_proto.onMediaSeeking = function onMediaSeeking() {
var config = this.config,
fragCurrent = this.fragCurrent,
media = this.media,
mediaBuffer = this.mediaBuffer,
state = this.state;
var currentTime = media ? media.currentTime : null;
var bufferInfo = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].bufferInfo(mediaBuffer || media, currentTime, config.maxBufferHole);
this.log("media seeking to " + (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(currentTime) ? currentTime.toFixed(3) : currentTime) + ", state: " + state);
if (state === State.ENDED) {
// if seeking to unbuffered area, clean up fragPrevious
if (!bufferInfo.len) {
this.fragPrevious = null;
this.fragCurrent = null;
} // switch to IDLE state to check for potential new fragment
this.state = State.IDLE;
} else if (fragCurrent && !bufferInfo.len) {
// check if we are seeking to a unbuffered area AND if frag loading is in progress
var tolerance = config.maxFragLookUpTolerance;
var fragStartOffset = fragCurrent.start - tolerance;
var fragEndOffset = fragCurrent.start + fragCurrent.duration + tolerance; // check if the seek position will be out of currently loaded frag range : if out cancel frag load, if in, don't do anything
if (currentTime < fragStartOffset || currentTime > fragEndOffset) {
if (fragCurrent.loader) {
this.log('seeking outside of buffer while fragment load in progress, cancel fragment load');
fragCurrent.loader.abort();
}
this.fragCurrent = null;
this.fragPrevious = null; // switch to IDLE state to load new fragment
this.state = State.IDLE;
}
}
if (media) {
this.lastCurrentTime = currentTime;
} // in case seeking occurs although no media buffered, adjust startPosition and nextLoadPosition to seek target
if (!this.loadedmetadata && !bufferInfo.len) {
this.nextLoadPosition = this.startPosition = currentTime;
} // tick to speed up processing
this.tick();
};
_proto.onMediaEnded = function onMediaEnded() {
// reset startPosition and lastCurrentTime to restart playback @ stream beginning
this.startPosition = this.lastCurrentTime = 0;
};
_proto.onKeyLoaded = function onKeyLoaded(event, data) {
if (this.state === State.KEY_LOADING && this.levels) {
this.state = State.IDLE;
var levelDetails = this.levels[data.frag.level].details;
if (levelDetails) {
this.loadFragment(data.frag, levelDetails, data.frag.start);
}
}
};
_proto.onHandlerDestroying = function onHandlerDestroying() {
this.stopLoad();
_TaskLoop.prototype.onHandlerDestroying.call(this);
};
_proto.onHandlerDestroyed = function onHandlerDestroyed() {
this.state = State.STOPPED;
this.hls.off(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].KEY_LOADED, this.onKeyLoaded, this);
if (this.fragmentLoader) {
this.fragmentLoader.destroy();
}
if (this.decrypter) {
this.decrypter.destroy();
} // @ts-ignore
this.hls = this.log = this.warn = this.decrypter = this.fragmentLoader = this.fragmentTracker = null;
_TaskLoop.prototype.onHandlerDestroyed.call(this);
};
_proto.loadFragment = function loadFragment(frag, levelDetails, targetBufferTime) {
this._loadFragForPlayback(frag, levelDetails, targetBufferTime);
};
_proto._loadFragForPlayback = function _loadFragForPlayback(frag, levelDetails, targetBufferTime) {
var _this2 = this;
var progressCallback = function progressCallback(data) {
if (_this2.fragContextChanged(frag)) {
_this2.warn("Fragment " + frag.sn + (data.part ? ' p: ' + data.part.index : '') + " of level " + frag.level + " was dropped during download.");
_this2.fragmentTracker.removeFragment(frag);
return;
}
frag.stats.chunkCount++;
_this2._handleFragmentLoadProgress(data);
};
this._doFragLoad(frag, levelDetails, targetBufferTime, progressCallback).then(function (data) {
if (!data) {
// if we're here we probably needed to backtrack or are waiting for more parts
return;
}
_this2.fragLoadError = 0;
if (_this2.fragContextChanged(frag)) {
if (_this2.state === State.FRAG_LOADING || _this2.state === State.BACKTRACKING) {
_this2.fragmentTracker.removeFragment(frag);
_this2.state = State.IDLE;
}
return;
}
if ('payload' in data) {
_this2.log("Loaded fragment " + frag.sn + " of level " + frag.level);
_this2.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].FRAG_LOADED, data); // Tracker backtrack must be called after onFragLoaded to update the fragment entity state to BACKTRACKED
// This happens after handleTransmuxComplete when the worker or progressive is disabled
if (_this2.state === State.BACKTRACKING) {
_this2.fragmentTracker.backtrack(frag, data);
_this2.resetFragmentLoading(frag);
return;
}
} // Pass through the whole payload; controllers not implementing progressive loading receive data from this callback
_this2._handleFragmentLoadComplete(data);
}).catch(function (reason) {
_this2.warn(reason);
_this2.resetFragmentLoading(frag);
});
};
_proto.flushMainBuffer = function flushMainBuffer(startOffset, endOffset, type) {
if (type === void 0) {
type = null;
}
// When alternate audio is playing, the audio-stream-controller is responsible for the audio buffer. Otherwise,
// passing a null type flushes both buffers
var flushScope = {
startOffset: startOffset,
endOffset: endOffset,
type: type
}; // Reset load errors on flush
this.fragLoadError = 0;
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].BUFFER_FLUSHING, flushScope);
};
_proto._loadInitSegment = function _loadInitSegment(frag) {
var _this3 = this;
this._doFragLoad(frag).then(function (data) {
if (!data || _this3.fragContextChanged(frag) || !_this3.levels) {
throw new Error('init load aborted');
}
return data;
}).then(function (data) {
var hls = _this3.hls;
var payload = data.payload;
var decryptData = frag.decryptdata; // check to see if the payload needs to be decrypted
if (payload && payload.byteLength > 0 && decryptData && decryptData.key && decryptData.iv && decryptData.method === 'AES-128') {
var startTime = self.performance.now(); // decrypt the subtitles
return _this3.decrypter.webCryptoDecrypt(new Uint8Array(payload), decryptData.key.buffer, decryptData.iv.buffer).then(function (decryptedData) {
var endTime = self.performance.now();
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].FRAG_DECRYPTED, {
frag: frag,
payload: decryptedData,
stats: {
tstart: startTime,
tdecrypt: endTime
}
});
data.payload = decryptedData;
return data;
});
}
return data;
}).then(function (data) {
var fragCurrent = _this3.fragCurrent,
hls = _this3.hls,
levels = _this3.levels;
if (!levels) {
throw new Error('init load aborted, missing levels');
}
var details = levels[frag.level].details;
console.assert(details, 'Level details are defined when init segment is loaded');
var initSegment = details.initSegment;
console.assert(initSegment, 'Fragment initSegment is defined when init segment is loaded');
var stats = frag.stats;
_this3.state = State.IDLE;
_this3.fragLoadError = 0;
initSegment.data = new Uint8Array(data.payload);
stats.parsing.start = stats.buffering.start = self.performance.now();
stats.parsing.end = stats.buffering.end = self.performance.now(); // Silence FRAG_BUFFERED event if fragCurrent is null
if (data.frag === fragCurrent) {
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].FRAG_BUFFERED, {
stats: stats,
frag: fragCurrent,
part: null,
id: frag.type
});
}
_this3.tick();
}).catch(function (reason) {
_this3.warn(reason);
_this3.resetFragmentLoading(frag);
});
};
_proto.fragContextChanged = function fragContextChanged(frag) {
var fragCurrent = this.fragCurrent;
return !frag || !fragCurrent || frag.level !== fragCurrent.level || frag.sn !== fragCurrent.sn || frag.urlId !== fragCurrent.urlId;
};
_proto.fragBufferedComplete = function fragBufferedComplete(frag, part) {
var media = this.mediaBuffer ? this.mediaBuffer : this.media;
this.log("Buffered " + frag.type + " sn: " + frag.sn + (part ? ' part: ' + part.index : '') + " of " + (this.logPrefix === '[stream-controller]' ? 'level' : 'track') + " " + frag.level + " " + _utils_time_ranges__WEBPACK_IMPORTED_MODULE_14__["default"].toString(_utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].getBuffered(media)));
this.state = State.IDLE;
this.tick();
};
_proto._handleFragmentLoadComplete = function _handleFragmentLoadComplete(fragLoadedEndData) {
var transmuxer = this.transmuxer;
if (!transmuxer) {
return;
}
var frag = fragLoadedEndData.frag,
part = fragLoadedEndData.part,
partsLoaded = fragLoadedEndData.partsLoaded; // If we did not load parts, or loaded all parts, we have complete (not partial) fragment data
var complete = !partsLoaded || partsLoaded.length === 0 || partsLoaded.some(function (fragLoaded) {
return !fragLoaded;
});
var chunkMeta = new _types_transmuxer__WEBPACK_IMPORTED_MODULE_8__["ChunkMetadata"](frag.level, frag.sn, frag.stats.chunkCount + 1, 0, part ? part.index : -1, !complete);
transmuxer.flush(chunkMeta);
} // eslint-disable-next-line @typescript-eslint/no-unused-vars
;
_proto._handleFragmentLoadProgress = function _handleFragmentLoadProgress(frag) {};
_proto._doFragLoad = function _doFragLoad(frag, details, targetBufferTime, progressCallback) {
var _this4 = this;
if (targetBufferTime === void 0) {
targetBufferTime = null;
}
if (!this.levels) {
throw new Error('frag load aborted, missing levels');
}
targetBufferTime = Math.max(frag.start, targetBufferTime || 0);
if (this.config.lowLatencyMode && details) {
var partList = details.partList;
if (partList && progressCallback) {
if (targetBufferTime > frag.end && details.fragmentHint) {
frag = details.fragmentHint;
}
var partIndex = this.getNextPart(partList, frag, targetBufferTime);
if (partIndex > -1) {
var part = partList[partIndex];
this.log("Loading part sn: " + frag.sn + " p: " + part.index + " cc: " + frag.cc + " of playlist [" + details.startSN + "-" + details.endSN + "] parts [0-" + partIndex + "-" + (partList.length - 1) + "] " + (this.logPrefix === '[stream-controller]' ? 'level' : 'track') + ": " + frag.level + ", target: " + parseFloat(targetBufferTime.toFixed(3)));
this.nextLoadPosition = part.start + part.duration;
this.state = State.FRAG_LOADING;
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].FRAG_LOADING, {
frag: frag,
part: partList[partIndex],
targetBufferTime: targetBufferTime
});
return this.doFragPartsLoad(frag, partList, partIndex, progressCallback).catch(function (error) {
return _this4.handleFragLoadError(error);
});
} else if (!frag.url || this.loadedEndOfParts(partList, targetBufferTime)) {
// Fragment hint has no parts
return Promise.resolve(null);
}
}
}
this.log("Loading fragment " + frag.sn + " cc: " + frag.cc + " " + (details ? 'of [' + details.startSN + '-' + details.endSN + '] ' : '') + (this.logPrefix === '[stream-controller]' ? 'level' : 'track') + ": " + frag.level + ", target: " + parseFloat(targetBufferTime.toFixed(3))); // Don't update nextLoadPosition for fragments which are not buffered
if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(frag.sn) && !this.bitrateTest) {
this.nextLoadPosition = frag.start + frag.duration;
}
this.state = State.FRAG_LOADING;
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].FRAG_LOADING, {
frag: frag,
targetBufferTime: targetBufferTime
});
return this.fragmentLoader.load(frag, progressCallback).catch(function (error) {
return _this4.handleFragLoadError(error);
});
};
_proto.doFragPartsLoad = function doFragPartsLoad(frag, partList, partIndex, progressCallback) {
var _this5 = this;
return new Promise(function (resolve, reject) {
var partsLoaded = [];
var loadPartIndex = function loadPartIndex(index) {
var part = partList[index];
_this5.fragmentLoader.loadPart(frag, part, progressCallback).then(function (partLoadedData) {
partsLoaded[part.index] = partLoadedData;
var loadedPart = partLoadedData.part;
_this5.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].FRAG_LOADED, partLoadedData);
var nextPart = partList[index + 1];
if (nextPart && nextPart.fragment === frag) {
loadPartIndex(index + 1);
} else {
return resolve({
frag: frag,
part: loadedPart,
partsLoaded: partsLoaded
});
}
}).catch(reject);
};
loadPartIndex(partIndex);
});
};
_proto.handleFragLoadError = function handleFragLoadError(_ref) {
var data = _ref.data;
if (data && data.details === _errors__WEBPACK_IMPORTED_MODULE_6__["ErrorDetails"].INTERNAL_ABORTED) {
this.handleFragLoadAborted(data.frag, data.part);
} else {
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].ERROR, data);
}
return null;
};
_proto._handleTransmuxerFlush = function _handleTransmuxerFlush(chunkMeta) {
var context = this.getCurrentContext(chunkMeta);
if (!context || this.state !== State.PARSING) {
if (!this.fragCurrent) {
this.state = State.IDLE;
}
return;
}
var frag = context.frag,
part = context.part,
level = context.level;
var now = self.performance.now();
frag.stats.parsing.end = now;
if (part) {
part.stats.parsing.end = now;
}
this.updateLevelTiming(frag, part, level, chunkMeta.partial);
};
_proto.getCurrentContext = function getCurrentContext(chunkMeta) {
var levels = this.levels;
var levelIndex = chunkMeta.level,
sn = chunkMeta.sn,
partIndex = chunkMeta.part;
if (!levels || !levels[levelIndex]) {
this.warn("Levels object was unset while buffering fragment " + sn + " of level " + levelIndex + ". The current chunk will not be buffered.");
return null;
}
var level = levels[levelIndex];
var part = partIndex > -1 ? _level_helper__WEBPACK_IMPORTED_MODULE_7__["getPartWith"](level, sn, partIndex) : null;
var frag = part ? part.fragment : _level_helper__WEBPACK_IMPORTED_MODULE_7__["getFragmentWithSN"](level, sn);
if (!frag) {
return null;
}
return {
frag: frag,
part: part,
level: level
};
};
_proto.bufferFragmentData = function bufferFragmentData(data, frag, part, chunkMeta) {
if (!data || this.state !== State.PARSING) {
return;
}
var data1 = data.data1,
data2 = data.data2;
var buffer = data1;
if (data1 && data2) {
// Combine the moof + mdat so that we buffer with a single append
buffer = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_9__["appendUint8Array"])(data1, data2);
}
if (!buffer || !buffer.length) {
return;
}
var segment = {
type: data.type,
frag: frag,
part: part,
chunkMeta: chunkMeta,
parent: frag.type,
data: buffer
};
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].BUFFER_APPENDING, segment);
if (data.dropped && data.independent && !part) {
// Clear buffer so that we reload previous segments sequentially if required
this.flushBufferGap(frag);
}
};
_proto.flushBufferGap = function flushBufferGap(frag) {
var media = this.media;
if (!media) {
return;
} // If currentTime is not buffered, clear the back buffer so that we can backtrack as much as needed
if (!_utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].isBuffered(media, media.currentTime)) {
this.flushMainBuffer(0, frag.start);
return;
} // Remove back-buffer without interrupting playback to allow back tracking
var currentTime = media.currentTime;
var bufferInfo = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].bufferInfo(media, currentTime, 0);
var fragDuration = frag.duration;
var segmentFraction = Math.min(this.config.maxFragLookUpTolerance * 2, fragDuration * 0.25);
var start = Math.max(Math.min(frag.start - segmentFraction, bufferInfo.end - segmentFraction), currentTime + segmentFraction);
if (frag.start - start > segmentFraction) {
this.flushMainBuffer(start, frag.start);
}
};
_proto.reduceMaxBufferLength = function reduceMaxBufferLength(threshold) {
var config = this.config;
var minLength = threshold || config.maxBufferLength;
if (config.maxMaxBufferLength >= minLength) {
// reduce max buffer length as it might be too high. we do this to avoid loop flushing ...
config.maxMaxBufferLength /= 2;
this.warn("Reduce max buffer length to " + config.maxMaxBufferLength + "s");
return true;
}
return false;
};
_proto.getNextFragment = function getNextFragment(pos, levelDetails) {
var fragments = levelDetails.fragments;
var fragLen = fragments.length;
if (!fragLen) {
return null;
} // find fragment index, contiguous with end of buffer position
var config = this.config;
var start = fragments[0].start;
var frag; // If an initSegment is present, it must be buffered first
if (levelDetails.initSegment && !levelDetails.initSegment.data && !this.bitrateTest) {
frag = levelDetails.initSegment;
} else if (levelDetails.live) {
var initialLiveManifestSize = config.initialLiveManifestSize;
if (fragLen < initialLiveManifestSize) {
this.warn("Not enough fragments to start playback (have: " + fragLen + ", need: " + initialLiveManifestSize + ")");
return null;
} // The real fragment start times for a live stream are only known after the PTS range for that level is known.
// In order to discover the range, we load the best matching fragment for that level and demux it.
// Do not load using live logic if the starting frag is requested - we want to use getFragmentAtPosition() so that
// we get the fragment matching that start time
if (!levelDetails.PTSKnown && !this.startFragRequested) {
frag = this.getInitialLiveFragment(levelDetails, fragments);
}
} else if (pos <= start) {
// VoD playlist: if loadPosition before start of playlist, load first fragment
frag = fragments[0];
} // If we haven't run into any special cases already, just load the fragment most closely matching the requested position
if (!frag) {
var end = config.lowLatencyMode ? levelDetails.partEnd : levelDetails.fragmentEnd;
frag = this.getFragmentAtPosition(pos, end, levelDetails);
}
return frag;
};
_proto.getNextPart = function getNextPart(partList, frag, targetBufferTime) {
var nextPart = -1;
var contiguous = false;
var independentAttrOmitted = true;
for (var i = 0, len = partList.length; i < len; i++) {
var part = partList[i];
independentAttrOmitted = independentAttrOmitted && !part.independent;
if (nextPart > -1 && targetBufferTime < part.start) {
break;
}
var loaded = part.loaded;
if (!loaded && (contiguous || part.independent || independentAttrOmitted) && part.fragment === frag) {
nextPart = i;
}
contiguous = loaded;
}
return nextPart;
};
_proto.loadedEndOfParts = function loadedEndOfParts(partList, targetBufferTime) {
var lastPart = partList[partList.length - 1];
return lastPart && targetBufferTime > lastPart.start && lastPart.loaded;
}
/*
This method is used find the best matching first fragment for a live playlist. This fragment is used to calculate the
"sliding" of the playlist, which is its offset from the start of playback. After sliding we can compute the real
start and end times for each fragment in the playlist (after which this method will not need to be called).
*/
;
_proto.getInitialLiveFragment = function getInitialLiveFragment(levelDetails, fragments) {
var fragPrevious = this.fragPrevious;
var frag = null;
if (fragPrevious) {
if (levelDetails.hasProgramDateTime) {
// Prefer using PDT, because it can be accurate enough to choose the correct fragment without knowing the level sliding
this.log("Live playlist, switching playlist, load frag with same PDT: " + fragPrevious.programDateTime);
frag = Object(_fragment_finders__WEBPACK_IMPORTED_MODULE_11__["findFragmentByPDT"])(fragments, fragPrevious.endProgramDateTime, this.config.maxFragLookUpTolerance);
}
if (!frag) {
// SN does not need to be accurate between renditions, but depending on the packaging it may be so.
var targetSN = fragPrevious.sn + 1;
if (targetSN >= levelDetails.startSN && targetSN <= levelDetails.endSN) {
var fragNext = fragments[targetSN - levelDetails.startSN]; // Ensure that we're staying within the continuity range, since PTS resets upon a new range
if (fragPrevious.cc === fragNext.cc) {
frag = fragNext;
this.log("Live playlist, switching playlist, load frag with next SN: " + frag.sn);
}
} // It's important to stay within the continuity range if available; otherwise the fragments in the playlist
// will have the wrong start times
if (!frag) {
frag = Object(_fragment_finders__WEBPACK_IMPORTED_MODULE_11__["findFragWithCC"])(fragments, fragPrevious.cc);
if (frag) {
this.log("Live playlist, switching playlist, load frag with same CC: " + frag.sn);
}
}
}
} else {
// Find a new start fragment when fragPrevious is null
var liveStart = this.hls.liveSyncPosition;
if (liveStart !== null) {
frag = this.getFragmentAtPosition(liveStart, this.bitrateTest ? levelDetails.fragmentEnd : levelDetails.edge, levelDetails);
}
}
return frag;
}
/*
This method finds the best matching fragment given the provided position.
*/
;
_proto.getFragmentAtPosition = function getFragmentAtPosition(bufferEnd, end, levelDetails) {
var config = this.config,
fragPrevious = this.fragPrevious;
var fragments = levelDetails.fragments,
endSN = levelDetails.endSN;
var fragmentHint = levelDetails.fragmentHint;
var tolerance = config.maxFragLookUpTolerance;
var loadingParts = !!(config.lowLatencyMode && levelDetails.partList && fragmentHint);
if (loadingParts && fragmentHint && !this.bitrateTest) {
// Include incomplete fragment with parts at end
fragments = fragments.concat(fragmentHint);
endSN = fragmentHint.sn;
}
var frag;
if (bufferEnd < end) {
var lookupTolerance = bufferEnd > end - tolerance ? 0 : tolerance; // Remove the tolerance if it would put the bufferEnd past the actual end of stream
// Uses buffer and sequence number to calculate switch segment (required if using EXT-X-DISCONTINUITY-SEQUENCE)
frag = Object(_fragment_finders__WEBPACK_IMPORTED_MODULE_11__["findFragmentByPTS"])(fragPrevious, fragments, bufferEnd, lookupTolerance);
} else {
// reach end of playlist
frag = fragments[fragments.length - 1];
}
if (frag) {
var curSNIdx = frag.sn - levelDetails.startSN;
var sameLevel = fragPrevious && frag.level === fragPrevious.level;
var nextFrag = fragments[curSNIdx + 1];
var fragState = this.fragmentTracker.getState(frag);
if (fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_2__["FragmentState"].BACKTRACKED) {
frag = null;
var i = curSNIdx;
while (fragments[i] && this.fragmentTracker.getState(fragments[i]) === _fragment_tracker__WEBPACK_IMPORTED_MODULE_2__["FragmentState"].BACKTRACKED) {
// When fragPrevious is null, backtrack to first the first fragment is not BACKTRACKED for loading
// When fragPrevious is set, we want the first BACKTRACKED fragment for parsing and buffering
if (!fragPrevious) {
frag = fragments[--i];
} else {
frag = fragments[i--];
}
}
if (!frag) {
frag = nextFrag;
}
} else if (fragPrevious && frag.sn === fragPrevious.sn && !loadingParts) {
// Force the next fragment to load if the previous one was already selected. This can occasionally happen with
// non-uniform fragment durations
if (sameLevel) {
if (frag.sn < endSN && this.fragmentTracker.getState(nextFrag) !== _fragment_tracker__WEBPACK_IMPORTED_MODULE_2__["FragmentState"].OK) {
this.log("SN " + frag.sn + " just loaded, load next one: " + nextFrag.sn);
frag = nextFrag;
} else {
frag = null;
}
}
}
}
return frag;
};
_proto.synchronizeToLiveEdge = function synchronizeToLiveEdge(levelDetails) {
var config = this.config,
media = this.media;
if (!media) {
return;
}
var liveSyncPosition = this.hls.liveSyncPosition;
var currentTime = media.currentTime;
var start = levelDetails.fragments[0].start;
var end = levelDetails.edge; // Continue if we can seek forward to sync position or if current time is outside of sliding window
if (liveSyncPosition !== null && media.duration > liveSyncPosition && (currentTime < liveSyncPosition || currentTime < start - config.maxFragLookUpTolerance || currentTime > end)) {
// Continue if buffer is starving or if current time is behind max latency
var maxLatency = config.liveMaxLatencyDuration !== undefined ? config.liveMaxLatencyDuration : config.liveMaxLatencyDurationCount * levelDetails.targetduration;
if (media.readyState < 4 || currentTime < end - maxLatency) {
if (!this.loadedmetadata) {
this.nextLoadPosition = liveSyncPosition;
} // Only seek if ready and there is not a significant forward buffer available for playback
if (media.readyState) {
this.warn("Playback: " + currentTime.toFixed(3) + " is located too far from the end of live sliding playlist: " + end + ", reset currentTime to : " + liveSyncPosition.toFixed(3));
media.currentTime = liveSyncPosition;
}
}
}
};
_proto.alignPlaylists = function alignPlaylists(details, previousDetails) {
var levels = this.levels,
levelLastLoaded = this.levelLastLoaded;
var lastLevel = levelLastLoaded !== null ? levels[levelLastLoaded] : null; // FIXME: If not for `shouldAlignOnDiscontinuities` requiring fragPrevious.cc,
// this could all go in LevelHelper.mergeDetails
var sliding = 0;
if (previousDetails && details.fragments.length > 0) {
sliding = details.fragments[0].start;
if (details.alignedSliding && Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(sliding)) {
this.log("Live playlist sliding:" + sliding.toFixed(3));
} else if (!sliding) {
this.warn("[" + this.constructor.name + "] Live playlist - outdated PTS, unknown sliding");
Object(_utils_discontinuities__WEBPACK_IMPORTED_MODULE_10__["alignStream"])(this.fragPrevious, lastLevel, details);
}
} else {
this.log('Live playlist - first load, unknown sliding');
Object(_utils_discontinuities__WEBPACK_IMPORTED_MODULE_10__["alignStream"])(this.fragPrevious, lastLevel, details);
}
return sliding;
};
_proto.waitForCdnTuneIn = function waitForCdnTuneIn(details) {
// Wait for Low-Latency CDN Tune-in to get an updated playlist
var advancePartLimit = 3;
return details.live && details.canBlockReload && details.tuneInGoal > Math.max(details.partHoldBack, details.partTarget * advancePartLimit);
};
_proto.setStartPosition = function setStartPosition(details, sliding) {
// compute start position if set to -1. use it straight away if value is defined
if (this.startPosition === -1 || this.lastCurrentTime === -1) {
// first, check if start time offset has been set in playlist, if yes, use this value
var startTimeOffset = details.startTimeOffset;
if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(startTimeOffset)) {
if (startTimeOffset < 0) {
this.log("Negative start time offset " + startTimeOffset + ", count from end of last fragment");
startTimeOffset = sliding + details.totalduration + startTimeOffset;
}
this.log("Start time offset found in playlist, adjust startPosition to " + startTimeOffset);
this.startPosition = startTimeOffset;
} else {
if (details.live) {
this.startPosition = this.hls.liveSyncPosition || sliding;
this.log("Configure startPosition to " + this.startPosition);
} else {
this.startPosition = 0;
}
}
this.lastCurrentTime = this.startPosition;
}
this.nextLoadPosition = this.startPosition;
};
_proto.getLoadPosition = function getLoadPosition() {
var media = this.media; // if we have not yet loaded any fragment, start loading from start position
var pos = 0;
if (this.loadedmetadata) {
pos = media.currentTime;
} else if (this.nextLoadPosition) {
pos = this.nextLoadPosition;
}
return pos;
};
_proto.handleFragLoadAborted = function handleFragLoadAborted(frag, part) {
if (this.transmuxer && frag.sn !== 'initSegment') {
this.warn("Fragment " + frag.sn + (part ? ' part' + part.index : '') + " of level " + frag.level + " was aborted");
this.resetFragmentLoading(frag);
}
};
_proto.resetFragmentLoading = function resetFragmentLoading(frag) {
if (!this.fragCurrent || !this.fragContextChanged(frag)) {
this.state = State.IDLE;
}
};
_proto.onFragmentOrKeyLoadError = function onFragmentOrKeyLoadError(filterType, data) {
if (data.fatal) {
return;
}
var frag = data.frag; // Handle frag error related to caller's filterType
if (!frag || frag.type !== filterType) {
return;
}
var fragCurrent = this.fragCurrent;
console.assert(fragCurrent && frag.sn === fragCurrent.sn && frag.level === fragCurrent.level && frag.urlId === fragCurrent.urlId, 'Frag load error must match current frag to retry');
var config = this.config; // keep retrying until the limit will be reached
if (this.fragLoadError + 1 <= config.fragLoadingMaxRetry) {
if (this.resetLiveStartWhenNotLoaded(frag.level)) {
return;
} // exponential backoff capped to config.fragLoadingMaxRetryTimeout
var delay = Math.min(Math.pow(2, this.fragLoadError) * config.fragLoadingRetryDelay, config.fragLoadingMaxRetryTimeout);
this.warn("Fragment " + frag.sn + " of " + filterType + " " + frag.level + " failed to load, retrying in " + delay + "ms");
this.retryDate = self.performance.now() + delay;
this.fragLoadError++;
this.state = State.FRAG_LOADING_WAITING_RETRY;
} else if (data.levelRetry) {
if (filterType === _types_loader__WEBPACK_IMPORTED_MODULE_15__["PlaylistLevelType"].AUDIO) {
// Reset current fragment since audio track audio is essential and may not have a fail-over track
this.fragCurrent = null;
} // Fragment errors that result in a level switch or redundant fail-over
// should reset the stream controller state to idle
this.fragLoadError = 0;
this.state = State.IDLE;
} else {
_utils_logger__WEBPACK_IMPORTED_MODULE_4__["logger"].error(data.details + " reaches max retry, redispatch as fatal ..."); // switch error to fatal
data.fatal = true;
this.hls.stopLoad();
this.state = State.ERROR;
}
};
_proto.afterBufferFlushed = function afterBufferFlushed(media, type) {
if (!media) {
return;
} // After successful buffer flushing, filter flushed fragments from bufferedFrags use mediaBuffered instead of media
// (so that we will check against video.buffered ranges in case of alt audio track)
var bufferedTimeRanges = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].getBuffered(media);
this.fragmentTracker.detectEvictedFragments(type, bufferedTimeRanges);
};
_proto.resetLiveStartWhenNotLoaded = function resetLiveStartWhenNotLoaded(level) {
// if loadedmetadata is not set, it means that we are emergency switch down on first frag
// in that case, reset startFragRequested flag
if (!this.loadedmetadata) {
this.startFragRequested = false;
var details = this.levels ? this.levels[level].details : null;
if (details !== null && details !== void 0 && details.live) {
// We can't afford to retry after a delay in a live scenario. Update the start position and return to IDLE.
this.startPosition = -1;
this.setStartPosition(details, 0);
this.state = State.IDLE;
return true;
}
this.nextLoadPosition = this.startPosition;
}
return false;
};
_proto.updateLevelTiming = function updateLevelTiming(frag, part, level, partial) {
var _this6 = this;
var details = level.details;
console.assert(!!details, 'level.details must be defined');
var parsed = Object.keys(frag.elementaryStreams).reduce(function (result, type) {
var info = frag.elementaryStreams[type];
if (info) {
var parsedDuration = info.endPTS - info.startPTS;
if (parsedDuration <= 0) {
// Destroy the transmuxer after it's next time offset failed to advance because duration was <= 0.
// The new transmuxer will be configured with a time offset matching the next fragment start,
// preventing the timeline from shifting.
_this6.warn("Could not parse fragment " + frag.sn + " " + type + " duration reliably (" + parsedDuration + ") resetting transmuxer to fallback to playlist timing");
if (_this6.transmuxer) {
_this6.transmuxer.destroy();
_this6.transmuxer = null;
}
return result || false;
}
var drift = partial ? 0 : _level_helper__WEBPACK_IMPORTED_MODULE_7__["updateFragPTSDTS"](details, frag, info.startPTS, info.endPTS, info.startDTS, info.endDTS);
_this6.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].LEVEL_PTS_UPDATED, {
details: details,
level: level,
drift: drift,
type: type,
frag: frag,
start: info.startPTS,
end: info.endPTS
});
return true;
}
return result;
}, false);
if (parsed) {
this.state = State.PARSED;
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].FRAG_PARSED, {
frag: frag,
part: part
});
} else {
this.fragCurrent = null;
this.fragPrevious = null;
this.state = State.IDLE;
}
};
_createClass(BaseStreamController, [{
key: "state",
get: function get() {
return this._state;
},
set: function set(nextState) {
var previousState = this._state;
if (previousState !== nextState) {
this._state = nextState;
this.log(previousState + "->" + nextState);
}
}
}]);
return BaseStreamController;
}(_task_loop__WEBPACK_IMPORTED_MODULE_1__["default"]);
/***/ }),
/***/ "./src/controller/buffer-controller.ts":
/*!*********************************************!*\
!*** ./src/controller/buffer-controller.ts ***!
\*********************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return BufferController; });
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
/* harmony import */ var _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/buffer-helper */ "./src/utils/buffer-helper.ts");
/* harmony import */ var _utils_mediasource_helper__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/mediasource-helper */ "./src/utils/mediasource-helper.ts");
/* harmony import */ var _loader_fragment__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../loader/fragment */ "./src/loader/fragment.ts");
/* harmony import */ var _buffer_operation_queue__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./buffer-operation-queue */ "./src/controller/buffer-operation-queue.ts");
var MediaSource = Object(_utils_mediasource_helper__WEBPACK_IMPORTED_MODULE_5__["getMediaSource"])();
var VIDEO_CODEC_PROFILE_REPACE = /([ha]vc.)(?:\.[^.,]+)+/;
var BufferController = /*#__PURE__*/function () {
// The level details used to determine duration, target-duration and live
// cache the self generated object url to detect hijack of video tag
// A queue of buffer operations which require the SourceBuffer to not be updating upon execution
// References to event listeners for each SourceBuffer, so that they can be referenced for event removal
// The number of BUFFER_CODEC events received before any sourceBuffers are created
// The total number of BUFFER_CODEC events received
// A reference to the attached media element
// A reference to the active media source
// counters
function BufferController(_hls) {
var _this = this;
this.details = null;
this._objectUrl = null;
this.operationQueue = void 0;
this.listeners = void 0;
this.hls = void 0;
this.bufferCodecEventsExpected = 0;
this._bufferCodecEventsTotal = 0;
this.media = null;
this.mediaSource = null;
this.appendError = 0;
this.tracks = {};
this.pendingTracks = {};
this.sourceBuffer = void 0;
this._onMediaSourceOpen = function () {
var hls = _this.hls,
media = _this.media,
mediaSource = _this.mediaSource;
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('[buffer-controller]: Media source opened');
if (media) {
_this.updateMediaElementDuration();
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_ATTACHED, {
media: media
});
}
if (mediaSource) {
// once received, don't listen anymore to sourceopen event
mediaSource.removeEventListener('sourceopen', _this._onMediaSourceOpen);
}
_this.checkPendingTracks();
};
this._onMediaSourceClose = function () {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('[buffer-controller]: Media source closed');
};
this._onMediaSourceEnded = function () {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('[buffer-controller]: Media source ended');
};
this.hls = _hls;
this._initSourceBuffer();
this.registerListeners();
}
var _proto = BufferController.prototype;
_proto.destroy = function destroy() {
this.unregisterListeners();
this.details = null;
};
_proto.registerListeners = function registerListeners() {
var hls = this.hls;
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_ATTACHING, this.onMediaAttaching, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_PARSED, this.onManifestParsed, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_RESET, this.onBufferReset, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_APPENDING, this.onBufferAppending, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_CODECS, this.onBufferCodecs, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_EOS, this.onBufferEos, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_FLUSHING, this.onBufferFlushing, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_UPDATED, this.onLevelUpdated, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_PARSED, this.onFragParsed, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_CHANGED, this.onFragChanged, this);
};
_proto.unregisterListeners = function unregisterListeners() {
var hls = this.hls;
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_ATTACHING, this.onMediaAttaching, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_PARSED, this.onManifestParsed, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_RESET, this.onBufferReset, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_APPENDING, this.onBufferAppending, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_CODECS, this.onBufferCodecs, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_EOS, this.onBufferEos, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_FLUSHING, this.onBufferFlushing, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_UPDATED, this.onLevelUpdated, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_PARSED, this.onFragParsed, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_CHANGED, this.onFragChanged, this);
};
_proto._initSourceBuffer = function _initSourceBuffer() {
this.sourceBuffer = {};
this.operationQueue = new _buffer_operation_queue__WEBPACK_IMPORTED_MODULE_7__["default"](this.sourceBuffer);
this.listeners = {
audio: [],
video: [],
audiovideo: []
};
};
_proto.onManifestParsed = function onManifestParsed(event, data) {
// in case of alt audio 2 BUFFER_CODECS events will be triggered, one per stream controller
// sourcebuffers will be created all at once when the expected nb of tracks will be reached
// in case alt audio is not used, only one BUFFER_CODEC event will be fired from main stream controller
// it will contain the expected nb of source buffers, no need to compute it
var codecEvents = 2;
if (data.audio && !data.video || !data.altAudio) {
codecEvents = 1;
}
this.bufferCodecEventsExpected = this._bufferCodecEventsTotal = codecEvents;
this.details = null;
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log(this.bufferCodecEventsExpected + " bufferCodec event(s) expected");
};
_proto.onMediaAttaching = function onMediaAttaching(event, data) {
var media = this.media = data.media;
if (media && MediaSource) {
var ms = this.mediaSource = new MediaSource(); // MediaSource listeners are arrow functions with a lexical scope, and do not need to be bound
ms.addEventListener('sourceopen', this._onMediaSourceOpen);
ms.addEventListener('sourceended', this._onMediaSourceEnded);
ms.addEventListener('sourceclose', this._onMediaSourceClose); // link video and media Source
media.src = self.URL.createObjectURL(ms); // cache the locally generated object url
this._objectUrl = media.src;
}
};
_proto.onMediaDetaching = function onMediaDetaching() {
var media = this.media,
mediaSource = this.mediaSource,
_objectUrl = this._objectUrl;
if (mediaSource) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('[buffer-controller]: media source detaching');
if (mediaSource.readyState === 'open') {
try {
// endOfStream could trigger exception if any sourcebuffer is in updating state
// we don't really care about checking sourcebuffer state here,
// as we are anyway detaching the MediaSource
// let's just avoid this exception to propagate
mediaSource.endOfStream();
} catch (err) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn("[buffer-controller]: onMediaDetaching: " + err.message + " while calling endOfStream");
}
} // Clean up the SourceBuffers by invoking onBufferReset
this.onBufferReset();
mediaSource.removeEventListener('sourceopen', this._onMediaSourceOpen);
mediaSource.removeEventListener('sourceended', this._onMediaSourceEnded);
mediaSource.removeEventListener('sourceclose', this._onMediaSourceClose); // Detach properly the MediaSource from the HTMLMediaElement as
// suggested in https://github.com/w3c/media-source/issues/53.
if (media) {
if (_objectUrl) {
self.URL.revokeObjectURL(_objectUrl);
} // clean up video tag src only if it's our own url. some external libraries might
// hijack the video tag and change its 'src' without destroying the Hls instance first
if (media.src === _objectUrl) {
media.removeAttribute('src');
media.load();
} else {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn('[buffer-controller]: media.src was changed by a third party - skip cleanup');
}
}
this.mediaSource = null;
this.media = null;
this._objectUrl = null;
this.bufferCodecEventsExpected = this._bufferCodecEventsTotal;
this.pendingTracks = {};
this.tracks = {};
}
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_DETACHED, undefined);
};
_proto.onBufferReset = function onBufferReset() {
var _this2 = this;
var sourceBuffer = this.sourceBuffer;
this.getSourceBufferTypes().forEach(function (type) {
var sb = sourceBuffer[type];
try {
if (sb) {
_this2.removeBufferListeners(type);
if (_this2.mediaSource) {
_this2.mediaSource.removeSourceBuffer(sb);
} // Synchronously remove the SB from the map before the next call in order to prevent an async function from
// accessing it
sourceBuffer[type] = undefined;
}
} catch (err) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn("[buffer-controller]: Failed to reset the " + type + " buffer", err);
}
});
this._initSourceBuffer();
};
_proto.onBufferCodecs = function onBufferCodecs(event, data) {
var _this3 = this;
var sourceBufferCount = Object.keys(this.sourceBuffer).length;
Object.keys(data).forEach(function (trackName) {
if (sourceBufferCount) {
// check if SourceBuffer codec needs to change
var track = _this3.tracks[trackName];
if (track && typeof track.buffer.changeType === 'function') {
var _data$trackName = data[trackName],
codec = _data$trackName.codec,
levelCodec = _data$trackName.levelCodec,
container = _data$trackName.container;
var currentCodec = (track.levelCodec || track.codec).replace(VIDEO_CODEC_PROFILE_REPACE, '$1');
var nextCodec = (levelCodec || codec).replace(VIDEO_CODEC_PROFILE_REPACE, '$1');
if (currentCodec !== nextCodec) {
var mimeType = container + ";codecs=" + (levelCodec || codec);
_this3.appendChangeType(trackName, mimeType);
}
}
} else {
// if source buffer(s) not created yet, appended buffer tracks in this.pendingTracks
_this3.pendingTracks[trackName] = data[trackName];
}
}); // if sourcebuffers already created, do nothing ...
if (sourceBufferCount) {
return;
}
this.bufferCodecEventsExpected = Math.max(this.bufferCodecEventsExpected - 1, 0);
if (this.mediaSource && this.mediaSource.readyState === 'open') {
this.checkPendingTracks();
}
};
_proto.appendChangeType = function appendChangeType(type, mimeType) {
var _this4 = this;
var operationQueue = this.operationQueue;
var operation = {
execute: function execute() {
var sb = _this4.sourceBuffer[type];
if (sb) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("[buffer-controller]: changing " + type + " sourceBuffer type to " + mimeType);
sb.changeType(mimeType);
}
operationQueue.shiftAndExecuteNext(type);
},
onStart: function onStart() {},
onComplete: function onComplete() {},
onError: function onError(e) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn("[buffer-controller]: Failed to change " + type + " SourceBuffer type", e);
}
};
operationQueue.append(operation, type);
};
_proto.onBufferAppending = function onBufferAppending(event, eventData) {
var _this5 = this;
var hls = this.hls,
operationQueue = this.operationQueue,
tracks = this.tracks;
var data = eventData.data,
type = eventData.type,
frag = eventData.frag,
part = eventData.part,
chunkMeta = eventData.chunkMeta;
var chunkStats = chunkMeta.buffering[type];
var bufferAppendingStart = self.performance.now();
chunkStats.start = bufferAppendingStart;
var fragBuffering = frag.stats.buffering;
var partBuffering = part ? part.stats.buffering : null;
if (fragBuffering.start === 0) {
fragBuffering.start = bufferAppendingStart;
}
if (partBuffering && partBuffering.start === 0) {
partBuffering.start = bufferAppendingStart;
} // TODO: Only update timestampOffset when audio/mpeg fragment or part is not contiguous with previously appended
// Adjusting `SourceBuffer.timestampOffset` (desired point in the timeline where the next frames should be appended)
// in Chrome browser when we detect MPEG audio container and time delta between level PTS and `SourceBuffer.timestampOffset`
// is greater than 100ms (this is enough to handle seek for VOD or level change for LIVE videos).
// More info here: https://github.com/video-dev/hls.js/issues/332#issuecomment-257986486
var audioTrack = tracks.audio;
var checkTimestampOffset = type === 'audio' && chunkMeta.id === 1 && (audioTrack === null || audioTrack === void 0 ? void 0 : audioTrack.container) === 'audio/mpeg';
var operation = {
execute: function execute() {
chunkStats.executeStart = self.performance.now();
if (checkTimestampOffset) {
var sb = _this5.sourceBuffer[type];
if (sb) {
var delta = frag.start - sb.timestampOffset;
if (Math.abs(delta) >= 0.1) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("[buffer-controller]: Updating audio SourceBuffer timestampOffset to " + frag.start + " (delta: " + delta + ") sn: " + frag.sn + ")");
sb.timestampOffset = frag.start;
}
}
}
_this5.appendExecutor(data, type);
},
onStart: function onStart() {// logger.debug(`[buffer-controller]: ${type} SourceBuffer updatestart`);
},
onComplete: function onComplete() {
// logger.debug(`[buffer-controller]: ${type} SourceBuffer updateend`);
var end = self.performance.now();
chunkStats.executeEnd = chunkStats.end = end;
if (fragBuffering.first === 0) {
fragBuffering.first = end;
}
if (partBuffering && partBuffering.first === 0) {
partBuffering.first = end;
}
var sourceBuffer = _this5.sourceBuffer;
var timeRanges = {};
for (var _type in sourceBuffer) {
timeRanges[_type] = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__["BufferHelper"].getBuffered(sourceBuffer[_type]);
}
_this5.appendError = 0;
_this5.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_APPENDED, {
type: type,
frag: frag,
part: part,
chunkMeta: chunkMeta,
parent: frag.type,
timeRanges: timeRanges
});
},
onError: function onError(err) {
// in case any error occured while appending, put back segment in segments table
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error("[buffer-controller]: Error encountered while trying to append to the " + type + " SourceBuffer", err);
var event = {
type: _errors__WEBPACK_IMPORTED_MODULE_3__["ErrorTypes"].MEDIA_ERROR,
parent: frag.type,
details: _errors__WEBPACK_IMPORTED_MODULE_3__["ErrorDetails"].BUFFER_APPEND_ERROR,
err: err,
fatal: false
};
if (err.code === DOMException.QUOTA_EXCEEDED_ERR) {
// QuotaExceededError: http://www.w3.org/TR/html5/infrastructure.html#quotaexceedederror
// let's stop appending any segments, and report BUFFER_FULL_ERROR error
event.details = _errors__WEBPACK_IMPORTED_MODULE_3__["ErrorDetails"].BUFFER_FULL_ERROR;
} else {
_this5.appendError++;
event.details = _errors__WEBPACK_IMPORTED_MODULE_3__["ErrorDetails"].BUFFER_APPEND_ERROR;
/* with UHD content, we could get loop of quota exceeded error until
browser is able to evict some data from sourcebuffer. Retrying can help recover.
*/
if (_this5.appendError > hls.config.appendErrorMaxRetry) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("[buffer-controller]: Failed " + hls.config.appendErrorMaxRetry + " times to append segment in sourceBuffer");
event.fatal = true;
}
}
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, event);
}
};
operationQueue.append(operation, type);
};
_proto.onBufferFlushing = function onBufferFlushing(event, data) {
var _this6 = this;
var operationQueue = this.operationQueue;
var flushOperation = function flushOperation(type) {
return {
execute: _this6.removeExecutor.bind(_this6, type, data.startOffset, data.endOffset),
onStart: function onStart() {// logger.debug(`[buffer-controller]: Started flushing ${data.startOffset} -> ${data.endOffset} for ${type} Source Buffer`);
},
onComplete: function onComplete() {
// logger.debug(`[buffer-controller]: Finished flushing ${data.startOffset} -> ${data.endOffset} for ${type} Source Buffer`);
_this6.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_FLUSHED, {
type: type
});
},
onError: function onError(e) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn("[buffer-controller]: Failed to remove from " + type + " SourceBuffer", e);
}
};
};
if (data.type) {
operationQueue.append(flushOperation(data.type), data.type);
} else {
operationQueue.append(flushOperation('audio'), 'audio');
operationQueue.append(flushOperation('video'), 'video');
}
};
_proto.onFragParsed = function onFragParsed(event, data) {
var _this7 = this;
var frag = data.frag,
part = data.part;
var buffersAppendedTo = [];
var elementaryStreams = part ? part.elementaryStreams : frag.elementaryStreams;
if (elementaryStreams[_loader_fragment__WEBPACK_IMPORTED_MODULE_6__["ElementaryStreamTypes"].AUDIOVIDEO]) {
buffersAppendedTo.push('audiovideo');
} else {
if (elementaryStreams[_loader_fragment__WEBPACK_IMPORTED_MODULE_6__["ElementaryStreamTypes"].AUDIO]) {
buffersAppendedTo.push('audio');
}
if (elementaryStreams[_loader_fragment__WEBPACK_IMPORTED_MODULE_6__["ElementaryStreamTypes"].VIDEO]) {
buffersAppendedTo.push('video');
}
}
var onUnblocked = function onUnblocked() {
var now = self.performance.now();
frag.stats.buffering.end = now;
if (part) {
part.stats.buffering.end = now;
}
var stats = part ? part.stats : frag.stats;
_this7.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_BUFFERED, {
frag: frag,
part: part,
stats: stats,
id: frag.type
});
};
if (buffersAppendedTo.length === 0) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn("Fragments must have at least one ElementaryStreamType set. type: " + frag.type + " level: " + frag.level + " sn: " + frag.sn);
}
this.blockBuffers(onUnblocked, buffersAppendedTo);
};
_proto.onFragChanged = function onFragChanged(event, data) {
this.flushBackBuffer();
} // on BUFFER_EOS mark matching sourcebuffer(s) as ended and trigger checkEos()
// an undefined data.type will mark all buffers as EOS.
;
_proto.onBufferEos = function onBufferEos(event, data) {
var _this8 = this;
for (var type in this.sourceBuffer) {
if (!data.type || data.type === type) {
var sb = this.sourceBuffer[type];
if (sb && !sb.ended) {
sb.ended = true;
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("[buffer-controller]: " + type + " sourceBuffer now EOS");
}
}
}
var endStream = function endStream() {
var mediaSource = _this8.mediaSource;
if (!mediaSource || mediaSource.readyState !== 'open') {
return;
} // Allow this to throw and be caught by the enqueueing function
mediaSource.endOfStream();
};
this.blockBuffers(endStream);
};
_proto.onLevelUpdated = function onLevelUpdated(event, _ref) {
var details = _ref.details;
if (!details.fragments.length) {
return;
}
this.details = details;
if (this.getSourceBufferTypes().length) {
this.blockBuffers(this.updateMediaElementDuration.bind(this));
} else {
this.updateMediaElementDuration();
}
};
_proto.flushBackBuffer = function flushBackBuffer() {
var hls = this.hls,
details = this.details,
media = this.media,
sourceBuffer = this.sourceBuffer;
if (!media || details === null) {
return;
}
var sourceBufferTypes = this.getSourceBufferTypes();
if (!sourceBufferTypes.length) {
return;
} // Support for deprecated liveBackBufferLength
var backBufferLength = details.live && hls.config.liveBackBufferLength !== null ? hls.config.liveBackBufferLength : hls.config.backBufferLength;
if (!Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(backBufferLength) || backBufferLength < 0) {
return;
}
var currentTime = media.currentTime;
var targetDuration = details.levelTargetDuration;
var maxBackBufferLength = Math.max(backBufferLength, targetDuration);
var targetBackBufferPosition = Math.floor(currentTime / targetDuration) * targetDuration - maxBackBufferLength;
sourceBufferTypes.forEach(function (type) {
var sb = sourceBuffer[type];
if (sb) {
var buffered = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__["BufferHelper"].getBuffered(sb); // when target buffer start exceeds actual buffer start
if (buffered.length > 0 && targetBackBufferPosition > buffered.start(0)) {
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BACK_BUFFER_REACHED, {
bufferEnd: targetBackBufferPosition
}); // Support for deprecated event:
if (details.live) {
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LIVE_BACK_BUFFER_REACHED, {
bufferEnd: targetBackBufferPosition
});
}
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_FLUSHING, {
startOffset: 0,
endOffset: targetBackBufferPosition,
type: type
});
}
}
});
}
/**
* Update Media Source duration to current level duration or override to Infinity if configuration parameter
* 'liveDurationInfinity` is set to `true`
* More details: https://github.com/video-dev/hls.js/issues/355
*/
;
_proto.updateMediaElementDuration = function updateMediaElementDuration() {
if (!this.details || !this.media || !this.mediaSource || this.mediaSource.readyState !== 'open') {
return;
}
var details = this.details,
hls = this.hls,
media = this.media,
mediaSource = this.mediaSource;
var levelDuration = details.fragments[0].start + details.totalduration;
var mediaDuration = media.duration;
var msDuration = Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(mediaSource.duration) ? mediaSource.duration : 0;
if (details.live && hls.config.liveDurationInfinity) {
// Override duration to Infinity
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('[buffer-controller]: Media Source duration is set to Infinity');
mediaSource.duration = Infinity;
this.updateSeekableRange(details);
} else if (levelDuration > msDuration && levelDuration > mediaDuration || !Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(mediaDuration)) {
// levelDuration was the last value we set.
// not using mediaSource.duration as the browser may tweak this value
// only update Media Source duration if its value increase, this is to avoid
// flushing already buffered portion when switching between quality level
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("[buffer-controller]: Updating Media Source duration to " + levelDuration.toFixed(3));
mediaSource.duration = levelDuration;
}
};
_proto.updateSeekableRange = function updateSeekableRange(levelDetails) {
var mediaSource = this.mediaSource;
var fragments = levelDetails.fragments;
var len = fragments.length;
if (len && levelDetails.live && mediaSource !== null && mediaSource !== void 0 && mediaSource.setLiveSeekableRange) {
var start = Math.max(0, fragments[0].start);
var end = Math.max(start, start + levelDetails.totalduration);
mediaSource.setLiveSeekableRange(start, end);
}
};
_proto.checkPendingTracks = function checkPendingTracks() {
var bufferCodecEventsExpected = this.bufferCodecEventsExpected,
operationQueue = this.operationQueue,
pendingTracks = this.pendingTracks; // Check if we've received all of the expected bufferCodec events. When none remain, create all the sourceBuffers at once.
// This is important because the MSE spec allows implementations to throw QuotaExceededErrors if creating new sourceBuffers after
// data has been appended to existing ones.
// 2 tracks is the max (one for audio, one for video). If we've reach this max go ahead and create the buffers.
var pendingTracksCount = Object.keys(pendingTracks).length;
if (pendingTracksCount && !bufferCodecEventsExpected || pendingTracksCount === 2) {
// ok, let's create them now !
this.createSourceBuffers(pendingTracks);
this.pendingTracks = {}; // append any pending segments now !
var buffers = Object.keys(this.sourceBuffer);
if (buffers.length === 0) {
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_3__["ErrorTypes"].MEDIA_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_3__["ErrorDetails"].BUFFER_INCOMPATIBLE_CODECS_ERROR,
fatal: true,
reason: 'could not create source buffer for media codec(s)'
});
return;
}
buffers.forEach(function (type) {
operationQueue.executeNext(type);
});
}
};
_proto.createSourceBuffers = function createSourceBuffers(tracks) {
var sourceBuffer = this.sourceBuffer,
mediaSource = this.mediaSource;
if (!mediaSource) {
throw Error('createSourceBuffers called when mediaSource was null');
}
var tracksCreated = 0;
for (var trackName in tracks) {
if (!sourceBuffer[trackName]) {
var track = tracks[trackName];
if (!track) {
throw Error("source buffer exists for track " + trackName + ", however track does not");
} // use levelCodec as first priority
var codec = track.levelCodec || track.codec;
var mimeType = track.container + ";codecs=" + codec;
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("[buffer-controller]: creating sourceBuffer(" + mimeType + ")");
try {
var sb = sourceBuffer[trackName] = mediaSource.addSourceBuffer(mimeType);
var sbName = trackName;
this.addBufferListener(sbName, 'updatestart', this._onSBUpdateStart);
this.addBufferListener(sbName, 'updateend', this._onSBUpdateEnd);
this.addBufferListener(sbName, 'error', this._onSBUpdateError);
this.tracks[trackName] = {
buffer: sb,
codec: codec,
container: track.container,
levelCodec: track.levelCodec,
id: track.id
};
tracksCreated++;
} catch (err) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error("[buffer-controller]: error while trying to add sourceBuffer: " + err.message);
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_3__["ErrorTypes"].MEDIA_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_3__["ErrorDetails"].BUFFER_ADD_CODEC_ERROR,
fatal: false,
error: err,
mimeType: mimeType
});
}
}
}
if (tracksCreated) {
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_CREATED, {
tracks: this.tracks
});
}
} // Keep as arrow functions so that we can directly reference these functions directly as event listeners
;
_proto._onSBUpdateStart = function _onSBUpdateStart(type) {
var operationQueue = this.operationQueue;
var operation = operationQueue.current(type);
operation.onStart();
};
_proto._onSBUpdateEnd = function _onSBUpdateEnd(type) {
var operationQueue = this.operationQueue;
var operation = operationQueue.current(type);
operation.onComplete();
operationQueue.shiftAndExecuteNext(type);
};
_proto._onSBUpdateError = function _onSBUpdateError(type, event) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error("[buffer-controller]: " + type + " SourceBuffer error", event); // according to http://www.w3.org/TR/media-source/#sourcebuffer-append-error
// SourceBuffer errors are not necessarily fatal; if so, the HTMLMediaElement will fire an error event
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_3__["ErrorTypes"].MEDIA_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_3__["ErrorDetails"].BUFFER_APPENDING_ERROR,
fatal: false
}); // updateend is always fired after error, so we'll allow that to shift the current operation off of the queue
var operation = this.operationQueue.current(type);
if (operation) {
operation.onError(event);
}
} // This method must result in an updateend event; if remove is not called, _onSBUpdateEnd must be called manually
;
_proto.removeExecutor = function removeExecutor(type, startOffset, endOffset) {
var media = this.media,
mediaSource = this.mediaSource,
operationQueue = this.operationQueue,
sourceBuffer = this.sourceBuffer;
var sb = sourceBuffer[type];
if (!media || !mediaSource || !sb) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn("[buffer-controller]: Attempting to remove from the " + type + " SourceBuffer, but it does not exist");
operationQueue.shiftAndExecuteNext(type);
return;
}
var mediaDuration = Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(media.duration) ? media.duration : Infinity;
var msDuration = Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(mediaSource.duration) ? mediaSource.duration : Infinity;
var removeStart = Math.max(0, startOffset);
var removeEnd = Math.min(endOffset, mediaDuration, msDuration);
if (removeEnd > removeStart) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("[buffer-controller]: Removing [" + removeStart + "," + removeEnd + "] from the " + type + " SourceBuffer");
console.assert(!sb.updating, type + " sourceBuffer must not be updating");
sb.remove(removeStart, removeEnd);
} else {
// Cycle the queue
operationQueue.shiftAndExecuteNext(type);
}
} // This method must result in an updateend event; if append is not called, _onSBUpdateEnd must be called manually
;
_proto.appendExecutor = function appendExecutor(data, type) {
var operationQueue = this.operationQueue,
sourceBuffer = this.sourceBuffer;
var sb = sourceBuffer[type];
if (!sb) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn("[buffer-controller]: Attempting to append to the " + type + " SourceBuffer, but it does not exist");
operationQueue.shiftAndExecuteNext(type);
return;
}
sb.ended = false;
console.assert(!sb.updating, type + " sourceBuffer must not be updating");
sb.appendBuffer(data);
} // Enqueues an operation to each SourceBuffer queue which, upon execution, resolves a promise. When all promises
// resolve, the onUnblocked function is executed. Functions calling this method do not need to unblock the queue
// upon completion, since we already do it here
;
_proto.blockBuffers = function blockBuffers(onUnblocked, buffers) {
var _this9 = this;
if (buffers === void 0) {
buffers = this.getSourceBufferTypes();
}
if (!buffers.length) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('[buffer-controller]: Blocking operation requested, but no SourceBuffers exist');
Promise.resolve(onUnblocked);
return;
}
var operationQueue = this.operationQueue; // logger.debug(`[buffer-controller]: Blocking ${buffers} SourceBuffer`);
var blockingOperations = buffers.map(function (type) {
return operationQueue.appendBlocker(type);
});
Promise.all(blockingOperations).then(function () {
// logger.debug(`[buffer-controller]: Blocking operation resolved; unblocking ${buffers} SourceBuffer`);
onUnblocked();
buffers.forEach(function (type) {
var sb = _this9.sourceBuffer[type]; // Only cycle the queue if the SB is not updating. There's a bug in Chrome which sets the SB updating flag to
// true when changing the MediaSource duration (https://bugs.chromium.org/p/chromium/issues/detail?id=959359&can=2&q=mediasource%20duration)
// While this is a workaround, it's probably useful to have around
if (!sb || !sb.updating) {
operationQueue.shiftAndExecuteNext(type);
}
});
});
};
_proto.getSourceBufferTypes = function getSourceBufferTypes() {
return Object.keys(this.sourceBuffer);
};
_proto.addBufferListener = function addBufferListener(type, event, fn) {
var buffer = this.sourceBuffer[type];
if (!buffer) {
return;
}
var listener = fn.bind(this, type);
this.listeners[type].push({
event: event,
listener: listener
});
buffer.addEventListener(event, listener);
};
_proto.removeBufferListeners = function removeBufferListeners(type) {
var buffer = this.sourceBuffer[type];
if (!buffer) {
return;
}
this.listeners[type].forEach(function (l) {
buffer.removeEventListener(l.event, l.listener);
});
};
return BufferController;
}();
/***/ }),
/***/ "./src/controller/buffer-operation-queue.ts":
/*!**************************************************!*\
!*** ./src/controller/buffer-operation-queue.ts ***!
\**************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return BufferOperationQueue; });
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
var BufferOperationQueue = /*#__PURE__*/function () {
function BufferOperationQueue(sourceBufferReference) {
this.buffers = void 0;
this.queues = {
video: [],
audio: [],
audiovideo: []
};
this.buffers = sourceBufferReference;
}
var _proto = BufferOperationQueue.prototype;
_proto.append = function append(operation, type) {
var queue = this.queues[type];
queue.push(operation);
if (queue.length === 1 && this.buffers[type]) {
this.executeNext(type);
}
};
_proto.insertAbort = function insertAbort(operation, type) {
var queue = this.queues[type];
queue.unshift(operation);
this.executeNext(type);
};
_proto.appendBlocker = function appendBlocker(type) {
var execute;
var promise = new Promise(function (resolve) {
execute = resolve;
});
var operation = {
execute: execute,
onStart: function onStart() {},
onComplete: function onComplete() {},
onError: function onError() {}
};
this.append(operation, type);
return promise;
};
_proto.executeNext = function executeNext(type) {
var buffers = this.buffers,
queues = this.queues;
var sb = buffers[type];
var queue = queues[type];
if (queue.length) {
var operation = queue[0];
try {
// Operations are expected to result in an 'updateend' event being fired. If not, the queue will lock. Operations
// which do not end with this event must call _onSBUpdateEnd manually
operation.execute();
} catch (e) {
_utils_logger__WEBPACK_IMPORTED_MODULE_0__["logger"].warn('[buffer-operation-queue]: Unhandled exception executing the current operation');
operation.onError(e); // Only shift the current operation off, otherwise the updateend handler will do this for us
if (!sb || !sb.updating) {
queue.shift();
}
}
}
};
_proto.shiftAndExecuteNext = function shiftAndExecuteNext(type) {
this.queues[type].shift();
this.executeNext(type);
};
_proto.current = function current(type) {
return this.queues[type][0];
};
return BufferOperationQueue;
}();
/***/ }),
/***/ "./src/controller/cap-level-controller.ts":
/*!************************************************!*\
!*** ./src/controller/cap-level-controller.ts ***!
\************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ "./src/events.ts");
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
/*
* cap stream level to media size dimension controller
*/
var CapLevelController = /*#__PURE__*/function () {
function CapLevelController(hls) {
this.autoLevelCapping = void 0;
this.firstLevel = void 0;
this.media = void 0;
this.restrictedLevels = void 0;
this.timer = void 0;
this.hls = void 0;
this.streamController = void 0;
this.clientRect = void 0;
this.hls = hls;
this.autoLevelCapping = Number.POSITIVE_INFINITY;
this.firstLevel = -1;
this.media = null;
this.restrictedLevels = [];
this.timer = undefined;
this.clientRect = null;
this.registerListeners();
}
var _proto = CapLevelController.prototype;
_proto.setStreamController = function setStreamController(streamController) {
this.streamController = streamController;
};
_proto.destroy = function destroy() {
this.unregisterListener();
if (this.hls.config.capLevelToPlayerSize) {
this.stopCapping();
}
this.media = null;
this.clientRect = null; // @ts-ignore
this.hls = this.streamController = null;
};
_proto.registerListeners = function registerListeners() {
var hls = this.hls;
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FPS_DROP_LEVEL_CAPPING, this.onFpsDropLevelCapping, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHING, this.onMediaAttaching, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MANIFEST_PARSED, this.onManifestParsed, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].BUFFER_CODECS, this.onBufferCodecs, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
};
_proto.unregisterListener = function unregisterListener() {
var hls = this.hls;
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FPS_DROP_LEVEL_CAPPING, this.onFpsDropLevelCapping, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHING, this.onMediaAttaching, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MANIFEST_PARSED, this.onManifestParsed, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].BUFFER_CODECS, this.onBufferCodecs, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
};
_proto.onFpsDropLevelCapping = function onFpsDropLevelCapping(event, data) {
// Don't add a restricted level more than once
if (CapLevelController.isLevelAllowed(data.droppedLevel, this.restrictedLevels)) {
this.restrictedLevels.push(data.droppedLevel);
}
};
_proto.onMediaAttaching = function onMediaAttaching(event, data) {
this.media = data.media instanceof HTMLVideoElement ? data.media : null;
};
_proto.onManifestParsed = function onManifestParsed(event, data) {
var hls = this.hls;
this.restrictedLevels = [];
this.firstLevel = data.firstLevel;
if (hls.config.capLevelToPlayerSize && data.video) {
// Start capping immediately if the manifest has signaled video codecs
this.startCapping();
}
} // Only activate capping when playing a video stream; otherwise, multi-bitrate audio-only streams will be restricted
// to the first level
;
_proto.onBufferCodecs = function onBufferCodecs(event, data) {
var hls = this.hls;
if (hls.config.capLevelToPlayerSize && data.video) {
// If the manifest did not signal a video codec capping has been deferred until we're certain video is present
this.startCapping();
}
};
_proto.onMediaDetaching = function onMediaDetaching() {
this.stopCapping();
};
_proto.detectPlayerSize = function detectPlayerSize() {
if (this.media && this.mediaHeight > 0 && this.mediaWidth > 0) {
var levels = this.hls.levels;
if (levels.length) {
var hls = this.hls;
hls.autoLevelCapping = this.getMaxLevel(levels.length - 1);
if (hls.autoLevelCapping > this.autoLevelCapping && this.streamController) {
// if auto level capping has a higher value for the previous one, flush the buffer using nextLevelSwitch
// usually happen when the user go to the fullscreen mode.
this.streamController.nextLevelSwitch();
}
this.autoLevelCapping = hls.autoLevelCapping;
}
}
}
/*
* returns level should be the one with the dimensions equal or greater than the media (player) dimensions (so the video will be downscaled)
*/
;
_proto.getMaxLevel = function getMaxLevel(capLevelIndex) {
var _this = this;
var levels = this.hls.levels;
if (!levels.length) {
return -1;
}
var validLevels = levels.filter(function (level, index) {
return CapLevelController.isLevelAllowed(index, _this.restrictedLevels) && index <= capLevelIndex;
});
this.clientRect = null;
return CapLevelController.getMaxLevelByMediaSize(validLevels, this.mediaWidth, this.mediaHeight);
};
_proto.startCapping = function startCapping() {
if (this.timer) {
// Don't reset capping if started twice; this can happen if the manifest signals a video codec
return;
}
this.autoLevelCapping = Number.POSITIVE_INFINITY;
this.hls.firstLevel = this.getMaxLevel(this.firstLevel);
self.clearInterval(this.timer);
this.timer = self.setInterval(this.detectPlayerSize.bind(this), 1000);
this.detectPlayerSize();
};
_proto.stopCapping = function stopCapping() {
this.restrictedLevels = [];
this.firstLevel = -1;
this.autoLevelCapping = Number.POSITIVE_INFINITY;
if (this.timer) {
self.clearInterval(this.timer);
this.timer = undefined;
}
};
_proto.getDimensions = function getDimensions() {
if (this.clientRect) {
return this.clientRect;
}
var media = this.media;
var boundsRect = {
width: 0,
height: 0
};
if (media) {
var clientRect = media.getBoundingClientRect();
boundsRect.width = clientRect.width;
boundsRect.height = clientRect.height;
if (!boundsRect.width && !boundsRect.height) {
// When the media element has no width or height (equivalent to not being in the DOM),
// then use its width and height attributes (media.width, media.height)
boundsRect.width = clientRect.right - clientRect.left || media.width || 0;
boundsRect.height = clientRect.bottom - clientRect.top || media.height || 0;
}
}
this.clientRect = boundsRect;
return boundsRect;
};
CapLevelController.isLevelAllowed = function isLevelAllowed(level, restrictedLevels) {
if (restrictedLevels === void 0) {
restrictedLevels = [];
}
return restrictedLevels.indexOf(level) === -1;
};
CapLevelController.getMaxLevelByMediaSize = function getMaxLevelByMediaSize(levels, width, height) {
if (!levels || !levels.length) {
return -1;
} // Levels can have the same dimensions but differing bandwidths - since levels are ordered, we can look to the next
// to determine whether we've chosen the greatest bandwidth for the media's dimensions
var atGreatestBandiwdth = function atGreatestBandiwdth(curLevel, nextLevel) {
if (!nextLevel) {
return true;
}
return curLevel.width !== nextLevel.width || curLevel.height !== nextLevel.height;
}; // If we run through the loop without breaking, the media's dimensions are greater than every level, so default to
// the max level
var maxLevelIndex = levels.length - 1;
for (var i = 0; i < levels.length; i += 1) {
var level = levels[i];
if ((level.width >= width || level.height >= height) && atGreatestBandiwdth(level, levels[i + 1])) {
maxLevelIndex = i;
break;
}
}
return maxLevelIndex;
};
_createClass(CapLevelController, [{
key: "mediaWidth",
get: function get() {
return this.getDimensions().width * CapLevelController.contentScaleFactor;
}
}, {
key: "mediaHeight",
get: function get() {
return this.getDimensions().height * CapLevelController.contentScaleFactor;
}
}], [{
key: "contentScaleFactor",
get: function get() {
var pixelRatio = 1;
try {
pixelRatio = self.devicePixelRatio;
} catch (e) {
/* no-op */
}
return pixelRatio;
}
}]);
return CapLevelController;
}();
/* harmony default export */ __webpack_exports__["default"] = (CapLevelController);
/***/ }),
/***/ "./src/controller/eme-controller.ts":
/*!******************************************!*\
!*** ./src/controller/eme-controller.ts ***!
\******************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/* harmony import */ var _utils_mediakeys_helper__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/mediakeys-helper */ "./src/utils/mediakeys-helper.ts");
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
/**
* @author Stephan Hesse <disparat@gmail.com> | <tchakabam@gmail.com>
*
* DRM support for Hls.js
*/
var MAX_LICENSE_REQUEST_FAILURES = 3;
/**
* @see https://developer.mozilla.org/en-US/docs/Web/API/MediaKeySystemConfiguration
* @param {Array<string>} audioCodecs List of required audio codecs to support
* @param {Array<string>} videoCodecs List of required video codecs to support
* @param {object} drmSystemOptions Optional parameters/requirements for the key-system
* @returns {Array<MediaSystemConfiguration>} An array of supported configurations
*/
var createWidevineMediaKeySystemConfigurations = function createWidevineMediaKeySystemConfigurations(audioCodecs, videoCodecs, drmSystemOptions) {
/* jshint ignore:line */
var baseConfig = {
// initDataTypes: ['keyids', 'mp4'],
// label: "",
// persistentState: "not-allowed", // or "required" ?
// distinctiveIdentifier: "not-allowed", // or "required" ?
// sessionTypes: ['temporary'],
audioCapabilities: [],
// { contentType: 'audio/mp4; codecs="mp4a.40.2"' }
videoCapabilities: [] // { contentType: 'video/mp4; codecs="avc1.42E01E"' }
};
audioCodecs.forEach(function (codec) {
baseConfig.audioCapabilities.push({
contentType: "audio/mp4; codecs=\"" + codec + "\"",
robustness: drmSystemOptions.audioRobustness || ''
});
});
videoCodecs.forEach(function (codec) {
baseConfig.videoCapabilities.push({
contentType: "video/mp4; codecs=\"" + codec + "\"",
robustness: drmSystemOptions.videoRobustness || ''
});
});
return [baseConfig];
};
/**
* The idea here is to handle key-system (and their respective platforms) specific configuration differences
* in order to work with the local requestMediaKeySystemAccess method.
*
* We can also rule-out platform-related key-system support at this point by throwing an error.
*
* @param {string} keySystem Identifier for the key-system, see `KeySystems` enum
* @param {Array<string>} audioCodecs List of required audio codecs to support
* @param {Array<string>} videoCodecs List of required video codecs to support
* @throws will throw an error if a unknown key system is passed
* @returns {Array<MediaSystemConfiguration>} A non-empty Array of MediaKeySystemConfiguration objects
*/
var getSupportedMediaKeySystemConfigurations = function getSupportedMediaKeySystemConfigurations(keySystem, audioCodecs, videoCodecs, drmSystemOptions) {
switch (keySystem) {
case _utils_mediakeys_helper__WEBPACK_IMPORTED_MODULE_3__["KeySystems"].WIDEVINE:
return createWidevineMediaKeySystemConfigurations(audioCodecs, videoCodecs, drmSystemOptions);
default:
throw new Error("Unknown key-system: " + keySystem);
}
};
/**
* Controller to deal with encrypted media extensions (EME)
* @see https://developer.mozilla.org/en-US/docs/Web/API/Encrypted_Media_Extensions_API
*
* @class
* @constructor
*/
var EMEController = /*#__PURE__*/function () {
/**
* @constructs
* @param {Hls} hls Our Hls.js instance
*/
function EMEController(hls) {
this.hls = void 0;
this._widevineLicenseUrl = void 0;
this._licenseXhrSetup = void 0;
this._licenseResponseCallback = void 0;
this._emeEnabled = void 0;
this._requestMediaKeySystemAccess = void 0;
this._drmSystemOptions = void 0;
this._config = void 0;
this._mediaKeysList = [];
this._media = null;
this._hasSetMediaKeys = false;
this._requestLicenseFailureCount = 0;
this.mediaKeysPromise = null;
this._onMediaEncrypted = this.onMediaEncrypted.bind(this);
this.hls = hls;
this._config = hls.config;
this._widevineLicenseUrl = this._config.widevineLicenseUrl;
this._licenseXhrSetup = this._config.licenseXhrSetup;
this._licenseResponseCallback = this._config.licenseResponseCallback;
this._emeEnabled = this._config.emeEnabled;
this._requestMediaKeySystemAccess = this._config.requestMediaKeySystemAccessFunc;
this._drmSystemOptions = this._config.drmSystemOptions;
this._registerListeners();
}
var _proto = EMEController.prototype;
_proto.destroy = function destroy() {
this._unregisterListeners(); // @ts-ignore
this.hls = this._onMediaEncrypted = null;
this._requestMediaKeySystemAccess = null;
};
_proto._registerListeners = function _registerListeners() {
this.hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this);
this.hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_DETACHED, this.onMediaDetached, this);
this.hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MANIFEST_PARSED, this.onManifestParsed, this);
};
_proto._unregisterListeners = function _unregisterListeners() {
this.hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this);
this.hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_DETACHED, this.onMediaDetached, this);
this.hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MANIFEST_PARSED, this.onManifestParsed, this);
}
/**
* @param {string} keySystem Identifier for the key-system, see `KeySystems` enum
* @returns {string} License server URL for key-system (if any configured, otherwise causes error)
* @throws if a unsupported keysystem is passed
*/
;
_proto.getLicenseServerUrl = function getLicenseServerUrl(keySystem) {
switch (keySystem) {
case _utils_mediakeys_helper__WEBPACK_IMPORTED_MODULE_3__["KeySystems"].WIDEVINE:
if (!this._widevineLicenseUrl) {
break;
}
return this._widevineLicenseUrl;
}
throw new Error("no license server URL configured for key-system \"" + keySystem + "\"");
}
/**
* Requests access object and adds it to our list upon success
* @private
* @param {string} keySystem System ID (see `KeySystems`)
* @param {Array<string>} audioCodecs List of required audio codecs to support
* @param {Array<string>} videoCodecs List of required video codecs to support
* @throws When a unsupported KeySystem is passed
*/
;
_proto._attemptKeySystemAccess = function _attemptKeySystemAccess(keySystem, audioCodecs, videoCodecs) {
var _this = this;
// This can throw, but is caught in event handler callpath
var mediaKeySystemConfigs = getSupportedMediaKeySystemConfigurations(keySystem, audioCodecs, videoCodecs, this._drmSystemOptions);
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('Requesting encrypted media key-system access'); // expecting interface like window.navigator.requestMediaKeySystemAccess
var keySystemAccessPromise = this.requestMediaKeySystemAccess(keySystem, mediaKeySystemConfigs);
this.mediaKeysPromise = keySystemAccessPromise.then(function (mediaKeySystemAccess) {
return _this._onMediaKeySystemAccessObtained(keySystem, mediaKeySystemAccess);
});
keySystemAccessPromise.catch(function (err) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error("Failed to obtain key-system \"" + keySystem + "\" access:", err);
});
};
/**
* Handles obtaining access to a key-system
* @private
* @param {string} keySystem
* @param {MediaKeySystemAccess} mediaKeySystemAccess https://developer.mozilla.org/en-US/docs/Web/API/MediaKeySystemAccess
*/
_proto._onMediaKeySystemAccessObtained = function _onMediaKeySystemAccessObtained(keySystem, mediaKeySystemAccess) {
var _this2 = this;
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("Access for key-system \"" + keySystem + "\" obtained");
var mediaKeysListItem = {
mediaKeysSessionInitialized: false,
mediaKeySystemAccess: mediaKeySystemAccess,
mediaKeySystemDomain: keySystem
};
this._mediaKeysList.push(mediaKeysListItem);
var mediaKeysPromise = Promise.resolve().then(function () {
return mediaKeySystemAccess.createMediaKeys();
}).then(function (mediaKeys) {
mediaKeysListItem.mediaKeys = mediaKeys;
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("Media-keys created for key-system \"" + keySystem + "\"");
_this2._onMediaKeysCreated();
return mediaKeys;
});
mediaKeysPromise.catch(function (err) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error('Failed to create media-keys:', err);
});
return mediaKeysPromise;
}
/**
* Handles key-creation (represents access to CDM). We are going to create key-sessions upon this
* for all existing keys where no session exists yet.
*
* @private
*/
;
_proto._onMediaKeysCreated = function _onMediaKeysCreated() {
var _this3 = this;
// check for all key-list items if a session exists, otherwise, create one
this._mediaKeysList.forEach(function (mediaKeysListItem) {
if (!mediaKeysListItem.mediaKeysSession) {
// mediaKeys is definitely initialized here
mediaKeysListItem.mediaKeysSession = mediaKeysListItem.mediaKeys.createSession();
_this3._onNewMediaKeySession(mediaKeysListItem.mediaKeysSession);
}
});
}
/**
* @private
* @param {*} keySession
*/
;
_proto._onNewMediaKeySession = function _onNewMediaKeySession(keySession) {
var _this4 = this;
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("New key-system session " + keySession.sessionId);
keySession.addEventListener('message', function (event) {
_this4._onKeySessionMessage(keySession, event.message);
}, false);
}
/**
* @private
* @param {MediaKeySession} keySession
* @param {ArrayBuffer} message
*/
;
_proto._onKeySessionMessage = function _onKeySessionMessage(keySession, message) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('Got EME message event, creating license request');
this._requestLicense(message, function (data) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("Received license data (length: " + (data ? data.byteLength : data) + "), updating key-session");
keySession.update(data);
});
}
/**
* @private
* @param e {MediaEncryptedEvent}
*/
;
_proto.onMediaEncrypted = function onMediaEncrypted(e) {
var _this5 = this;
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("Media is encrypted using \"" + e.initDataType + "\" init data type");
if (!this.mediaKeysPromise) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error('Fatal: Media is encrypted but no CDM access or no keys have been requested');
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].KEY_SYSTEM_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].KEY_SYSTEM_NO_KEYS,
fatal: true
});
return;
}
var finallySetKeyAndStartSession = function finallySetKeyAndStartSession(mediaKeys) {
if (!_this5._media) {
return;
}
_this5._attemptSetMediaKeys(mediaKeys);
_this5._generateRequestWithPreferredKeySession(e.initDataType, e.initData);
}; // Could use `Promise.finally` but some Promise polyfills are missing it
this.mediaKeysPromise.then(finallySetKeyAndStartSession).catch(finallySetKeyAndStartSession);
}
/**
* @private
*/
;
_proto._attemptSetMediaKeys = function _attemptSetMediaKeys(mediaKeys) {
if (!this._media) {
throw new Error('Attempted to set mediaKeys without first attaching a media element');
}
if (!this._hasSetMediaKeys) {
// FIXME: see if we can/want/need-to really to deal with several potential key-sessions?
var keysListItem = this._mediaKeysList[0];
if (!keysListItem || !keysListItem.mediaKeys) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error('Fatal: Media is encrypted but no CDM access or no keys have been obtained yet');
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].KEY_SYSTEM_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].KEY_SYSTEM_NO_KEYS,
fatal: true
});
return;
}
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('Setting keys for encrypted media');
this._media.setMediaKeys(keysListItem.mediaKeys);
this._hasSetMediaKeys = true;
}
}
/**
* @private
*/
;
_proto._generateRequestWithPreferredKeySession = function _generateRequestWithPreferredKeySession(initDataType, initData) {
var _this6 = this;
// FIXME: see if we can/want/need-to really to deal with several potential key-sessions?
var keysListItem = this._mediaKeysList[0];
if (!keysListItem) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error('Fatal: Media is encrypted but not any key-system access has been obtained yet');
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].KEY_SYSTEM_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].KEY_SYSTEM_NO_ACCESS,
fatal: true
});
return;
}
if (keysListItem.mediaKeysSessionInitialized) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn('Key-Session already initialized but requested again');
return;
}
var keySession = keysListItem.mediaKeysSession;
if (!keySession) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error('Fatal: Media is encrypted but no key-session existing');
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].KEY_SYSTEM_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].KEY_SYSTEM_NO_SESSION,
fatal: true
});
return;
} // initData is null if the media is not CORS-same-origin
if (!initData) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn('Fatal: initData required for generating a key session is null');
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].KEY_SYSTEM_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].KEY_SYSTEM_NO_INIT_DATA,
fatal: true
});
return;
}
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("Generating key-session request for \"" + initDataType + "\" init data type");
keysListItem.mediaKeysSessionInitialized = true;
keySession.generateRequest(initDataType, initData).then(function () {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].debug('Key-session generation succeeded');
}).catch(function (err) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error('Error generating key-session request:', err);
_this6.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].KEY_SYSTEM_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].KEY_SYSTEM_NO_SESSION,
fatal: false
});
});
}
/**
* @private
* @param {string} url License server URL
* @param {ArrayBuffer} keyMessage Message data issued by key-system
* @param {function} callback Called when XHR has succeeded
* @returns {XMLHttpRequest} Unsent (but opened state) XHR object
* @throws if XMLHttpRequest construction failed
*/
;
_proto._createLicenseXhr = function _createLicenseXhr(url, keyMessage, callback) {
var xhr = new XMLHttpRequest();
xhr.responseType = 'arraybuffer';
xhr.onreadystatechange = this._onLicenseRequestReadyStageChange.bind(this, xhr, url, keyMessage, callback);
var licenseXhrSetup = this._licenseXhrSetup;
if (licenseXhrSetup) {
try {
licenseXhrSetup.call(this.hls, xhr, url);
licenseXhrSetup = undefined;
} catch (e) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error(e);
}
}
try {
// if licenseXhrSetup did not yet call open, let's do it now
if (!xhr.readyState) {
xhr.open('POST', url, true);
}
if (licenseXhrSetup) {
licenseXhrSetup.call(this.hls, xhr, url);
}
} catch (e) {
// IE11 throws an exception on xhr.open if attempting to access an HTTP resource over HTTPS
throw new Error("issue setting up KeySystem license XHR " + e);
}
return xhr;
}
/**
* @private
* @param {XMLHttpRequest} xhr
* @param {string} url License server URL
* @param {ArrayBuffer} keyMessage Message data issued by key-system
* @param {function} callback Called when XHR has succeeded
*/
;
_proto._onLicenseRequestReadyStageChange = function _onLicenseRequestReadyStageChange(xhr, url, keyMessage, callback) {
switch (xhr.readyState) {
case 4:
if (xhr.status === 200) {
this._requestLicenseFailureCount = 0;
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('License request succeeded');
var _data = xhr.response;
var licenseResponseCallback = this._licenseResponseCallback;
if (licenseResponseCallback) {
try {
_data = licenseResponseCallback.call(this.hls, xhr, url);
} catch (e) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error(e);
}
}
callback(_data);
} else {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error("License Request XHR failed (" + url + "). Status: " + xhr.status + " (" + xhr.statusText + ")");
this._requestLicenseFailureCount++;
if (this._requestLicenseFailureCount > MAX_LICENSE_REQUEST_FAILURES) {
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].KEY_SYSTEM_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].KEY_SYSTEM_LICENSE_REQUEST_FAILED,
fatal: true
});
return;
}
var attemptsLeft = MAX_LICENSE_REQUEST_FAILURES - this._requestLicenseFailureCount + 1;
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn("Retrying license request, " + attemptsLeft + " attempts left");
this._requestLicense(keyMessage, callback);
}
break;
}
}
/**
* @private
* @param {MediaKeysListItem} keysListItem
* @param {ArrayBuffer} keyMessage
* @returns {ArrayBuffer} Challenge data posted to license server
* @throws if KeySystem is unsupported
*/
;
_proto._generateLicenseRequestChallenge = function _generateLicenseRequestChallenge(keysListItem, keyMessage) {
switch (keysListItem.mediaKeySystemDomain) {
// case KeySystems.PLAYREADY:
// from https://github.com/MicrosoftEdge/Demos/blob/master/eme/scripts/demo.js
/*
if (this.licenseType !== this.LICENSE_TYPE_WIDEVINE) {
// For PlayReady CDMs, we need to dig the Challenge out of the XML.
var keyMessageXml = new DOMParser().parseFromString(String.fromCharCode.apply(null, new Uint16Array(keyMessage)), 'application/xml');
if (keyMessageXml.getElementsByTagName('Challenge')[0]) {
challenge = atob(keyMessageXml.getElementsByTagName('Challenge')[0].childNodes[0].nodeValue);
} else {
throw 'Cannot find <Challenge> in key message';
}
var headerNames = keyMessageXml.getElementsByTagName('name');
var headerValues = keyMessageXml.getElementsByTagName('value');
if (headerNames.length !== headerValues.length) {
throw 'Mismatched header <name>/<value> pair in key message';
}
for (var i = 0; i < headerNames.length; i++) {
xhr.setRequestHeader(headerNames[i].childNodes[0].nodeValue, headerValues[i].childNodes[0].nodeValue);
}
}
break;
*/
case _utils_mediakeys_helper__WEBPACK_IMPORTED_MODULE_3__["KeySystems"].WIDEVINE:
// For Widevine CDMs, the challenge is the keyMessage.
return keyMessage;
}
throw new Error("unsupported key-system: " + keysListItem.mediaKeySystemDomain);
}
/**
* @private
* @param keyMessage
* @param callback
*/
;
_proto._requestLicense = function _requestLicense(keyMessage, callback) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('Requesting content license for key-system');
var keysListItem = this._mediaKeysList[0];
if (!keysListItem) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error('Fatal error: Media is encrypted but no key-system access has been obtained yet');
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].KEY_SYSTEM_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].KEY_SYSTEM_NO_ACCESS,
fatal: true
});
return;
}
try {
var _url = this.getLicenseServerUrl(keysListItem.mediaKeySystemDomain);
var _xhr = this._createLicenseXhr(_url, keyMessage, callback);
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("Sending license request to URL: " + _url);
var challenge = this._generateLicenseRequestChallenge(keysListItem, keyMessage);
_xhr.send(challenge);
} catch (e) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error("Failure requesting DRM license: " + e);
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].KEY_SYSTEM_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].KEY_SYSTEM_LICENSE_REQUEST_FAILED,
fatal: true
});
}
};
_proto.onMediaAttached = function onMediaAttached(event, data) {
if (!this._emeEnabled) {
return;
}
var media = data.media; // keep reference of media
this._media = media;
media.addEventListener('encrypted', this._onMediaEncrypted);
};
_proto.onMediaDetached = function onMediaDetached() {
var media = this._media;
var mediaKeysList = this._mediaKeysList;
if (!media) {
return;
}
media.removeEventListener('encrypted', this._onMediaEncrypted);
this._media = null;
this._mediaKeysList = []; // Close all sessions and remove media keys from the video element.
Promise.all(mediaKeysList.map(function (mediaKeysListItem) {
if (mediaKeysListItem.mediaKeysSession) {
return mediaKeysListItem.mediaKeysSession.close().catch(function () {// Ignore errors when closing the sessions. Closing a session that
// generated no key requests will throw an error.
});
}
})).then(function () {
return media.setMediaKeys(null);
}).catch(function () {// Ignore any failures while removing media keys from the video element.
});
};
_proto.onManifestParsed = function onManifestParsed(event, data) {
if (!this._emeEnabled) {
return;
}
var audioCodecs = data.levels.map(function (level) {
return level.audioCodec;
}).filter(function (audioCodec) {
return !!audioCodec;
});
var videoCodecs = data.levels.map(function (level) {
return level.videoCodec;
}).filter(function (videoCodec) {
return !!videoCodec;
});
this._attemptKeySystemAccess(_utils_mediakeys_helper__WEBPACK_IMPORTED_MODULE_3__["KeySystems"].WIDEVINE, audioCodecs, videoCodecs);
};
_createClass(EMEController, [{
key: "requestMediaKeySystemAccess",
get: function get() {
if (!this._requestMediaKeySystemAccess) {
throw new Error('No requestMediaKeySystemAccess function configured');
}
return this._requestMediaKeySystemAccess;
}
}]);
return EMEController;
}();
/* harmony default export */ __webpack_exports__["default"] = (EMEController);
/***/ }),
/***/ "./src/controller/fps-controller.ts":
/*!******************************************!*\
!*** ./src/controller/fps-controller.ts ***!
\******************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
var FPSController = /*#__PURE__*/function () {
// stream controller must be provided as a dependency!
function FPSController(hls) {
this.hls = void 0;
this.isVideoPlaybackQualityAvailable = false;
this.timer = void 0;
this.media = null;
this.lastTime = void 0;
this.lastDroppedFrames = 0;
this.lastDecodedFrames = 0;
this.streamController = void 0;
this.hls = hls;
this.registerListeners();
}
var _proto = FPSController.prototype;
_proto.setStreamController = function setStreamController(streamController) {
this.streamController = streamController;
};
_proto.registerListeners = function registerListeners() {
this.hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHING, this.onMediaAttaching, this);
};
_proto.unregisterListeners = function unregisterListeners() {
this.hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHING, this.onMediaAttaching);
};
_proto.destroy = function destroy() {
if (this.timer) {
clearInterval(this.timer);
}
this.unregisterListeners();
this.isVideoPlaybackQualityAvailable = false;
this.media = null;
};
_proto.onMediaAttaching = function onMediaAttaching(event, data) {
var config = this.hls.config;
if (config.capLevelOnFPSDrop) {
var media = data.media instanceof self.HTMLVideoElement ? data.media : null;
this.media = media;
if (media && typeof media.getVideoPlaybackQuality === 'function') {
this.isVideoPlaybackQualityAvailable = true;
}
self.clearInterval(this.timer);
this.timer = self.setTimeout(this.checkFPSInterval.bind(this), config.fpsDroppedMonitoringPeriod);
}
};
_proto.checkFPS = function checkFPS(video, decodedFrames, droppedFrames) {
var currentTime = performance.now();
if (decodedFrames) {
if (this.lastTime) {
var currentPeriod = currentTime - this.lastTime;
var currentDropped = droppedFrames - this.lastDroppedFrames;
var currentDecoded = decodedFrames - this.lastDecodedFrames;
var droppedFPS = 1000 * currentDropped / currentPeriod;
var hls = this.hls;
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FPS_DROP, {
currentDropped: currentDropped,
currentDecoded: currentDecoded,
totalDroppedFrames: droppedFrames
});
if (droppedFPS > 0) {
// logger.log('checkFPS : droppedFPS/decodedFPS:' + droppedFPS/(1000 * currentDecoded / currentPeriod));
if (currentDropped > hls.config.fpsDroppedMonitoringThreshold * currentDecoded) {
var currentLevel = hls.currentLevel;
_utils_logger__WEBPACK_IMPORTED_MODULE_1__["logger"].warn('drop FPS ratio greater than max allowed value for currentLevel: ' + currentLevel);
if (currentLevel > 0 && (hls.autoLevelCapping === -1 || hls.autoLevelCapping >= currentLevel)) {
currentLevel = currentLevel - 1;
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FPS_DROP_LEVEL_CAPPING, {
level: currentLevel,
droppedLevel: hls.currentLevel
});
hls.autoLevelCapping = currentLevel;
this.streamController.nextLevelSwitch();
}
}
}
}
this.lastTime = currentTime;
this.lastDroppedFrames = droppedFrames;
this.lastDecodedFrames = decodedFrames;
}
};
_proto.checkFPSInterval = function checkFPSInterval() {
var video = this.media;
if (video) {
if (this.isVideoPlaybackQualityAvailable) {
var videoPlaybackQuality = video.getVideoPlaybackQuality();
this.checkFPS(video, videoPlaybackQuality.totalVideoFrames, videoPlaybackQuality.droppedVideoFrames);
} else {
// HTMLVideoElement doesn't include the webkit types
this.checkFPS(video, video.webkitDecodedFrameCount, video.webkitDroppedFrameCount);
}
}
};
return FPSController;
}();
/* harmony default export */ __webpack_exports__["default"] = (FPSController);
/***/ }),
/***/ "./src/controller/fragment-finders.ts":
/*!********************************************!*\
!*** ./src/controller/fragment-finders.ts ***!
\********************************************/
/*! exports provided: findFragmentByPDT, findFragmentByPTS, fragmentWithinToleranceTest, pdtWithinToleranceTest, findFragWithCC */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findFragmentByPDT", function() { return findFragmentByPDT; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findFragmentByPTS", function() { return findFragmentByPTS; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "fragmentWithinToleranceTest", function() { return fragmentWithinToleranceTest; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "pdtWithinToleranceTest", function() { return pdtWithinToleranceTest; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findFragWithCC", function() { return findFragWithCC; });
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var _utils_binary_search__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/binary-search */ "./src/utils/binary-search.ts");
/**
* Returns first fragment whose endPdt value exceeds the given PDT.
* @param {Array<Fragment>} fragments - The array of candidate fragments
* @param {number|null} [PDTValue = null] - The PDT value which must be exceeded
* @param {number} [maxFragLookUpTolerance = 0] - The amount of time that a fragment's start/end can be within in order to be considered contiguous
* @returns {*|null} fragment - The best matching fragment
*/
function findFragmentByPDT(fragments, PDTValue, maxFragLookUpTolerance) {
if (PDTValue === null || !Array.isArray(fragments) || !fragments.length || !Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(PDTValue)) {
return null;
} // if less than start
var startPDT = fragments[0].programDateTime;
if (PDTValue < (startPDT || 0)) {
return null;
}
var endPDT = fragments[fragments.length - 1].endProgramDateTime;
if (PDTValue >= (endPDT || 0)) {
return null;
}
maxFragLookUpTolerance = maxFragLookUpTolerance || 0;
for (var seg = 0; seg < fragments.length; ++seg) {
var frag = fragments[seg];
if (pdtWithinToleranceTest(PDTValue, maxFragLookUpTolerance, frag)) {
return frag;
}
}
return null;
}
/**
* Finds a fragment based on the SN of the previous fragment; or based on the needs of the current buffer.
* This method compensates for small buffer gaps by applying a tolerance to the start of any candidate fragment, thus
* breaking any traps which would cause the same fragment to be continuously selected within a small range.
* @param {*} fragPrevious - The last frag successfully appended
* @param {Array} fragments - The array of candidate fragments
* @param {number} [bufferEnd = 0] - The end of the contiguous buffered range the playhead is currently within
* @param {number} maxFragLookUpTolerance - The amount of time that a fragment's start/end can be within in order to be considered contiguous
* @returns {*} foundFrag - The best matching fragment
*/
function findFragmentByPTS(fragPrevious, fragments, bufferEnd, maxFragLookUpTolerance) {
if (bufferEnd === void 0) {
bufferEnd = 0;
}
if (maxFragLookUpTolerance === void 0) {
maxFragLookUpTolerance = 0;
}
var fragNext = null;
if (fragPrevious) {
fragNext = fragments[fragPrevious.sn - fragments[0].sn + 1];
} else if (bufferEnd === 0 && fragments[0].start === 0) {
fragNext = fragments[0];
} // Prefer the next fragment if it's within tolerance
if (fragNext && fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, fragNext) === 0) {
return fragNext;
} // We might be seeking past the tolerance so find the best match
var foundFragment = _utils_binary_search__WEBPACK_IMPORTED_MODULE_1__["default"].search(fragments, fragmentWithinToleranceTest.bind(null, bufferEnd, maxFragLookUpTolerance));
if (foundFragment) {
return foundFragment;
} // If no match was found return the next fragment after fragPrevious, or null
return fragNext;
}
/**
* The test function used by the findFragmentBySn's BinarySearch to look for the best match to the current buffer conditions.
* @param {*} candidate - The fragment to test
* @param {number} [bufferEnd = 0] - The end of the current buffered range the playhead is currently within
* @param {number} [maxFragLookUpTolerance = 0] - The amount of time that a fragment's start can be within in order to be considered contiguous
* @returns {number} - 0 if it matches, 1 if too low, -1 if too high
*/
function fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, candidate) {
if (bufferEnd === void 0) {
bufferEnd = 0;
}
if (maxFragLookUpTolerance === void 0) {
maxFragLookUpTolerance = 0;
}
// offset should be within fragment boundary - config.maxFragLookUpTolerance
// this is to cope with situations like
// bufferEnd = 9.991
// frag[Ø] : [0,10]
// frag[1] : [10,20]
// bufferEnd is within frag[0] range ... although what we are expecting is to return frag[1] here
// frag start frag start+duration
// |-----------------------------|
// <---> <--->
// ...--------><-----------------------------><---------....
// previous frag matching fragment next frag
// return -1 return 0 return 1
// logger.log(`level/sn/start/end/bufEnd:${level}/${candidate.sn}/${candidate.start}/${(candidate.start+candidate.duration)}/${bufferEnd}`);
// Set the lookup tolerance to be small enough to detect the current segment - ensures we don't skip over very small segments
var candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0));
if (candidate.start + candidate.duration - candidateLookupTolerance <= bufferEnd) {
return 1;
} else if (candidate.start - candidateLookupTolerance > bufferEnd && candidate.start) {
// if maxFragLookUpTolerance will have negative value then don't return -1 for first element
return -1;
}
return 0;
}
/**
* The test function used by the findFragmentByPdt's BinarySearch to look for the best match to the current buffer conditions.
* This function tests the candidate's program date time values, as represented in Unix time
* @param {*} candidate - The fragment to test
* @param {number} [pdtBufferEnd = 0] - The Unix time representing the end of the current buffered range
* @param {number} [maxFragLookUpTolerance = 0] - The amount of time that a fragment's start can be within in order to be considered contiguous
* @returns {boolean} True if contiguous, false otherwise
*/
function pdtWithinToleranceTest(pdtBufferEnd, maxFragLookUpTolerance, candidate) {
var candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0)) * 1000; // endProgramDateTime can be null, default to zero
var endProgramDateTime = candidate.endProgramDateTime || 0;
return endProgramDateTime - candidateLookupTolerance > pdtBufferEnd;
}
function findFragWithCC(fragments, cc) {
return _utils_binary_search__WEBPACK_IMPORTED_MODULE_1__["default"].search(fragments, function (candidate) {
if (candidate.cc < cc) {
return 1;
} else if (candidate.cc > cc) {
return -1;
} else {
return 0;
}
});
}
/***/ }),
/***/ "./src/controller/fragment-tracker.ts":
/*!********************************************!*\
!*** ./src/controller/fragment-tracker.ts ***!
\********************************************/
/*! exports provided: FragmentState, FragmentTracker */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FragmentState", function() { return FragmentState; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FragmentTracker", function() { return FragmentTracker; });
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts");
var FragmentState;
(function (FragmentState) {
FragmentState["NOT_LOADED"] = "NOT_LOADED";
FragmentState["BACKTRACKED"] = "BACKTRACKED";
FragmentState["APPENDING"] = "APPENDING";
FragmentState["PARTIAL"] = "PARTIAL";
FragmentState["OK"] = "OK";
})(FragmentState || (FragmentState = {}));
var FragmentTracker = /*#__PURE__*/function () {
function FragmentTracker(hls) {
this.activeFragment = null;
this.activeParts = null;
this.fragments = Object.create(null);
this.timeRanges = Object.create(null);
this.bufferPadding = 0.2;
this.hls = void 0;
this.hls = hls;
this._registerListeners();
}
var _proto = FragmentTracker.prototype;
_proto._registerListeners = function _registerListeners() {
var hls = this.hls;
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].BUFFER_APPENDED, this.onBufferAppended, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FRAG_BUFFERED, this.onFragBuffered, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FRAG_LOADED, this.onFragLoaded, this);
};
_proto._unregisterListeners = function _unregisterListeners() {
var hls = this.hls;
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].BUFFER_APPENDED, this.onBufferAppended, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FRAG_BUFFERED, this.onFragBuffered, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FRAG_LOADED, this.onFragLoaded, this);
};
_proto.destroy = function destroy() {
this._unregisterListeners(); // @ts-ignore
this.fragments = this.timeRanges = null;
}
/**
* Return a Fragment with an appended range that matches the position and levelType.
* If not found any Fragment, return null
*/
;
_proto.getAppendedFrag = function getAppendedFrag(position, levelType) {
if (levelType === _types_loader__WEBPACK_IMPORTED_MODULE_1__["PlaylistLevelType"].MAIN) {
var activeFragment = this.activeFragment,
activeParts = this.activeParts;
if (!activeFragment) {
return null;
}
if (activeParts) {
for (var i = activeParts.length; i--;) {
var activePart = activeParts[i];
var appendedPTS = activePart ? activePart.end : activeFragment.appendedPTS;
if (activePart.start <= position && appendedPTS !== undefined && position <= appendedPTS) {
// 9 is a magic number. remove parts from lookup after a match but keep some short seeks back.
if (i > 9) {
this.activeParts = activeParts.slice(i - 9);
}
return activePart;
}
}
} else if (activeFragment.start <= position && activeFragment.appendedPTS !== undefined && position <= activeFragment.appendedPTS) {
return activeFragment;
}
}
return this.getBufferedFrag(position, levelType);
}
/**
* Return a buffered Fragment that matches the position and levelType.
* A buffered Fragment is one whose loading, parsing and appending is done (completed or "partial" meaning aborted).
* If not found any Fragment, return null
*/
;
_proto.getBufferedFrag = function getBufferedFrag(position, levelType) {
var fragments = this.fragments;
var keys = Object.keys(fragments);
for (var i = keys.length; i--;) {
var fragmentEntity = fragments[keys[i]];
if ((fragmentEntity === null || fragmentEntity === void 0 ? void 0 : fragmentEntity.body.type) === levelType && fragmentEntity.buffered) {
var frag = fragmentEntity.body;
if (frag.start <= position && position <= frag.end) {
return frag;
}
}
}
return null;
}
/**
* Partial fragments effected by coded frame eviction will be removed
* The browser will unload parts of the buffer to free up memory for new buffer data
* Fragments will need to be reloaded when the buffer is freed up, removing partial fragments will allow them to reload(since there might be parts that are still playable)
*/
;
_proto.detectEvictedFragments = function detectEvictedFragments(elementaryStream, timeRange) {
var _this = this;
// Check if any flagged fragments have been unloaded
Object.keys(this.fragments).forEach(function (key) {
var fragmentEntity = _this.fragments[key];
if (!fragmentEntity || !fragmentEntity.buffered) {
return;
}
var esData = fragmentEntity.range[elementaryStream];
if (!esData) {
return;
}
esData.time.some(function (time) {
var isNotBuffered = !_this.isTimeBuffered(time.startPTS, time.endPTS, timeRange);
if (isNotBuffered) {
// Unregister partial fragment as it needs to load again to be reused
_this.removeFragment(fragmentEntity.body);
}
return isNotBuffered;
});
});
}
/**
* Checks if the fragment passed in is loaded in the buffer properly
* Partially loaded fragments will be registered as a partial fragment
*/
;
_proto.detectPartialFragments = function detectPartialFragments(data) {
var _this2 = this;
var timeRanges = this.timeRanges;
var frag = data.frag,
part = data.part;
if (!timeRanges || frag.sn === 'initSegment') {
return;
}
var fragKey = getFragmentKey(frag);
var fragmentEntity = this.fragments[fragKey];
if (!fragmentEntity) {
return;
}
Object.keys(timeRanges).forEach(function (elementaryStream) {
var streamInfo = frag.elementaryStreams[elementaryStream];
if (!streamInfo) {
return;
}
var timeRange = timeRanges[elementaryStream];
var partial = part !== null || streamInfo.partial === true;
fragmentEntity.range[elementaryStream] = _this2.getBufferedTimes(frag, part, partial, timeRange);
});
fragmentEntity.backtrack = fragmentEntity.loaded = null;
if (Object.keys(fragmentEntity.range).length) {
fragmentEntity.buffered = true;
} else {
// remove fragment if nothing was appended
this.removeFragment(fragmentEntity.body);
}
};
_proto.getBufferedTimes = function getBufferedTimes(fragment, part, partial, timeRange) {
var buffered = {
time: [],
partial: partial
};
var startPTS = part ? part.start : fragment.start;
var endPTS = part ? part.end : fragment.end;
var minEndPTS = fragment.minEndPTS || endPTS;
var maxStartPTS = fragment.maxStartPTS || startPTS;
for (var i = 0; i < timeRange.length; i++) {
var startTime = timeRange.start(i) - this.bufferPadding;
var endTime = timeRange.end(i) + this.bufferPadding;
if (maxStartPTS >= startTime && minEndPTS <= endTime) {
// Fragment is entirely contained in buffer
// No need to check the other timeRange times since it's completely playable
buffered.time.push({
startPTS: Math.max(startPTS, timeRange.start(i)),
endPTS: Math.min(endPTS, timeRange.end(i))
});
break;
} else if (startPTS < endTime && endPTS > startTime) {
buffered.partial = true; // Check for intersection with buffer
// Get playable sections of the fragment
buffered.time.push({
startPTS: Math.max(startPTS, timeRange.start(i)),
endPTS: Math.min(endPTS, timeRange.end(i))
});
} else if (endPTS <= startTime) {
// No need to check the rest of the timeRange as it is in order
break;
}
}
return buffered;
}
/**
* Gets the partial fragment for a certain time
*/
;
_proto.getPartialFragment = function getPartialFragment(time) {
var bestFragment = null;
var timePadding;
var startTime;
var endTime;
var bestOverlap = 0;
var bufferPadding = this.bufferPadding,
fragments = this.fragments;
Object.keys(fragments).forEach(function (key) {
var fragmentEntity = fragments[key];
if (!fragmentEntity) {
return;
}
if (isPartial(fragmentEntity)) {
startTime = fragmentEntity.body.start - bufferPadding;
endTime = fragmentEntity.body.end + bufferPadding;
if (time >= startTime && time <= endTime) {
// Use the fragment that has the most padding from start and end time
timePadding = Math.min(time - startTime, endTime - time);
if (bestOverlap <= timePadding) {
bestFragment = fragmentEntity.body;
bestOverlap = timePadding;
}
}
}
});
return bestFragment;
};
_proto.getState = function getState(fragment) {
var fragKey = getFragmentKey(fragment);
var fragmentEntity = this.fragments[fragKey];
if (fragmentEntity) {
if (!fragmentEntity.buffered) {
if (fragmentEntity.backtrack) {
return FragmentState.BACKTRACKED;
}
return FragmentState.APPENDING;
} else if (isPartial(fragmentEntity)) {
return FragmentState.PARTIAL;
} else {
return FragmentState.OK;
}
}
return FragmentState.NOT_LOADED;
};
_proto.backtrack = function backtrack(frag, data) {
var fragKey = getFragmentKey(frag);
var fragmentEntity = this.fragments[fragKey];
if (!fragmentEntity || fragmentEntity.backtrack) {
return null;
}
var backtrack = fragmentEntity.backtrack = data ? data : fragmentEntity.loaded;
fragmentEntity.loaded = null;
return backtrack;
};
_proto.getBacktrackData = function getBacktrackData(fragment) {
var fragKey = getFragmentKey(fragment);
var fragmentEntity = this.fragments[fragKey];
if (fragmentEntity) {
var _backtrack$payload;
var backtrack = fragmentEntity.backtrack; // If data was already sent to Worker it is detached no longer available
if (backtrack !== null && backtrack !== void 0 && (_backtrack$payload = backtrack.payload) !== null && _backtrack$payload !== void 0 && _backtrack$payload.byteLength) {
return backtrack;
} else {
this.removeFragment(fragment);
}
}
return null;
};
_proto.isTimeBuffered = function isTimeBuffered(startPTS, endPTS, timeRange) {
var startTime;
var endTime;
for (var i = 0; i < timeRange.length; i++) {
startTime = timeRange.start(i) - this.bufferPadding;
endTime = timeRange.end(i) + this.bufferPadding;
if (startPTS >= startTime && endPTS <= endTime) {
return true;
}
if (endPTS <= startTime) {
// No need to check the rest of the timeRange as it is in order
return false;
}
}
return false;
};
_proto.onFragLoaded = function onFragLoaded(event, data) {
var frag = data.frag,
part = data.part; // don't track initsegment (for which sn is not a number)
// don't track frags used for bitrateTest, they're irrelevant.
// don't track parts for memory efficiency
if (frag.sn === 'initSegment' || frag.bitrateTest || part) {
return;
}
var fragKey = getFragmentKey(frag);
this.fragments[fragKey] = {
body: frag,
loaded: data,
backtrack: null,
buffered: false,
range: Object.create(null)
};
};
_proto.onBufferAppended = function onBufferAppended(event, data) {
var _this3 = this;
var frag = data.frag,
part = data.part,
timeRanges = data.timeRanges;
if (frag.type === _types_loader__WEBPACK_IMPORTED_MODULE_1__["PlaylistLevelType"].MAIN) {
this.activeFragment = frag;
if (part) {
var activeParts = this.activeParts;
if (!activeParts) {
this.activeParts = activeParts = [];
}
activeParts.push(part);
} else {
this.activeParts = null;
}
} // Store the latest timeRanges loaded in the buffer
this.timeRanges = timeRanges;
Object.keys(timeRanges).forEach(function (elementaryStream) {
var timeRange = timeRanges[elementaryStream];
_this3.detectEvictedFragments(elementaryStream, timeRange);
if (!part) {
for (var i = 0; i < timeRange.length; i++) {
frag.appendedPTS = Math.max(timeRange.end(i), frag.appendedPTS || 0);
}
}
});
};
_proto.onFragBuffered = function onFragBuffered(event, data) {
this.detectPartialFragments(data);
};
_proto.hasFragment = function hasFragment(fragment) {
var fragKey = getFragmentKey(fragment);
return !!this.fragments[fragKey];
};
_proto.removeFragment = function removeFragment(fragment) {
var fragKey = getFragmentKey(fragment);
fragment.stats.loaded = 0;
fragment.clearElementaryStreamInfo();
delete this.fragments[fragKey];
};
_proto.removeAllFragments = function removeAllFragments() {
this.fragments = Object.create(null);
this.activeFragment = null;
this.activeParts = null;
};
return FragmentTracker;
}();
function isPartial(fragmentEntity) {
var _fragmentEntity$range, _fragmentEntity$range2;
return fragmentEntity.buffered && (((_fragmentEntity$range = fragmentEntity.range.video) === null || _fragmentEntity$range === void 0 ? void 0 : _fragmentEntity$range.partial) || ((_fragmentEntity$range2 = fragmentEntity.range.audio) === null || _fragmentEntity$range2 === void 0 ? void 0 : _fragmentEntity$range2.partial));
}
function getFragmentKey(fragment) {
return fragment.type + "_" + fragment.level + "_" + fragment.urlId + "_" + fragment.sn;
}
/***/ }),
/***/ "./src/controller/gap-controller.ts":
/*!******************************************!*\
!*** ./src/controller/gap-controller.ts ***!
\******************************************/
/*! exports provided: STALL_MINIMUM_DURATION_MS, MAX_START_GAP_JUMP, SKIP_BUFFER_HOLE_STEP_SECONDS, SKIP_BUFFER_RANGE_START, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "STALL_MINIMUM_DURATION_MS", function() { return STALL_MINIMUM_DURATION_MS; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MAX_START_GAP_JUMP", function() { return MAX_START_GAP_JUMP; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SKIP_BUFFER_HOLE_STEP_SECONDS", function() { return SKIP_BUFFER_HOLE_STEP_SECONDS; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SKIP_BUFFER_RANGE_START", function() { return SKIP_BUFFER_RANGE_START; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return GapController; });
/* harmony import */ var _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/buffer-helper */ "./src/utils/buffer-helper.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
var STALL_MINIMUM_DURATION_MS = 250;
var MAX_START_GAP_JUMP = 2.0;
var SKIP_BUFFER_HOLE_STEP_SECONDS = 0.1;
var SKIP_BUFFER_RANGE_START = 0.05;
var GapController = /*#__PURE__*/function () {
function GapController(config, media, fragmentTracker, hls) {
this.config = void 0;
this.media = void 0;
this.fragmentTracker = void 0;
this.hls = void 0;
this.nudgeRetry = 0;
this.stallReported = false;
this.stalled = null;
this.moved = false;
this.seeking = false;
this.config = config;
this.media = media;
this.fragmentTracker = fragmentTracker;
this.hls = hls;
}
var _proto = GapController.prototype;
_proto.destroy = function destroy() {
// @ts-ignore
this.hls = this.fragmentTracker = this.media = null;
}
/**
* Checks if the playhead is stuck within a gap, and if so, attempts to free it.
* A gap is an unbuffered range between two buffered ranges (or the start and the first buffered range).
*
* @param {number} lastCurrentTime Previously read playhead position
*/
;
_proto.poll = function poll(lastCurrentTime) {
var config = this.config,
media = this.media,
stalled = this.stalled;
var currentTime = media.currentTime,
seeking = media.seeking;
var seeked = this.seeking && !seeking;
var beginSeek = !this.seeking && seeking;
this.seeking = seeking; // The playhead is moving, no-op
if (currentTime !== lastCurrentTime) {
this.moved = true;
if (stalled !== null) {
// The playhead is now moving, but was previously stalled
if (this.stallReported) {
var _stalledDuration = self.performance.now() - stalled;
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn("playback not stuck anymore @" + currentTime + ", after " + Math.round(_stalledDuration) + "ms");
this.stallReported = false;
}
this.stalled = null;
this.nudgeRetry = 0;
}
return;
} // Clear stalled state when beginning or finishing seeking so that we don't report stalls coming out of a seek
if (beginSeek || seeked) {
this.stalled = null;
} // The playhead should not be moving
if (media.paused || media.ended || media.playbackRate === 0 || !_utils_buffer_helper__WEBPACK_IMPORTED_MODULE_0__["BufferHelper"].getBuffered(media).length) {
return;
}
var bufferInfo = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_0__["BufferHelper"].bufferInfo(media, currentTime, 0);
var isBuffered = bufferInfo.len > 0;
var nextStart = bufferInfo.nextStart || 0; // There is no playable buffer (seeked, waiting for buffer)
if (!isBuffered && !nextStart) {
return;
}
if (seeking) {
// Waiting for seeking in a buffered range to complete
var hasEnoughBuffer = bufferInfo.len > MAX_START_GAP_JUMP; // Next buffered range is too far ahead to jump to while still seeking
var noBufferGap = !nextStart || nextStart - currentTime > MAX_START_GAP_JUMP && !this.fragmentTracker.getPartialFragment(currentTime);
if (hasEnoughBuffer || noBufferGap) {
return;
} // Reset moved state when seeking to a point in or before a gap
this.moved = false;
} // Skip start gaps if we haven't played, but the last poll detected the start of a stall
// The addition poll gives the browser a chance to jump the gap for us
if (!this.moved && this.stalled !== null) {
var _level$details;
// Jump start gaps within jump threshold
var startJump = Math.max(nextStart, bufferInfo.start || 0) - currentTime; // When joining a live stream with audio tracks, account for live playlist window sliding by allowing
// a larger jump over start gaps caused by the audio-stream-controller buffering a start fragment
// that begins over 1 target duration after the video start position.
var level = this.hls.levels ? this.hls.levels[this.hls.currentLevel] : null;
var isLive = level === null || level === void 0 ? void 0 : (_level$details = level.details) === null || _level$details === void 0 ? void 0 : _level$details.live;
var maxStartGapJump = isLive ? level.details.targetduration * 2 : MAX_START_GAP_JUMP;
if (startJump > 0 && startJump <= maxStartGapJump) {
this._trySkipBufferHole(null);
return;
}
} // Start tracking stall time
var tnow = self.performance.now();
if (stalled === null) {
this.stalled = tnow;
return;
}
var stalledDuration = tnow - stalled;
if (!seeking && stalledDuration >= STALL_MINIMUM_DURATION_MS) {
// Report stalling after trying to fix
this._reportStall(bufferInfo.len);
}
var bufferedWithHoles = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_0__["BufferHelper"].bufferInfo(media, currentTime, config.maxBufferHole);
this._tryFixBufferStall(bufferedWithHoles, stalledDuration);
}
/**
* Detects and attempts to fix known buffer stalling issues.
* @param bufferInfo - The properties of the current buffer.
* @param stalledDurationMs - The amount of time Hls.js has been stalling for.
* @private
*/
;
_proto._tryFixBufferStall = function _tryFixBufferStall(bufferInfo, stalledDurationMs) {
var config = this.config,
fragmentTracker = this.fragmentTracker,
media = this.media;
var currentTime = media.currentTime;
var partial = fragmentTracker.getPartialFragment(currentTime);
if (partial) {
// Try to skip over the buffer hole caused by a partial fragment
// This method isn't limited by the size of the gap between buffered ranges
var targetTime = this._trySkipBufferHole(partial); // we return here in this case, meaning
// the branch below only executes when we don't handle a partial fragment
if (targetTime) {
return;
}
} // if we haven't had to skip over a buffer hole of a partial fragment
// we may just have to "nudge" the playlist as the browser decoding/rendering engine
// needs to cross some sort of threshold covering all source-buffers content
// to start playing properly.
if (bufferInfo.len > config.maxBufferHole && stalledDurationMs > config.highBufferWatchdogPeriod * 1000) {
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn('Trying to nudge playhead over buffer-hole'); // Try to nudge currentTime over a buffer hole if we've been stalling for the configured amount of seconds
// We only try to jump the hole if it's under the configured size
// Reset stalled so to rearm watchdog timer
this.stalled = null;
this._tryNudgeBuffer();
}
}
/**
* Triggers a BUFFER_STALLED_ERROR event, but only once per stall period.
* @param bufferLen - The playhead distance from the end of the current buffer segment.
* @private
*/
;
_proto._reportStall = function _reportStall(bufferLen) {
var hls = this.hls,
media = this.media,
stallReported = this.stallReported;
if (!stallReported) {
// Report stalled error once
this.stallReported = true;
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn("Playback stalling at @" + media.currentTime + " due to low buffer (buffer=" + bufferLen + ")");
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].MEDIA_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].BUFFER_STALLED_ERROR,
fatal: false,
buffer: bufferLen
});
}
}
/**
* Attempts to fix buffer stalls by jumping over known gaps caused by partial fragments
* @param partial - The partial fragment found at the current time (where playback is stalling).
* @private
*/
;
_proto._trySkipBufferHole = function _trySkipBufferHole(partial) {
var config = this.config,
hls = this.hls,
media = this.media;
var currentTime = media.currentTime;
var lastEndTime = 0; // Check if currentTime is between unbuffered regions of partial fragments
var buffered = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_0__["BufferHelper"].getBuffered(media);
for (var i = 0; i < buffered.length; i++) {
var startTime = buffered.start(i);
if (currentTime + config.maxBufferHole >= lastEndTime && currentTime < startTime) {
var targetTime = Math.max(startTime + SKIP_BUFFER_RANGE_START, media.currentTime + SKIP_BUFFER_HOLE_STEP_SECONDS);
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn("skipping hole, adjusting currentTime from " + currentTime + " to " + targetTime);
this.moved = true;
this.stalled = null;
media.currentTime = targetTime;
if (partial) {
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].MEDIA_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].BUFFER_SEEK_OVER_HOLE,
fatal: false,
reason: "fragment loaded with buffer holes, seeking from " + currentTime + " to " + targetTime,
frag: partial
});
}
return targetTime;
}
lastEndTime = buffered.end(i);
}
return 0;
}
/**
* Attempts to fix buffer stalls by advancing the mediaElement's current time by a small amount.
* @private
*/
;
_proto._tryNudgeBuffer = function _tryNudgeBuffer() {
var config = this.config,
hls = this.hls,
media = this.media;
var currentTime = media.currentTime;
var nudgeRetry = (this.nudgeRetry || 0) + 1;
this.nudgeRetry = nudgeRetry;
if (nudgeRetry < config.nudgeMaxRetry) {
var targetTime = currentTime + nudgeRetry * config.nudgeOffset; // playback stalled in buffered area ... let's nudge currentTime to try to overcome this
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn("Nudging 'currentTime' from " + currentTime + " to " + targetTime);
media.currentTime = targetTime;
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].MEDIA_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].BUFFER_NUDGE_ON_STALL,
fatal: false
});
} else {
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].error("Playhead still not moving while enough data buffered @" + currentTime + " after " + config.nudgeMaxRetry + " nudges");
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].MEDIA_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].BUFFER_STALLED_ERROR,
fatal: true
});
}
};
return GapController;
}();
/***/ }),
/***/ "./src/controller/id3-track-controller.ts":
/*!************************************************!*\
!*** ./src/controller/id3-track-controller.ts ***!
\************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/texttrack-utils */ "./src/utils/texttrack-utils.ts");
/* harmony import */ var _demux_id3__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../demux/id3 */ "./src/demux/id3.ts");
var MIN_CUE_DURATION = 0.25;
var ID3TrackController = /*#__PURE__*/function () {
function ID3TrackController(hls) {
this.hls = void 0;
this.id3Track = null;
this.media = null;
this.hls = hls;
this._registerListeners();
}
var _proto = ID3TrackController.prototype;
_proto.destroy = function destroy() {
this._unregisterListeners();
};
_proto._registerListeners = function _registerListeners() {
var hls = this.hls;
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FRAG_PARSING_METADATA, this.onFragParsingMetadata, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].BUFFER_FLUSHING, this.onBufferFlushing, this);
};
_proto._unregisterListeners = function _unregisterListeners() {
var hls = this.hls;
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FRAG_PARSING_METADATA, this.onFragParsingMetadata, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].BUFFER_FLUSHING, this.onBufferFlushing, this);
} // Add ID3 metatadata text track.
;
_proto.onMediaAttached = function onMediaAttached(event, data) {
this.media = data.media;
};
_proto.onMediaDetaching = function onMediaDetaching() {
if (!this.id3Track) {
return;
}
Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_1__["clearCurrentCues"])(this.id3Track);
this.id3Track = null;
this.media = null;
};
_proto.getID3Track = function getID3Track(textTracks) {
if (!this.media) {
return;
}
for (var i = 0; i < textTracks.length; i++) {
var textTrack = textTracks[i];
if (textTrack.kind === 'metadata' && textTrack.label === 'id3') {
// send 'addtrack' when reusing the textTrack for metadata,
// same as what we do for captions
Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_1__["sendAddTrackEvent"])(textTrack, this.media);
return textTrack;
}
}
return this.media.addTextTrack('metadata', 'id3');
};
_proto.onFragParsingMetadata = function onFragParsingMetadata(event, data) {
if (!this.media) {
return;
}
var fragment = data.frag;
var samples = data.samples; // create track dynamically
if (!this.id3Track) {
this.id3Track = this.getID3Track(this.media.textTracks);
this.id3Track.mode = 'hidden';
} // Attempt to recreate Safari functionality by creating
// WebKitDataCue objects when available and store the decoded
// ID3 data in the value property of the cue
var Cue = self.WebKitDataCue || self.VTTCue || self.TextTrackCue;
for (var i = 0; i < samples.length; i++) {
var frames = _demux_id3__WEBPACK_IMPORTED_MODULE_2__["getID3Frames"](samples[i].data);
if (frames) {
var startTime = samples[i].pts;
var endTime = i < samples.length - 1 ? samples[i + 1].pts : fragment.end;
var timeDiff = endTime - startTime;
if (timeDiff <= 0) {
endTime = startTime + MIN_CUE_DURATION;
}
for (var j = 0; j < frames.length; j++) {
var frame = frames[j]; // Safari doesn't put the timestamp frame in the TextTrack
if (!_demux_id3__WEBPACK_IMPORTED_MODULE_2__["isTimeStampFrame"](frame)) {
var cue = new Cue(startTime, endTime, '');
cue.value = frame;
this.id3Track.addCue(cue);
}
}
}
}
};
_proto.onBufferFlushing = function onBufferFlushing(event, _ref) {
var startOffset = _ref.startOffset,
endOffset = _ref.endOffset,
type = _ref.type;
if (!type || type === 'audio') {
// id3 cues come from parsed audio only remove cues when audio buffer is cleared
var id3Track = this.id3Track;
if (id3Track) {
Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_1__["removeCuesInRange"])(id3Track, startOffset, endOffset);
}
}
};
return ID3TrackController;
}();
/* harmony default export */ __webpack_exports__["default"] = (ID3TrackController);
/***/ }),
/***/ "./src/controller/latency-controller.ts":
/*!**********************************************!*\
!*** ./src/controller/latency-controller.ts ***!
\**********************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return LatencyController; });
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
var LatencyController = /*#__PURE__*/function () {
function LatencyController(hls) {
var _this = this;
this.hls = void 0;
this.config = void 0;
this.media = null;
this.levelDetails = null;
this.currentTime = 0;
this.stallCount = 0;
this._latency = null;
this.timeupdateHandler = function () {
return _this.timeupdate();
};
this.hls = hls;
this.config = hls.config;
this.registerListeners();
}
var _proto = LatencyController.prototype;
_proto.destroy = function destroy() {
this.unregisterListeners();
this.onMediaDetaching();
this.levelDetails = null; // @ts-ignore
this.hls = this.timeupdateHandler = null;
};
_proto.registerListeners = function registerListeners() {
this.hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this);
this.hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
this.hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADING, this.onManifestLoading, this);
this.hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_UPDATED, this.onLevelUpdated, this);
this.hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, this.onError, this);
};
_proto.unregisterListeners = function unregisterListeners() {
this.hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_ATTACHED, this.onMediaAttached);
this.hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_DETACHING, this.onMediaDetaching);
this.hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADING, this.onManifestLoading);
this.hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_UPDATED, this.onLevelUpdated);
this.hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, this.onError);
};
_proto.onMediaAttached = function onMediaAttached(event, data) {
this.media = data.media;
this.media.addEventListener('timeupdate', this.timeupdateHandler);
};
_proto.onMediaDetaching = function onMediaDetaching() {
if (this.media) {
this.media.removeEventListener('timeupdate', this.timeupdateHandler);
this.media = null;
}
};
_proto.onManifestLoading = function onManifestLoading() {
this.levelDetails = null;
this._latency = null;
this.stallCount = 0;
};
_proto.onLevelUpdated = function onLevelUpdated(event, _ref) {
var details = _ref.details;
this.levelDetails = details;
if (details.advanced) {
this.timeupdate();
}
if (!details.live && this.media) {
this.media.removeEventListener('timeupdate', this.timeupdateHandler);
}
};
_proto.onError = function onError(event, data) {
if (data.details !== _errors__WEBPACK_IMPORTED_MODULE_0__["ErrorDetails"].BUFFER_STALLED_ERROR) {
return;
}
this.stallCount++;
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn('[playback-rate-controller]: Stall detected, adjusting target latency');
};
_proto.timeupdate = function timeupdate() {
var media = this.media,
levelDetails = this.levelDetails;
if (!media || !levelDetails) {
return;
}
this.currentTime = media.currentTime;
var latency = this.computeLatency();
if (latency === null) {
return;
}
this._latency = latency; // Adapt playbackRate to meet target latency in low-latency mode
var _this$config = this.config,
lowLatencyMode = _this$config.lowLatencyMode,
maxLiveSyncPlaybackRate = _this$config.maxLiveSyncPlaybackRate;
if (!lowLatencyMode || maxLiveSyncPlaybackRate === 1) {
return;
}
var targetLatency = this.targetLatency;
if (targetLatency === null) {
return;
}
var distanceFromTarget = latency - targetLatency; // Only adjust playbackRate when within one target duration of targetLatency
// and more than one second from under-buffering.
// Playback further than one target duration from target can be considered DVR playback.
var liveMinLatencyDuration = Math.min(this.maxLatency, targetLatency + levelDetails.targetduration);
var inLiveRange = distanceFromTarget < liveMinLatencyDuration;
if (levelDetails.live && inLiveRange && distanceFromTarget > 0.05 && this.forwardBufferLength > 1) {
var max = Math.min(2, Math.max(1.0, maxLiveSyncPlaybackRate));
var rate = Math.round(2 / (1 + Math.exp(-0.75 * distanceFromTarget - this.edgeStalled)) * 20) / 20;
media.playbackRate = Math.min(max, Math.max(1, rate));
} else if (media.playbackRate !== 1 && media.playbackRate !== 0) {
media.playbackRate = 1;
}
};
_proto.estimateLiveEdge = function estimateLiveEdge() {
var levelDetails = this.levelDetails;
if (levelDetails === null) {
return null;
}
return levelDetails.edge + levelDetails.age;
};
_proto.computeLatency = function computeLatency() {
var liveEdge = this.estimateLiveEdge();
if (liveEdge === null) {
return null;
}
return liveEdge - this.currentTime;
};
_createClass(LatencyController, [{
key: "latency",
get: function get() {
return this._latency || 0;
}
}, {
key: "maxLatency",
get: function get() {
var config = this.config,
levelDetails = this.levelDetails;
if (config.liveMaxLatencyDuration !== undefined) {
return config.liveMaxLatencyDuration;
}
return levelDetails ? config.liveMaxLatencyDurationCount * levelDetails.targetduration : 0;
}
}, {
key: "targetLatency",
get: function get() {
var levelDetails = this.levelDetails;
if (levelDetails === null) {
return null;
}
var holdBack = levelDetails.holdBack,
partHoldBack = levelDetails.partHoldBack,
targetduration = levelDetails.targetduration;
var _this$config2 = this.config,
liveSyncDuration = _this$config2.liveSyncDuration,
liveSyncDurationCount = _this$config2.liveSyncDurationCount,
lowLatencyMode = _this$config2.lowLatencyMode;
var userConfig = this.hls.userConfig;
var targetLatency = lowLatencyMode ? partHoldBack || holdBack : holdBack;
if (userConfig.liveSyncDuration || userConfig.liveSyncDurationCount || targetLatency === 0) {
targetLatency = liveSyncDuration !== undefined ? liveSyncDuration : liveSyncDurationCount * targetduration;
}
var maxLiveSyncOnStallIncrease = targetduration;
var liveSyncOnStallIncrease = 1.0;
return targetLatency + Math.min(this.stallCount * liveSyncOnStallIncrease, maxLiveSyncOnStallIncrease);
}
}, {
key: "liveSyncPosition",
get: function get() {
var liveEdge = this.estimateLiveEdge();
var targetLatency = this.targetLatency;
var levelDetails = this.levelDetails;
if (liveEdge === null || targetLatency === null || levelDetails === null) {
return null;
}
var edge = levelDetails.edge;
var syncPosition = liveEdge - targetLatency - this.edgeStalled;
var min = edge - levelDetails.totalduration;
var max = edge - (this.config.lowLatencyMode && levelDetails.partTarget || levelDetails.targetduration);
return Math.min(Math.max(min, syncPosition), max);
}
}, {
key: "edgeStalled",
get: function get() {
var levelDetails = this.levelDetails;
if (levelDetails === null) {
return 0;
}
var maxLevelUpdateAge = (this.config.lowLatencyMode && levelDetails.partTarget || levelDetails.targetduration) * 3;
return Math.max(levelDetails.age - maxLevelUpdateAge, 0);
}
}, {
key: "forwardBufferLength",
get: function get() {
var media = this.media,
levelDetails = this.levelDetails;
if (!media || !levelDetails) {
return 0;
}
var bufferedRanges = media.buffered.length;
return bufferedRanges ? media.buffered.end(bufferedRanges - 1) : levelDetails.edge - this.currentTime;
}
}]);
return LatencyController;
}();
/***/ }),
/***/ "./src/controller/level-controller.ts":
/*!********************************************!*\
!*** ./src/controller/level-controller.ts ***!
\********************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return LevelController; });
/* harmony import */ var _types_level__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../types/level */ "./src/types/level.ts");
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
/* harmony import */ var _utils_codecs__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/codecs */ "./src/utils/codecs.ts");
/* harmony import */ var _level_helper__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./level-helper */ "./src/controller/level-helper.ts");
/* harmony import */ var _base_playlist_controller__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./base-playlist-controller */ "./src/controller/base-playlist-controller.ts");
/* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts");
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
/*
* Level Controller
*/
var chromeOrFirefox = /chrome|firefox/.test(navigator.userAgent.toLowerCase());
var LevelController = /*#__PURE__*/function (_BasePlaylistControll) {
_inheritsLoose(LevelController, _BasePlaylistControll);
function LevelController(hls) {
var _this;
_this = _BasePlaylistControll.call(this, hls, '[level-controller]') || this;
_this._levels = [];
_this._firstLevel = -1;
_this._startLevel = void 0;
_this.currentLevelIndex = -1;
_this.manualLevelIndex = -1;
_this.onParsedComplete = void 0;
_this._registerListeners();
return _this;
}
var _proto = LevelController.prototype;
_proto._registerListeners = function _registerListeners() {
var hls = this.hls;
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADED, this.onManifestLoaded, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_LOADED, this.onLevelLoaded, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_LOADED, this.onFragLoaded, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, this.onError, this);
};
_proto._unregisterListeners = function _unregisterListeners() {
var hls = this.hls;
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADED, this.onManifestLoaded, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_LOADED, this.onLevelLoaded, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_LOADED, this.onFragLoaded, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, this.onError, this);
};
_proto.destroy = function destroy() {
this._unregisterListeners();
this.manualLevelIndex = -1;
this._levels.length = 0;
_BasePlaylistControll.prototype.destroy.call(this);
};
_proto.startLoad = function startLoad() {
var levels = this._levels; // clean up live level details to force reload them, and reset load errors
levels.forEach(function (level) {
level.loadError = 0;
});
_BasePlaylistControll.prototype.startLoad.call(this);
};
_proto.onManifestLoaded = function onManifestLoaded(event, data) {
var levels = [];
var audioTracks = [];
var subtitleTracks = [];
var bitrateStart;
var levelSet = {};
var levelFromSet;
var resolutionFound = false;
var videoCodecFound = false;
var audioCodecFound = false; // regroup redundant levels together
data.levels.forEach(function (levelParsed) {
var attributes = levelParsed.attrs;
resolutionFound = resolutionFound || !!(levelParsed.width && levelParsed.height);
videoCodecFound = videoCodecFound || !!levelParsed.videoCodec;
audioCodecFound = audioCodecFound || !!levelParsed.audioCodec; // erase audio codec info if browser does not support mp4a.40.34.
// demuxer will autodetect codec and fallback to mpeg/audio
if (chromeOrFirefox && levelParsed.audioCodec && levelParsed.audioCodec.indexOf('mp4a.40.34') !== -1) {
levelParsed.audioCodec = undefined;
}
levelFromSet = levelSet[levelParsed.bitrate]; // FIXME: we would also have to match the resolution here
if (!levelFromSet) {
levelFromSet = new _types_level__WEBPACK_IMPORTED_MODULE_0__["Level"](levelParsed);
levelSet[levelParsed.bitrate] = levelFromSet;
levels.push(levelFromSet);
} else {
levelFromSet.url.push(levelParsed.url);
}
if (attributes) {
if (attributes.AUDIO) {
Object(_level_helper__WEBPACK_IMPORTED_MODULE_4__["addGroupId"])(levelFromSet, 'audio', attributes.AUDIO);
}
if (attributes.SUBTITLES) {
Object(_level_helper__WEBPACK_IMPORTED_MODULE_4__["addGroupId"])(levelFromSet, 'text', attributes.SUBTITLES);
}
}
}); // remove audio-only level if we also have levels with video codecs or RESOLUTION signalled
if ((resolutionFound || videoCodecFound) && audioCodecFound) {
levels = levels.filter(function (_ref) {
var videoCodec = _ref.videoCodec,
width = _ref.width,
height = _ref.height;
return !!videoCodec || !!(width && height);
});
} // only keep levels with supported audio/video codecs
levels = levels.filter(function (_ref2) {
var audioCodec = _ref2.audioCodec,
videoCodec = _ref2.videoCodec;
return (!audioCodec || Object(_utils_codecs__WEBPACK_IMPORTED_MODULE_3__["isCodecSupportedInMp4"])(audioCodec, 'audio')) && (!videoCodec || Object(_utils_codecs__WEBPACK_IMPORTED_MODULE_3__["isCodecSupportedInMp4"])(videoCodec, 'video'));
});
if (data.audioTracks) {
audioTracks = data.audioTracks.filter(function (track) {
return !track.audioCodec || Object(_utils_codecs__WEBPACK_IMPORTED_MODULE_3__["isCodecSupportedInMp4"])(track.audioCodec, 'audio');
}); // Assign ids after filtering as array indices by group-id
Object(_level_helper__WEBPACK_IMPORTED_MODULE_4__["assignTrackIdsByGroup"])(audioTracks);
}
if (data.subtitles) {
subtitleTracks = data.subtitles;
Object(_level_helper__WEBPACK_IMPORTED_MODULE_4__["assignTrackIdsByGroup"])(subtitleTracks);
}
if (levels.length > 0) {
// start bitrate is the first bitrate of the manifest
bitrateStart = levels[0].bitrate; // sort level on bitrate
levels.sort(function (a, b) {
return a.bitrate - b.bitrate;
});
this._levels = levels; // find index of first level in sorted levels
for (var i = 0; i < levels.length; i++) {
if (levels[i].bitrate === bitrateStart) {
this._firstLevel = i;
this.log("manifest loaded, " + levels.length + " level(s) found, first bitrate: " + bitrateStart);
break;
}
} // Audio is only alternate if manifest include a URI along with the audio group tag,
// and this is not an audio-only stream where levels contain audio-only
var audioOnly = audioCodecFound && !videoCodecFound;
var edata = {
levels: levels,
audioTracks: audioTracks,
subtitleTracks: subtitleTracks,
firstLevel: this._firstLevel,
stats: data.stats,
audio: audioCodecFound,
video: videoCodecFound,
altAudio: !audioOnly && audioTracks.some(function (t) {
return !!t.url;
})
};
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_PARSED, edata); // Initiate loading after all controllers have received MANIFEST_PARSED
if (this.hls.config.autoStartLoad || this.hls.forceStartLoad) {
this.hls.startLoad(this.hls.config.startPosition);
}
} else {
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorTypes"].MEDIA_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].MANIFEST_INCOMPATIBLE_CODECS_ERROR,
fatal: true,
url: data.url,
reason: 'no level with compatible codecs found in manifest'
});
}
};
_proto.onError = function onError(event, data) {
_BasePlaylistControll.prototype.onError.call(this, event, data);
if (data.fatal) {
return;
} // Switch to redundant level when track fails to load
var context = data.context;
var level = this._levels[this.currentLevelIndex];
if (context && (context.type === _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].AUDIO_TRACK && level.audioGroupIds && context.groupId === level.audioGroupIds[level.urlId] || context.type === _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].SUBTITLE_TRACK && level.textGroupIds && context.groupId === level.textGroupIds[level.urlId])) {
this.redundantFailover(this.currentLevelIndex);
return;
}
var levelError = false;
var levelSwitch = true;
var levelIndex; // try to recover not fatal errors
switch (data.details) {
case _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].FRAG_LOAD_ERROR:
case _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].FRAG_LOAD_TIMEOUT:
case _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].KEY_LOAD_ERROR:
case _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].KEY_LOAD_TIMEOUT:
if (data.frag) {
var _level = this._levels[data.frag.level]; // Set levelIndex when we're out of fragment retries
if (_level) {
_level.fragmentError++;
if (_level.fragmentError > this.hls.config.fragLoadingMaxRetry) {
levelIndex = data.frag.level;
}
} else {
levelIndex = data.frag.level;
}
}
break;
case _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].LEVEL_LOAD_ERROR:
case _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].LEVEL_LOAD_TIMEOUT:
// Do not perform level switch if an error occurred using delivery directives
// Attempt to reload level without directives first
if (context) {
if (context.deliveryDirectives) {
levelSwitch = false;
}
levelIndex = context.level;
}
levelError = true;
break;
case _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].REMUX_ALLOC_ERROR:
levelIndex = data.level;
levelError = true;
break;
}
if (levelIndex !== undefined) {
this.recoverLevel(data, levelIndex, levelError, levelSwitch);
}
}
/**
* Switch to a redundant stream if any available.
* If redundant stream is not available, emergency switch down if ABR mode is enabled.
*/
;
_proto.recoverLevel = function recoverLevel(errorEvent, levelIndex, levelError, levelSwitch) {
var errorDetails = errorEvent.details;
var level = this._levels[levelIndex];
level.loadError++;
if (levelError) {
var retrying = this.retryLoadingOrFail(errorEvent);
if (retrying) {
// boolean used to inform stream controller not to switch back to IDLE on non fatal error
errorEvent.levelRetry = true;
} else {
this.currentLevelIndex = -1;
return;
}
}
if (levelSwitch) {
var redundantLevels = level.url.length; // Try redundant fail-over until level.loadError reaches redundantLevels
if (redundantLevels > 1 && level.loadError < redundantLevels) {
errorEvent.levelRetry = true;
this.redundantFailover(levelIndex);
} else if (this.manualLevelIndex === -1) {
// Search for available level in auto level selection mode, cycling from highest to lowest bitrate
var nextLevel = levelIndex === 0 ? this._levels.length - 1 : levelIndex - 1;
if (this.currentLevelIndex !== nextLevel && this._levels[nextLevel].loadError === 0) {
this.warn(errorDetails + ": switch to " + nextLevel);
errorEvent.levelRetry = true;
this.hls.nextAutoLevel = nextLevel;
}
}
}
};
_proto.redundantFailover = function redundantFailover(levelIndex) {
var level = this._levels[levelIndex];
var redundantLevels = level.url.length;
if (redundantLevels > 1) {
// Update the url id of all levels so that we stay on the same set of variants when level switching
var newUrlId = (level.urlId + 1) % redundantLevels;
this.warn("Switching to redundant URL-id " + newUrlId);
this._levels.forEach(function (level) {
level.urlId = newUrlId;
});
this.level = levelIndex;
}
} // reset errors on the successful load of a fragment
;
_proto.onFragLoaded = function onFragLoaded(event, _ref3) {
var frag = _ref3.frag;
if (frag !== undefined && frag.type === _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN) {
var level = this._levels[frag.level];
if (level !== undefined) {
level.fragmentError = 0;
level.loadError = 0;
}
}
};
_proto.onLevelLoaded = function onLevelLoaded(event, data) {
var _data$deliveryDirecti2;
var level = data.level,
details = data.details;
var curLevel = this._levels[level];
if (!curLevel) {
var _data$deliveryDirecti;
this.warn("Invalid level index " + level);
if ((_data$deliveryDirecti = data.deliveryDirectives) !== null && _data$deliveryDirecti !== void 0 && _data$deliveryDirecti.skip) {
details.deltaUpdateFailed = true;
}
return;
} // only process level loaded events matching with expected level
if (level === this.currentLevelIndex) {
// reset level load error counter on successful level loaded only if there is no issues with fragments
if (curLevel.fragmentError === 0) {
curLevel.loadError = 0;
this.retryCount = 0;
}
this.playlistLoaded(level, data, curLevel.details);
} else if ((_data$deliveryDirecti2 = data.deliveryDirectives) !== null && _data$deliveryDirecti2 !== void 0 && _data$deliveryDirecti2.skip) {
// received a delta playlist update that cannot be merged
details.deltaUpdateFailed = true;
}
};
_proto.onAudioTrackSwitched = function onAudioTrackSwitched(event, data) {
var currentLevel = this.hls.levels[this.currentLevelIndex];
if (!currentLevel) {
return;
}
if (currentLevel.audioGroupIds) {
var urlId = -1;
var audioGroupId = this.hls.audioTracks[data.id].groupId;
for (var i = 0; i < currentLevel.audioGroupIds.length; i++) {
if (currentLevel.audioGroupIds[i] === audioGroupId) {
urlId = i;
break;
}
}
if (urlId !== currentLevel.urlId) {
currentLevel.urlId = urlId;
this.startLoad();
}
}
};
_proto.loadPlaylist = function loadPlaylist(hlsUrlParameters) {
var level = this.currentLevelIndex;
var currentLevel = this._levels[level];
if (this.canLoad && currentLevel && currentLevel.url.length > 0) {
var id = currentLevel.urlId;
var url = currentLevel.url[id];
if (hlsUrlParameters) {
try {
url = hlsUrlParameters.addDirectives(url);
} catch (error) {
this.warn("Could not construct new URL with HLS Delivery Directives: " + error);
}
}
this.log("Attempt loading level index " + level + (hlsUrlParameters ? ' at sn ' + hlsUrlParameters.msn + ' part ' + hlsUrlParameters.part : '') + " with URL-id " + id + " " + url); // console.log('Current audio track group ID:', this.hls.audioTracks[this.hls.audioTrack].groupId);
// console.log('New video quality level audio group id:', levelObject.attrs.AUDIO, level);
this.clearTimer();
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_LOADING, {
url: url,
level: level,
id: id,
deliveryDirectives: hlsUrlParameters || null
});
}
};
_proto.removeLevel = function removeLevel(levelIndex, urlId) {
var filterLevelAndGroupByIdIndex = function filterLevelAndGroupByIdIndex(url, id) {
return id !== urlId;
};
var levels = this._levels.filter(function (level, index) {
if (index !== levelIndex) {
return true;
}
if (level.url.length > 1 && urlId !== undefined) {
level.url = level.url.filter(filterLevelAndGroupByIdIndex);
if (level.audioGroupIds) {
level.audioGroupIds = level.audioGroupIds.filter(filterLevelAndGroupByIdIndex);
}
if (level.textGroupIds) {
level.textGroupIds = level.textGroupIds.filter(filterLevelAndGroupByIdIndex);
}
level.urlId = 0;
return true;
}
return false;
}).map(function (level, index) {
var details = level.details;
if (details !== null && details !== void 0 && details.fragments) {
details.fragments.forEach(function (fragment) {
fragment.level = index;
});
}
return level;
});
this._levels = levels;
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVELS_UPDATED, {
levels: levels
});
};
_createClass(LevelController, [{
key: "levels",
get: function get() {
if (this._levels.length === 0) {
return null;
}
return this._levels;
}
}, {
key: "level",
get: function get() {
return this.currentLevelIndex;
},
set: function set(newLevel) {
var _levels$newLevel;
var levels = this._levels;
if (levels.length === 0) {
return;
}
if (this.currentLevelIndex === newLevel && (_levels$newLevel = levels[newLevel]) !== null && _levels$newLevel !== void 0 && _levels$newLevel.details) {
return;
} // check if level idx is valid
if (newLevel < 0 || newLevel >= levels.length) {
// invalid level id given, trigger error
var fatal = newLevel < 0;
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorTypes"].OTHER_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].LEVEL_SWITCH_ERROR,
level: newLevel,
fatal: fatal,
reason: 'invalid level idx'
});
if (fatal) {
return;
}
newLevel = Math.min(newLevel, levels.length - 1);
} // stopping live reloading timer if any
this.clearTimer();
var lastLevelIndex = this.currentLevelIndex;
var lastLevel = levels[lastLevelIndex];
var level = levels[newLevel];
this.log("switching to level " + newLevel + " from " + lastLevelIndex);
this.currentLevelIndex = newLevel;
var levelSwitchingData = _extends({}, level, {
level: newLevel,
maxBitrate: level.maxBitrate,
uri: level.uri,
urlId: level.urlId
}); // @ts-ignore
delete levelSwitchingData._urlId;
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_SWITCHING, levelSwitchingData); // check if we need to load playlist for this level
var levelDetails = level.details;
if (!levelDetails || levelDetails.live) {
// level not retrieved yet, or live playlist we need to (re)load it
var hlsUrlParameters = this.switchParams(level.uri, lastLevel === null || lastLevel === void 0 ? void 0 : lastLevel.details);
this.loadPlaylist(hlsUrlParameters);
}
}
}, {
key: "manualLevel",
get: function get() {
return this.manualLevelIndex;
},
set: function set(newLevel) {
this.manualLevelIndex = newLevel;
if (this._startLevel === undefined) {
this._startLevel = newLevel;
}
if (newLevel !== -1) {
this.level = newLevel;
}
}
}, {
key: "firstLevel",
get: function get() {
return this._firstLevel;
},
set: function set(newLevel) {
this._firstLevel = newLevel;
}
}, {
key: "startLevel",
get: function get() {
// hls.startLevel takes precedence over config.startLevel
// if none of these values are defined, fallback on this._firstLevel (first quality level appearing in variant manifest)
if (this._startLevel === undefined) {
var configStartLevel = this.hls.config.startLevel;
if (configStartLevel !== undefined) {
return configStartLevel;
} else {
return this._firstLevel;
}
} else {
return this._startLevel;
}
},
set: function set(newLevel) {
this._startLevel = newLevel;
}
}, {
key: "nextLoadLevel",
get: function get() {
if (this.manualLevelIndex !== -1) {
return this.manualLevelIndex;
} else {
return this.hls.nextAutoLevel;
}
},
set: function set(nextLevel) {
this.level = nextLevel;
if (this.manualLevelIndex === -1) {
this.hls.nextAutoLevel = nextLevel;
}
}
}]);
return LevelController;
}(_base_playlist_controller__WEBPACK_IMPORTED_MODULE_5__["default"]);
/***/ }),
/***/ "./src/controller/level-helper.ts":
/*!****************************************!*\
!*** ./src/controller/level-helper.ts ***!
\****************************************/
/*! exports provided: addGroupId, assignTrackIdsByGroup, updatePTS, updateFragPTSDTS, mergeDetails, mapPartIntersection, mapFragmentIntersection, adjustSliding, computeReloadInterval, getFragmentWithSN, getPartWith */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "addGroupId", function() { return addGroupId; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "assignTrackIdsByGroup", function() { return assignTrackIdsByGroup; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updatePTS", function() { return updatePTS; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateFragPTSDTS", function() { return updateFragPTSDTS; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mergeDetails", function() { return mergeDetails; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mapPartIntersection", function() { return mapPartIntersection; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mapFragmentIntersection", function() { return mapFragmentIntersection; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "adjustSliding", function() { return adjustSliding; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "computeReloadInterval", function() { return computeReloadInterval; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getFragmentWithSN", function() { return getFragmentWithSN; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getPartWith", function() { return getPartWith; });
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/**
* @module LevelHelper
* Providing methods dealing with playlist sliding and drift
* */
function addGroupId(level, type, id) {
switch (type) {
case 'audio':
if (!level.audioGroupIds) {
level.audioGroupIds = [];
}
level.audioGroupIds.push(id);
break;
case 'text':
if (!level.textGroupIds) {
level.textGroupIds = [];
}
level.textGroupIds.push(id);
break;
}
}
function assignTrackIdsByGroup(tracks) {
var groups = {};
tracks.forEach(function (track) {
var groupId = track.groupId || '';
track.id = groups[groupId] = groups[groupId] || 0;
groups[groupId]++;
});
}
function updatePTS(fragments, fromIdx, toIdx) {
var fragFrom = fragments[fromIdx];
var fragTo = fragments[toIdx];
updateFromToPTS(fragFrom, fragTo);
}
function updateFromToPTS(fragFrom, fragTo) {
var fragToPTS = fragTo.startPTS; // if we know startPTS[toIdx]
if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(fragToPTS)) {
// update fragment duration.
// it helps to fix drifts between playlist reported duration and fragment real duration
var duration = 0;
var frag;
if (fragTo.sn > fragFrom.sn) {
duration = fragToPTS - fragFrom.start;
frag = fragFrom;
} else {
duration = fragFrom.start - fragToPTS;
frag = fragTo;
} // TODO? Drift can go either way, or the playlist could be completely accurate
// console.assert(duration > 0,
// `duration of ${duration} computed for frag ${frag.sn}, level ${frag.level}, there should be some duration drift between playlist and fragment!`);
if (frag.duration !== duration) {
frag.duration = duration;
} // we dont know startPTS[toIdx]
} else if (fragTo.sn > fragFrom.sn) {
var contiguous = fragFrom.cc === fragTo.cc; // TODO: With part-loading end/durations we need to confirm the whole fragment is loaded before using (or setting) minEndPTS
if (contiguous && fragFrom.minEndPTS) {
fragTo.start = fragFrom.start + (fragFrom.minEndPTS - fragFrom.start);
} else {
fragTo.start = fragFrom.start + fragFrom.duration;
}
} else {
fragTo.start = Math.max(fragFrom.start - fragTo.duration, 0);
}
}
function updateFragPTSDTS(details, frag, startPTS, endPTS, startDTS, endDTS) {
var parsedMediaDuration = endPTS - startPTS;
if (parsedMediaDuration <= 0) {
_utils_logger__WEBPACK_IMPORTED_MODULE_1__["logger"].warn('Fragment should have a positive duration', frag);
endPTS = startPTS + frag.duration;
endDTS = startDTS + frag.duration;
}
var maxStartPTS = startPTS;
var minEndPTS = endPTS;
var fragStartPts = frag.startPTS;
var fragEndPts = frag.endPTS;
if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(fragStartPts)) {
// delta PTS between audio and video
var deltaPTS = Math.abs(fragStartPts - startPTS);
if (!Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(frag.deltaPTS)) {
frag.deltaPTS = deltaPTS;
} else {
frag.deltaPTS = Math.max(deltaPTS, frag.deltaPTS);
}
maxStartPTS = Math.max(startPTS, fragStartPts);
startPTS = Math.min(startPTS, fragStartPts);
startDTS = Math.min(startDTS, frag.startDTS);
minEndPTS = Math.min(endPTS, fragEndPts);
endPTS = Math.max(endPTS, fragEndPts);
endDTS = Math.max(endDTS, frag.endDTS);
}
frag.duration = endPTS - startPTS;
var drift = startPTS - frag.start;
frag.appendedPTS = endPTS;
frag.start = frag.startPTS = startPTS;
frag.maxStartPTS = maxStartPTS;
frag.startDTS = startDTS;
frag.endPTS = endPTS;
frag.minEndPTS = minEndPTS;
frag.endDTS = endDTS;
var sn = frag.sn; // 'initSegment'
// exit if sn out of range
if (!details || sn < details.startSN || sn > details.endSN) {
return 0;
}
var i;
var fragIdx = sn - details.startSN;
var fragments = details.fragments; // update frag reference in fragments array
// rationale is that fragments array might not contain this frag object.
// this will happen if playlist has been refreshed between frag loading and call to updateFragPTSDTS()
// if we don't update frag, we won't be able to propagate PTS info on the playlist
// resulting in invalid sliding computation
fragments[fragIdx] = frag; // adjust fragment PTS/duration from seqnum-1 to frag 0
for (i = fragIdx; i > 0; i--) {
updateFromToPTS(fragments[i], fragments[i - 1]);
} // adjust fragment PTS/duration from seqnum to last frag
for (i = fragIdx; i < fragments.length - 1; i++) {
updateFromToPTS(fragments[i], fragments[i + 1]);
}
if (details.fragmentHint) {
updateFromToPTS(fragments[fragments.length - 1], details.fragmentHint);
}
details.PTSKnown = details.alignedSliding = true;
return drift;
}
function mergeDetails(oldDetails, newDetails) {
// potentially retrieve cached initsegment
if (newDetails.initSegment && oldDetails.initSegment) {
newDetails.initSegment = oldDetails.initSegment;
}
if (oldDetails.fragmentHint) {
// prevent PTS and duration from being adjusted on the next hint
delete oldDetails.fragmentHint.endPTS;
} // check if old/new playlists have fragments in common
// loop through overlapping SN and update startPTS , cc, and duration if any found
var ccOffset = 0;
var PTSFrag;
mapFragmentIntersection(oldDetails, newDetails, function (oldFrag, newFrag) {
if (oldFrag.relurl) {
// Do not compare CC if the old fragment has no url. This is a level.fragmentHint used by LL-HLS parts.
// It maybe be off by 1 if it was created before any parts or discontinuity tags were appended to the end
// of the playlist.
ccOffset = oldFrag.cc - newFrag.cc;
}
if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(oldFrag.startPTS) && Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(oldFrag.endPTS)) {
newFrag.start = newFrag.startPTS = oldFrag.startPTS;
newFrag.startDTS = oldFrag.startDTS;
newFrag.appendedPTS = oldFrag.appendedPTS;
newFrag.maxStartPTS = oldFrag.maxStartPTS;
newFrag.endPTS = oldFrag.endPTS;
newFrag.endDTS = oldFrag.endDTS;
newFrag.minEndPTS = oldFrag.minEndPTS;
newFrag.duration = oldFrag.endPTS - oldFrag.startPTS;
if (newFrag.duration) {
PTSFrag = newFrag;
} // PTS is known when any segment has startPTS and endPTS
newDetails.PTSKnown = newDetails.alignedSliding = true;
}
newFrag.elementaryStreams = oldFrag.elementaryStreams;
newFrag.loader = oldFrag.loader;
newFrag.stats = oldFrag.stats;
newFrag.urlId = oldFrag.urlId;
});
if (newDetails.skippedSegments) {
newDetails.deltaUpdateFailed = newDetails.fragments.some(function (frag) {
return !frag;
});
if (newDetails.deltaUpdateFailed) {
_utils_logger__WEBPACK_IMPORTED_MODULE_1__["logger"].warn('[level-helper] Previous playlist missing segments skipped in delta playlist');
for (var i = newDetails.skippedSegments; i--;) {
newDetails.fragments.shift();
}
newDetails.startSN = newDetails.fragments[0].sn;
newDetails.startCC = newDetails.fragments[0].cc;
}
}
var newFragments = newDetails.fragments;
if (ccOffset) {
_utils_logger__WEBPACK_IMPORTED_MODULE_1__["logger"].warn('discontinuity sliding from playlist, take drift into account');
for (var _i = 0; _i < newFragments.length; _i++) {
newFragments[_i].cc += ccOffset;
}
}
if (newDetails.skippedSegments) {
if (!newDetails.initSegment) {
newDetails.initSegment = oldDetails.initSegment;
}
newDetails.startCC = newDetails.fragments[0].cc;
} // Merge parts
mapPartIntersection(oldDetails.partList, newDetails.partList, function (oldPart, newPart) {
newPart.elementaryStreams = oldPart.elementaryStreams;
newPart.stats = oldPart.stats;
}); // if at least one fragment contains PTS info, recompute PTS information for all fragments
if (PTSFrag) {
updateFragPTSDTS(newDetails, PTSFrag, PTSFrag.startPTS, PTSFrag.endPTS, PTSFrag.startDTS, PTSFrag.endDTS);
} else {
// ensure that delta is within oldFragments range
// also adjust sliding in case delta is 0 (we could have old=[50-60] and new=old=[50-61])
// in that case we also need to adjust start offset of all fragments
adjustSliding(oldDetails, newDetails);
}
if (newFragments.length) {
newDetails.totalduration = newDetails.edge - newFragments[0].start;
}
}
function mapPartIntersection(oldParts, newParts, intersectionFn) {
if (oldParts && newParts) {
var delta = 0;
for (var i = 0, len = oldParts.length; i <= len; i++) {
var _oldPart = oldParts[i];
var _newPart = newParts[i + delta];
if (_oldPart && _newPart && _oldPart.index === _newPart.index && _oldPart.fragment.sn === _newPart.fragment.sn) {
intersectionFn(_oldPart, _newPart);
} else {
delta--;
}
}
}
}
function mapFragmentIntersection(oldDetails, newDetails, intersectionFn) {
var skippedSegments = newDetails.skippedSegments;
var start = Math.max(oldDetails.startSN, newDetails.startSN) - newDetails.startSN;
var end = (oldDetails.fragmentHint ? 1 : 0) + (skippedSegments ? newDetails.endSN : Math.min(oldDetails.endSN, newDetails.endSN)) - newDetails.startSN;
var delta = newDetails.startSN - oldDetails.startSN;
var newFrags = newDetails.fragmentHint ? newDetails.fragments.concat(newDetails.fragmentHint) : newDetails.fragments;
var oldFrags = oldDetails.fragmentHint ? oldDetails.fragments.concat(oldDetails.fragmentHint) : oldDetails.fragments;
for (var i = start; i <= end; i++) {
var _oldFrag = oldFrags[delta + i];
var _newFrag = newFrags[i];
if (skippedSegments && !_newFrag && i < skippedSegments) {
// Fill in skipped segments in delta playlist
_newFrag = newDetails.fragments[i] = _oldFrag;
}
if (_oldFrag && _newFrag) {
intersectionFn(_oldFrag, _newFrag);
}
}
}
function adjustSliding(oldDetails, newDetails) {
var delta = newDetails.startSN + newDetails.skippedSegments - oldDetails.startSN;
var oldFragments = oldDetails.fragments;
var newFragments = newDetails.fragments;
if (delta < 0 || delta >= oldFragments.length) {
return;
}
var playlistStartOffset = oldFragments[delta].start;
if (playlistStartOffset) {
for (var i = newDetails.skippedSegments; i < newFragments.length; i++) {
newFragments[i].start += playlistStartOffset;
}
if (newDetails.fragmentHint) {
newDetails.fragmentHint.start += playlistStartOffset;
}
}
}
function computeReloadInterval(newDetails, stats) {
var reloadInterval = 1000 * newDetails.levelTargetDuration;
var reloadIntervalAfterMiss = reloadInterval / 2;
var timeSinceLastModified = newDetails.age;
var useLastModified = timeSinceLastModified > 0 && timeSinceLastModified < reloadInterval * 3;
var roundTrip = stats.loading.end - stats.loading.start;
var estimatedTimeUntilUpdate;
var availabilityDelay = newDetails.availabilityDelay; // let estimate = 'average';
if (newDetails.updated === false) {
if (useLastModified) {
// estimate = 'miss round trip';
// We should have had a hit so try again in the time it takes to get a response,
// but no less than 1/3 second.
var minRetry = 333 * newDetails.misses;
estimatedTimeUntilUpdate = Math.max(Math.min(reloadIntervalAfterMiss, roundTrip * 2), minRetry);
newDetails.availabilityDelay = (newDetails.availabilityDelay || 0) + estimatedTimeUntilUpdate;
} else {
// estimate = 'miss half average';
// follow HLS Spec, If the client reloads a Playlist file and finds that it has not
// changed then it MUST wait for a period of one-half the target
// duration before retrying.
estimatedTimeUntilUpdate = reloadIntervalAfterMiss;
}
} else if (useLastModified) {
// estimate = 'next modified date';
// Get the closest we've been to timeSinceLastModified on update
availabilityDelay = Math.min(availabilityDelay || reloadInterval / 2, timeSinceLastModified);
newDetails.availabilityDelay = availabilityDelay;
estimatedTimeUntilUpdate = availabilityDelay + reloadInterval - timeSinceLastModified;
} else {
estimatedTimeUntilUpdate = reloadInterval - roundTrip;
} // console.log(`[computeReloadInterval] live reload ${newDetails.updated ? 'REFRESHED' : 'MISSED'}`,
// '\n method', estimate,
// '\n estimated time until update =>', estimatedTimeUntilUpdate,
// '\n average target duration', reloadInterval,
// '\n time since modified', timeSinceLastModified,
// '\n time round trip', roundTrip,
// '\n availability delay', availabilityDelay);
return Math.round(estimatedTimeUntilUpdate);
}
function getFragmentWithSN(level, sn) {
if (!level || !level.details) {
return null;
}
var levelDetails = level.details;
var fragment = levelDetails.fragments[sn - levelDetails.startSN];
if (fragment) {
return fragment;
}
fragment = levelDetails.fragmentHint;
if (fragment && fragment.sn === sn) {
return fragment;
}
return null;
}
function getPartWith(level, sn, partIndex) {
if (!level || !level.details) {
return null;
}
var partList = level.details.partList;
if (partList) {
for (var i = partList.length; i--;) {
var part = partList[i];
if (part.index === partIndex && part.fragment.sn === sn) {
return part;
}
}
}
return null;
}
/***/ }),
/***/ "./src/controller/stream-controller.ts":
/*!*********************************************!*\
!*** ./src/controller/stream-controller.ts ***!
\*********************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return StreamController; });
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./base-stream-controller */ "./src/controller/base-stream-controller.ts");
/* harmony import */ var _is_supported__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../is-supported */ "./src/is-supported.ts");
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/buffer-helper */ "./src/utils/buffer-helper.ts");
/* harmony import */ var _fragment_tracker__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./fragment-tracker */ "./src/controller/fragment-tracker.ts");
/* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts");
/* harmony import */ var _loader_fragment__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../loader/fragment */ "./src/loader/fragment.ts");
/* harmony import */ var _demux_transmuxer_interface__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../demux/transmuxer-interface */ "./src/demux/transmuxer-interface.ts");
/* harmony import */ var _types_transmuxer__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../types/transmuxer */ "./src/types/transmuxer.ts");
/* harmony import */ var _gap_controller__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./gap-controller */ "./src/controller/gap-controller.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
var TICK_INTERVAL = 100; // how often to tick in ms
var StreamController = /*#__PURE__*/function (_BaseStreamController) {
_inheritsLoose(StreamController, _BaseStreamController);
function StreamController(hls, fragmentTracker) {
var _this;
_this = _BaseStreamController.call(this, hls, fragmentTracker, '[stream-controller]') || this;
_this.audioCodecSwap = false;
_this.gapController = null;
_this.level = -1;
_this._forceStartLoad = false;
_this.altAudio = false;
_this.audioOnly = false;
_this.fragPlaying = null;
_this.onvplaying = null;
_this.onvseeked = null;
_this.fragLastKbps = 0;
_this.stalled = false;
_this.audioCodecSwitch = false;
_this.videoBuffer = null;
_this._registerListeners();
return _this;
}
var _proto = StreamController.prototype;
_proto._registerListeners = function _registerListeners() {
var hls = this.hls;
hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].MANIFEST_LOADING, this.onManifestLoading, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].MANIFEST_PARSED, this.onManifestParsed, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].LEVEL_LOADING, this.onLevelLoading, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].LEVEL_LOADED, this.onLevelLoaded, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].FRAG_LOAD_EMERGENCY_ABORTED, this.onFragLoadEmergencyAborted, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].ERROR, this.onError, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].BUFFER_CREATED, this.onBufferCreated, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].BUFFER_FLUSHED, this.onBufferFlushed, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].LEVELS_UPDATED, this.onLevelsUpdated, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].FRAG_BUFFERED, this.onFragBuffered, this);
};
_proto._unregisterListeners = function _unregisterListeners() {
var hls = this.hls;
hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].MANIFEST_LOADING, this.onManifestLoading, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].MANIFEST_PARSED, this.onManifestParsed, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].LEVEL_LOADED, this.onLevelLoaded, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].FRAG_LOAD_EMERGENCY_ABORTED, this.onFragLoadEmergencyAborted, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].ERROR, this.onError, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].BUFFER_CREATED, this.onBufferCreated, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].BUFFER_FLUSHED, this.onBufferFlushed, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].LEVELS_UPDATED, this.onLevelsUpdated, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].FRAG_BUFFERED, this.onFragBuffered, this);
};
_proto.onHandlerDestroying = function onHandlerDestroying() {
this._unregisterListeners();
this.onMediaDetaching();
};
_proto.startLoad = function startLoad(startPosition) {
if (this.levels) {
var lastCurrentTime = this.lastCurrentTime,
hls = this.hls;
this.stopLoad();
this.setInterval(TICK_INTERVAL);
this.level = -1;
this.fragLoadError = 0;
if (!this.startFragRequested) {
// determine load level
var startLevel = hls.startLevel;
if (startLevel === -1) {
if (hls.config.testBandwidth) {
// -1 : guess start Level by doing a bitrate test by loading first fragment of lowest quality level
startLevel = 0;
this.bitrateTest = true;
} else {
startLevel = hls.nextAutoLevel;
}
} // set new level to playlist loader : this will trigger start level load
// hls.nextLoadLevel remains until it is set to a new value or until a new frag is successfully loaded
this.level = hls.nextLoadLevel = startLevel;
this.loadedmetadata = false;
} // if startPosition undefined but lastCurrentTime set, set startPosition to last currentTime
if (lastCurrentTime > 0 && startPosition === -1) {
this.log("Override startPosition with lastCurrentTime @" + lastCurrentTime.toFixed(3));
startPosition = lastCurrentTime;
}
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
this.nextLoadPosition = this.startPosition = this.lastCurrentTime = startPosition;
this.tick();
} else {
this._forceStartLoad = true;
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].STOPPED;
}
};
_proto.stopLoad = function stopLoad() {
this._forceStartLoad = false;
_BaseStreamController.prototype.stopLoad.call(this);
};
_proto.doTick = function doTick() {
switch (this.state) {
case _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE:
this.doTickIdle();
break;
case _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_LEVEL:
{
var _levels$level;
var levels = this.levels,
level = this.level;
var details = levels === null || levels === void 0 ? void 0 : (_levels$level = levels[level]) === null || _levels$level === void 0 ? void 0 : _levels$level.details;
if (details && (!details.live || this.levelLastLoaded === this.level)) {
if (this.waitForCdnTuneIn(details)) {
break;
}
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
break;
}
break;
}
case _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].FRAG_LOADING_WAITING_RETRY:
{
var _this$media;
var now = self.performance.now();
var retryDate = this.retryDate; // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading
if (!retryDate || now >= retryDate || (_this$media = this.media) !== null && _this$media !== void 0 && _this$media.seeking) {
this.log('retryDate reached, switch back to IDLE state');
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
}
}
break;
default:
break;
} // check buffer
// check/update current fragment
this.onTickEnd();
};
_proto.onTickEnd = function onTickEnd() {
_BaseStreamController.prototype.onTickEnd.call(this);
this.checkBuffer();
this.checkFragmentChanged();
};
_proto.doTickIdle = function doTickIdle() {
var _frag$decryptdata, _frag$decryptdata2;
var hls = this.hls,
levelLastLoaded = this.levelLastLoaded,
levels = this.levels,
media = this.media;
var config = hls.config,
level = hls.nextLoadLevel; // if start level not parsed yet OR
// if video not attached AND start fragment already requested OR start frag prefetch not enabled
// exit loop, as we either need more info (level not parsed) or we need media to be attached to load new fragment
if (levelLastLoaded === null || !media && (this.startFragRequested || !config.startFragPrefetch)) {
return;
} // If the "main" level is audio-only but we are loading an alternate track in the same group, do not load anything
if (this.altAudio && this.audioOnly) {
return;
}
if (!levels || !levels[level]) {
return;
}
var levelInfo = levels[level]; // if buffer length is less than maxBufLen try to load a new fragment
// set next load level : this will trigger a playlist load if needed
this.level = hls.nextLoadLevel = level;
var levelDetails = levelInfo.details; // if level info not retrieved yet, switch state and wait for level retrieval
// if live playlist, ensure that new playlist has been refreshed to avoid loading/try to load
// a useless and outdated fragment (that might even introduce load error if it is already out of the live playlist)
if (!levelDetails || this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_LEVEL || levelDetails.live && this.levelLastLoaded !== level) {
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_LEVEL;
return;
}
var pos = this.getLoadPosition();
if (!Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(pos)) {
return;
}
var frag = levelDetails.initSegment;
var targetBufferTime = 0;
if (!frag || frag.data || this.bitrateTest) {
// 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 levelBitrate = levelInfo.maxBitrate;
var maxBufLen;
if (levelBitrate) {
maxBufLen = Math.max(8 * config.maxBufferSize / levelBitrate, config.maxBufferLength);
} else {
maxBufLen = config.maxBufferLength;
}
maxBufLen = Math.min(maxBufLen, config.maxMaxBufferLength); // 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 maxBufferHole = pos < config.maxBufferHole ? Math.max(_gap_controller__WEBPACK_IMPORTED_MODULE_10__["MAX_START_GAP_JUMP"], config.maxBufferHole) : config.maxBufferHole;
var bufferInfo = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__["BufferHelper"].bufferInfo(this.mediaBuffer ? this.mediaBuffer : media, pos, maxBufferHole);
var bufferLen = bufferInfo.len; // Stay idle if we are still with buffer margins
if (bufferLen >= maxBufLen) {
return;
}
if (this._streamEnded(bufferInfo, levelDetails)) {
var data = {};
if (this.altAudio) {
data.type = 'video';
}
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].BUFFER_EOS, data);
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].ENDED;
return;
}
targetBufferTime = bufferInfo.end;
frag = this.getNextFragment(targetBufferTime, levelDetails); // Avoid loop loading by using nextLoadPosition set for backtracking
if (frag && this.fragmentTracker.getState(frag) === _fragment_tracker__WEBPACK_IMPORTED_MODULE_5__["FragmentState"].OK && this.nextLoadPosition > targetBufferTime) {
frag = this.getNextFragment(this.nextLoadPosition, levelDetails);
}
if (!frag) {
return;
}
} // We want to load the key if we're dealing with an identity key, because we will decrypt
// this content using the key we fetch. Other keys will be handled by the DRM CDM via EME.
if (((_frag$decryptdata = frag.decryptdata) === null || _frag$decryptdata === void 0 ? void 0 : _frag$decryptdata.keyFormat) === 'identity' && !((_frag$decryptdata2 = frag.decryptdata) !== null && _frag$decryptdata2 !== void 0 && _frag$decryptdata2.key)) {
this.log("Loading key for " + frag.sn + " of [" + levelDetails.startSN + "-" + levelDetails.endSN + "], level " + level);
this.loadKey(frag);
} else {
this.loadFragment(frag, levelDetails, targetBufferTime);
}
};
_proto.loadKey = function loadKey(frag) {
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].KEY_LOADING;
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].KEY_LOADING, {
frag: frag
});
};
_proto.loadFragment = function loadFragment(frag, levelDetails, targetBufferTime) {
var _this$media2;
// Check if fragment is not loaded
var fragState = this.fragmentTracker.getState(frag);
this.fragCurrent = frag; // Use data from loaded backtracked fragment if available
if (fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_5__["FragmentState"].BACKTRACKED) {
var data = this.fragmentTracker.getBacktrackData(frag);
if (data) {
this._handleFragmentLoadProgress(data);
this._handleFragmentLoadComplete(data);
return;
} else {
fragState = _fragment_tracker__WEBPACK_IMPORTED_MODULE_5__["FragmentState"].NOT_LOADED;
}
}
if (fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_5__["FragmentState"].NOT_LOADED || fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_5__["FragmentState"].PARTIAL) {
if (frag.sn === 'initSegment') {
this._loadInitSegment(frag);
} else if (this.bitrateTest) {
frag.bitrateTest = true;
this.log("Fragment " + frag.sn + " of level " + frag.level + " is being downloaded to test bitrate and will not be buffered");
this._loadBitrateTestFrag(frag);
} else {
this.startFragRequested = true;
_BaseStreamController.prototype.loadFragment.call(this, frag, levelDetails, targetBufferTime);
}
} else if (fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_5__["FragmentState"].APPENDING) {
// Lower the buffer size and try again
if (this.reduceMaxBufferLength(frag.duration)) {
this.fragmentTracker.removeFragment(frag);
}
} else if (((_this$media2 = this.media) === null || _this$media2 === void 0 ? void 0 : _this$media2.buffered.length) === 0) {
// Stop gap for bad tracker / buffer flush behavior
this.fragmentTracker.removeAllFragments();
}
};
_proto.getAppendedFrag = function getAppendedFrag(position) {
var fragOrPart = this.fragmentTracker.getAppendedFrag(position, _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN);
if (fragOrPart && 'fragment' in fragOrPart) {
return fragOrPart.fragment;
}
return fragOrPart;
};
_proto.getBufferedFrag = function getBufferedFrag(position) {
return this.fragmentTracker.getBufferedFrag(position, _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN);
};
_proto.followingBufferedFrag = function followingBufferedFrag(frag) {
if (frag) {
// try to get range of next fragment (500ms after this range)
return this.getBufferedFrag(frag.end + 0.5);
}
return null;
}
/*
on immediate level switch :
- pause playback if playing
- cancel any pending load request
- and trigger a buffer flush
*/
;
_proto.immediateLevelSwitch = function immediateLevelSwitch() {
this.abortCurrentFrag();
this.flushMainBuffer(0, Number.POSITIVE_INFINITY);
}
/**
* try to switch ASAP without breaking video playback:
* in order to ensure smooth but quick level switching,
* we need to find the next flushable buffer range
* we should take into account new segment fetch time
*/
;
_proto.nextLevelSwitch = function nextLevelSwitch() {
var levels = this.levels,
media = this.media; // ensure that media is defined and that metadata are available (to retrieve currentTime)
if (media !== null && media !== void 0 && media.readyState) {
var fetchdelay;
var fragPlayingCurrent = this.getAppendedFrag(media.currentTime);
if (fragPlayingCurrent && fragPlayingCurrent.start > 1) {
// flush buffer preceding current fragment (flush until current fragment start offset)
// minus 1s to avoid video freezing, that could happen if we flush keyframe of current video ...
this.flushMainBuffer(0, fragPlayingCurrent.start - 1);
}
if (!media.paused && levels) {
// add a safety delay of 1s
var nextLevelId = this.hls.nextLoadLevel;
var nextLevel = levels[nextLevelId];
var fragLastKbps = this.fragLastKbps;
if (fragLastKbps && this.fragCurrent) {
fetchdelay = this.fragCurrent.duration * nextLevel.maxBitrate / (1000 * fragLastKbps) + 1;
} else {
fetchdelay = 0;
}
} else {
fetchdelay = 0;
} // this.log('fetchdelay:'+fetchdelay);
// find buffer range that will be reached once new fragment will be fetched
var bufferedFrag = this.getBufferedFrag(media.currentTime + fetchdelay);
if (bufferedFrag) {
// we can flush buffer range following this one without stalling playback
var nextBufferedFrag = this.followingBufferedFrag(bufferedFrag);
if (nextBufferedFrag) {
// if we are here, we can also cancel any loading/demuxing in progress, as they are useless
this.abortCurrentFrag(); // start flush position is in next buffered frag. Leave some padding for non-independent segments and smoother playback.
var maxStart = nextBufferedFrag.maxStartPTS ? nextBufferedFrag.maxStartPTS : nextBufferedFrag.start;
var fragDuration = nextBufferedFrag.duration;
var startPts = Math.max(bufferedFrag.end, maxStart + Math.min(Math.max(fragDuration - this.config.maxFragLookUpTolerance, fragDuration * 0.5), fragDuration * 0.75));
this.flushMainBuffer(startPts, Number.POSITIVE_INFINITY);
}
}
}
};
_proto.abortCurrentFrag = function abortCurrentFrag() {
var fragCurrent = this.fragCurrent;
if (fragCurrent !== null && fragCurrent !== void 0 && fragCurrent.loader) {
fragCurrent.loader.abort();
}
this.nextLoadPosition = this.getLoadPosition();
this.fragCurrent = null;
};
_proto.flushMainBuffer = function flushMainBuffer(startOffset, endOffset) {
_BaseStreamController.prototype.flushMainBuffer.call(this, startOffset, endOffset, this.altAudio ? 'video' : null);
};
_proto.onMediaAttached = function onMediaAttached(event, data) {
_BaseStreamController.prototype.onMediaAttached.call(this, event, data);
var media = data.media;
this.onvplaying = this.onMediaPlaying.bind(this);
this.onvseeked = this.onMediaSeeked.bind(this);
media.addEventListener('playing', this.onvplaying);
media.addEventListener('seeked', this.onvseeked);
this.gapController = new _gap_controller__WEBPACK_IMPORTED_MODULE_10__["default"](this.config, media, this.fragmentTracker, this.hls);
};
_proto.onMediaDetaching = function onMediaDetaching() {
var media = this.media;
if (media) {
media.removeEventListener('playing', this.onvplaying);
media.removeEventListener('seeked', this.onvseeked);
this.onvplaying = this.onvseeked = null;
this.videoBuffer = null;
}
this.fragPlaying = null;
if (this.gapController) {
this.gapController.destroy();
this.gapController = null;
}
_BaseStreamController.prototype.onMediaDetaching.call(this);
};
_proto.onMediaPlaying = function onMediaPlaying() {
// tick to speed up FRAG_CHANGED triggering
this.tick();
};
_proto.onMediaSeeked = function onMediaSeeked() {
var media = this.media;
var currentTime = media ? media.currentTime : null;
if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(currentTime)) {
this.log("Media seeked to " + currentTime.toFixed(3));
} // tick to speed up FRAG_CHANGED triggering
this.tick();
};
_proto.onManifestLoading = function onManifestLoading() {
// reset buffer on manifest loading
this.log('Trigger BUFFER_RESET');
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].BUFFER_RESET, undefined);
this.fragmentTracker.removeAllFragments();
this.stalled = false;
this.startPosition = this.lastCurrentTime = 0;
this.fragPlaying = null;
};
_proto.onManifestParsed = function onManifestParsed(event, data) {
var aac = false;
var heaac = false;
var codec;
data.levels.forEach(function (level) {
// detect if we have different kind of audio codecs used amongst playlists
codec = level.audioCodec;
if (codec) {
if (codec.indexOf('mp4a.40.2') !== -1) {
aac = true;
}
if (codec.indexOf('mp4a.40.5') !== -1) {
heaac = true;
}
}
});
this.audioCodecSwitch = aac && heaac && !Object(_is_supported__WEBPACK_IMPORTED_MODULE_2__["changeTypeSupported"])();
if (this.audioCodecSwitch) {
this.log('Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC');
}
this.levels = data.levels;
this.startFragRequested = false;
};
_proto.onLevelLoading = function onLevelLoading(event, data) {
var levels = this.levels;
if (!levels || this.state !== _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE) {
return;
}
var level = levels[data.level];
if (!level.details || level.details.live && this.levelLastLoaded !== data.level || this.waitForCdnTuneIn(level.details)) {
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_LEVEL;
}
};
_proto.onLevelLoaded = function onLevelLoaded(event, data) {
var _curLevel$details;
var levels = this.levels;
var newLevelId = data.level;
var newDetails = data.details;
var duration = newDetails.totalduration;
if (!levels) {
this.warn("Levels were reset while loading level " + newLevelId);
return;
}
this.log("Level " + newLevelId + " loaded [" + newDetails.startSN + "," + newDetails.endSN + "], cc [" + newDetails.startCC + ", " + newDetails.endCC + "] duration:" + duration);
var fragCurrent = this.fragCurrent;
if (fragCurrent && (this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].FRAG_LOADING || this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].FRAG_LOADING_WAITING_RETRY)) {
if (fragCurrent.level !== data.level && fragCurrent.loader) {
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
fragCurrent.loader.abort();
}
}
var curLevel = levels[newLevelId];
var sliding = 0;
if (newDetails.live || (_curLevel$details = curLevel.details) !== null && _curLevel$details !== void 0 && _curLevel$details.live) {
if (!newDetails.fragments[0]) {
newDetails.deltaUpdateFailed = true;
}
if (newDetails.deltaUpdateFailed) {
return;
}
sliding = this.alignPlaylists(newDetails, curLevel.details);
} // override level info
curLevel.details = newDetails;
this.levelLastLoaded = newLevelId;
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].LEVEL_UPDATED, {
details: newDetails,
level: newLevelId
}); // only switch back to IDLE state if we were waiting for level to start downloading a new fragment
if (this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_LEVEL) {
if (this.waitForCdnTuneIn(newDetails)) {
// Wait for Low-Latency CDN Tune-in
return;
}
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
}
if (!this.startFragRequested) {
this.setStartPosition(newDetails, sliding);
} else if (newDetails.live) {
this.synchronizeToLiveEdge(newDetails);
} // trigger handler right now
this.tick();
};
_proto._handleFragmentLoadProgress = function _handleFragmentLoadProgress(data) {
var _details$initSegment;
var frag = data.frag,
part = data.part,
payload = data.payload;
var levels = this.levels;
if (!levels) {
this.warn("Levels were reset while fragment load was in progress. Fragment " + frag.sn + " of level " + frag.level + " will not be buffered");
return;
}
var currentLevel = levels[frag.level];
var details = currentLevel.details;
if (!details) {
this.warn("Dropping fragment " + frag.sn + " of level " + frag.level + " after level details were reset");
return;
}
var videoCodec = currentLevel.videoCodec; // time Offset is accurate if level PTS is known, or if playlist is not sliding (not live)
var accurateTimeOffset = details.PTSKnown || !details.live;
var initSegmentData = (_details$initSegment = details.initSegment) === null || _details$initSegment === void 0 ? void 0 : _details$initSegment.data;
var audioCodec = this._getAudioCodec(currentLevel); // transmux the MPEG-TS data to ISO-BMFF segments
// this.log(`Transmuxing ${frag.sn} of [${details.startSN} ,${details.endSN}],level ${frag.level}, cc ${frag.cc}`);
var transmuxer = this.transmuxer = this.transmuxer || new _demux_transmuxer_interface__WEBPACK_IMPORTED_MODULE_8__["default"](this.hls, _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN, this._handleTransmuxComplete.bind(this), this._handleTransmuxerFlush.bind(this));
var partIndex = part ? part.index : -1;
var partial = partIndex !== -1;
var chunkMeta = new _types_transmuxer__WEBPACK_IMPORTED_MODULE_9__["ChunkMetadata"](frag.level, frag.sn, frag.stats.chunkCount, payload.byteLength, partIndex, partial);
var initPTS = this.initPTS[frag.cc];
transmuxer.push(payload, initSegmentData, audioCodec, videoCodec, frag, part, details.totalduration, accurateTimeOffset, chunkMeta, initPTS);
};
_proto.resetTransmuxer = function resetTransmuxer() {
if (this.transmuxer) {
this.transmuxer.destroy();
this.transmuxer = null;
}
};
_proto.onAudioTrackSwitching = function onAudioTrackSwitching(event, data) {
// if any URL found on new audio track, it is an alternate audio track
var fromAltAudio = this.altAudio;
var altAudio = !!data.url;
var trackId = data.id; // if we switch on main audio, ensure that main fragment scheduling is synced with media.buffered
// don't do anything if we switch to alt audio: audio stream controller is handling it.
// we will just have to change buffer scheduling on audioTrackSwitched
if (!altAudio) {
if (this.mediaBuffer !== this.media) {
this.log('Switching on main audio, use media.buffered to schedule main fragment loading');
this.mediaBuffer = this.media;
var fragCurrent = this.fragCurrent; // we need to refill audio buffer from main: cancel any frag loading to speed up audio switch
if (fragCurrent !== null && fragCurrent !== void 0 && fragCurrent.loader) {
this.log('Switching to main audio track, cancel main fragment load');
fragCurrent.loader.abort();
}
this.fragCurrent = null;
this.fragPrevious = null; // destroy transmuxer to force init segment generation (following audio switch)
this.resetTransmuxer(); // switch to IDLE state to load new fragment
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
} else if (this.audioOnly) {
// Reset audio transmuxer so when switching back to main audio we're not still appending where we left off
this.resetTransmuxer();
}
var hls = this.hls; // If switching from alt to main audio, flush all audio and trigger track switched
if (fromAltAudio) {
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].BUFFER_FLUSHING, {
startOffset: 0,
endOffset: Number.POSITIVE_INFINITY,
type: 'audio'
});
}
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].AUDIO_TRACK_SWITCHED, {
id: trackId
});
}
};
_proto.onAudioTrackSwitched = function onAudioTrackSwitched(event, data) {
var trackId = data.id;
var altAudio = !!this.hls.audioTracks[trackId].url;
if (altAudio) {
var videoBuffer = this.videoBuffer; // if we switched on alternate audio, ensure that main fragment scheduling is synced with video sourcebuffer buffered
if (videoBuffer && this.mediaBuffer !== videoBuffer) {
this.log('Switching on alternate audio, use video.buffered to schedule main fragment loading');
this.mediaBuffer = videoBuffer;
}
}
this.altAudio = altAudio;
this.tick();
};
_proto.onBufferCreated = function onBufferCreated(event, data) {
var tracks = data.tracks;
var mediaTrack;
var name;
var alternate = false;
for (var type in tracks) {
var track = tracks[type];
if (track.id === 'main') {
name = type;
mediaTrack = track; // keep video source buffer reference
if (type === 'video') {
var videoTrack = tracks[type];
if (videoTrack) {
this.videoBuffer = videoTrack.buffer;
}
}
} else {
alternate = true;
}
}
if (alternate && mediaTrack) {
this.log("Alternate track found, use " + name + ".buffered to schedule main fragment loading");
this.mediaBuffer = mediaTrack.buffer;
} else {
this.mediaBuffer = this.media;
}
};
_proto.onFragBuffered = function onFragBuffered(event, data) {
var frag = data.frag,
part = data.part;
if (frag && frag.type !== _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN) {
return;
}
if (this.fragContextChanged(frag)) {
// If a level switch was requested while a fragment was buffering, it will emit the FRAG_BUFFERED event upon completion
// Avoid setting state back to IDLE, since that will interfere with a level switch
this.warn("Fragment " + frag.sn + (part ? ' p: ' + part.index : '') + " of level " + frag.level + " finished buffering, but was aborted. state: " + this.state);
if (this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].PARSED) {
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
}
return;
}
var stats = part ? part.stats : frag.stats;
this.fragLastKbps = Math.round(8 * stats.total / (stats.buffering.end - stats.loading.first));
if (frag.sn !== 'initSegment') {
this.fragPrevious = frag;
}
this.fragBufferedComplete(frag, part);
};
_proto.onError = function onError(event, data) {
switch (data.details) {
case _errors__WEBPACK_IMPORTED_MODULE_11__["ErrorDetails"].FRAG_LOAD_ERROR:
case _errors__WEBPACK_IMPORTED_MODULE_11__["ErrorDetails"].FRAG_LOAD_TIMEOUT:
case _errors__WEBPACK_IMPORTED_MODULE_11__["ErrorDetails"].KEY_LOAD_ERROR:
case _errors__WEBPACK_IMPORTED_MODULE_11__["ErrorDetails"].KEY_LOAD_TIMEOUT:
this.onFragmentOrKeyLoadError(_types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN, data);
break;
case _errors__WEBPACK_IMPORTED_MODULE_11__["ErrorDetails"].LEVEL_LOAD_ERROR:
case _errors__WEBPACK_IMPORTED_MODULE_11__["ErrorDetails"].LEVEL_LOAD_TIMEOUT:
if (this.state !== _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].ERROR) {
if (data.fatal) {
// if fatal error, stop processing
this.warn("" + data.details);
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].ERROR;
} else {
// in case of non fatal error while loading level, if level controller is not retrying to load level , switch back to IDLE
if (!data.levelRetry && this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_LEVEL) {
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
}
}
}
break;
case _errors__WEBPACK_IMPORTED_MODULE_11__["ErrorDetails"].BUFFER_FULL_ERROR:
// if in appending state
if (data.parent === 'main' && (this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].PARSING || this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].PARSED)) {
// 0.5 : tolerance needed as some browsers stalls playback before reaching buffered end
var mediaBuffered = !!this.media && _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__["BufferHelper"].isBuffered(this.media, this.media.currentTime) && _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__["BufferHelper"].isBuffered(this.media, this.media.currentTime + 0.5); // reduce max buf len if current position is buffered
if (mediaBuffered) {
this.reduceMaxBufferLength();
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
} else {
// current position is not buffered, but browser is still complaining about buffer full error
// this happens on IE/Edge, refer to https://github.com/video-dev/hls.js/pull/708
// in that case flush the whole buffer to recover
this.warn('buffer full error also media.currentTime is not buffered, flush everything'); // flush everything
this.immediateLevelSwitch();
}
}
break;
default:
break;
}
} // Checks the health of the buffer and attempts to resolve playback stalls.
;
_proto.checkBuffer = function checkBuffer() {
var media = this.media,
gapController = this.gapController;
if (!media || !gapController || !media.readyState) {
// Exit early if we don't have media or if the media hasn't buffered anything yet (readyState 0)
return;
} // Check combined buffer
var buffered = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__["BufferHelper"].getBuffered(media);
if (!this.loadedmetadata && buffered.length) {
this.loadedmetadata = true;
this._seekToStartPos();
} else {
// Resolve gaps using the main buffer, whose ranges are the intersections of the A/V sourcebuffers
gapController.poll(this.lastCurrentTime);
}
this.lastCurrentTime = media.currentTime;
};
_proto.onFragLoadEmergencyAborted = function onFragLoadEmergencyAborted() {
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE; // if loadedmetadata is not set, it means that we are emergency switch down on first frag
// in that case, reset startFragRequested flag
if (!this.loadedmetadata) {
this.startFragRequested = false;
this.nextLoadPosition = this.startPosition;
}
this.tick();
};
_proto.onBufferFlushed = function onBufferFlushed(event, _ref) {
var type = _ref.type;
if (type !== _loader_fragment__WEBPACK_IMPORTED_MODULE_7__["ElementaryStreamTypes"].AUDIO) {
var media = (type === _loader_fragment__WEBPACK_IMPORTED_MODULE_7__["ElementaryStreamTypes"].VIDEO ? this.videoBuffer : this.mediaBuffer) || this.media;
this.afterBufferFlushed(media, type);
}
};
_proto.onLevelsUpdated = function onLevelsUpdated(event, data) {
this.levels = data.levels;
};
_proto.swapAudioCodec = function swapAudioCodec() {
this.audioCodecSwap = !this.audioCodecSwap;
}
/**
* Seeks to the set startPosition if not equal to the mediaElement's current time.
* @private
*/
;
_proto._seekToStartPos = function _seekToStartPos() {
var media = this.media;
var currentTime = media.currentTime;
var startPosition = this.startPosition; // only adjust currentTime if different from startPosition or if startPosition not buffered
// at that stage, there should be only one buffered range, as we reach that code after first fragment has been buffered
if (startPosition >= 0 && currentTime < startPosition) {
if (media.seeking) {
_utils_logger__WEBPACK_IMPORTED_MODULE_12__["logger"].log("could not seek to " + startPosition + ", already seeking at " + currentTime);
return;
}
var buffered = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__["BufferHelper"].getBuffered(media);
var bufferStart = buffered.length ? buffered.start(0) : 0;
var delta = bufferStart - startPosition;
if (delta > 0 && delta < this.config.maxBufferHole) {
_utils_logger__WEBPACK_IMPORTED_MODULE_12__["logger"].log("adjusting start position by " + delta + " to match buffer start");
startPosition += delta;
this.startPosition = startPosition;
}
this.log("seek to target start position " + startPosition + " from current time " + currentTime);
media.currentTime = startPosition;
}
};
_proto._getAudioCodec = function _getAudioCodec(currentLevel) {
var audioCodec = this.config.defaultAudioCodec || currentLevel.audioCodec;
if (this.audioCodecSwap && audioCodec) {
this.log('Swapping audio codec');
if (audioCodec.indexOf('mp4a.40.5') !== -1) {
audioCodec = 'mp4a.40.2';
} else {
audioCodec = 'mp4a.40.5';
}
}
return audioCodec;
};
_proto._loadBitrateTestFrag = function _loadBitrateTestFrag(frag) {
var _this2 = this;
this._doFragLoad(frag).then(function (data) {
var hls = _this2.hls;
if (!data || hls.nextLoadLevel || _this2.fragContextChanged(frag)) {
return;
}
_this2.fragLoadError = 0;
_this2.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
_this2.startFragRequested = false;
_this2.bitrateTest = false;
var stats = frag.stats; // Bitrate tests fragments are neither parsed nor buffered
stats.parsing.start = stats.parsing.end = stats.buffering.start = stats.buffering.end = self.performance.now();
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].FRAG_LOADED, data);
});
};
_proto._handleTransmuxComplete = function _handleTransmuxComplete(transmuxResult) {
var _id3$samples;
var id = 'main';
var hls = this.hls;
var remuxResult = transmuxResult.remuxResult,
chunkMeta = transmuxResult.chunkMeta;
var context = this.getCurrentContext(chunkMeta);
if (!context) {
this.warn("The loading context changed while buffering fragment " + chunkMeta.sn + " of level " + chunkMeta.level + ". This chunk will not be buffered.");
this.resetLiveStartWhenNotLoaded(chunkMeta.level);
return;
}
var frag = context.frag,
part = context.part,
level = context.level;
var video = remuxResult.video,
text = remuxResult.text,
id3 = remuxResult.id3,
initSegment = remuxResult.initSegment; // The audio-stream-controller handles audio buffering if Hls.js is playing an alternate audio track
var audio = this.altAudio ? undefined : remuxResult.audio; // Check if the current fragment has been aborted. We check this by first seeing if we're still playing the current level.
// If we are, subsequently check if the currently loading fragment (fragCurrent) has changed.
if (this.fragContextChanged(frag)) {
return;
}
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].PARSING;
if (initSegment) {
if (initSegment.tracks) {
this._bufferInitSegment(level, initSegment.tracks, frag, chunkMeta);
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].FRAG_PARSING_INIT_SEGMENT, {
frag: frag,
id: id,
tracks: initSegment.tracks
});
} // This would be nice if Number.isFinite acted as a typeguard, but it doesn't. See: https://github.com/Microsoft/TypeScript/issues/10038
var initPTS = initSegment.initPTS;
var timescale = initSegment.timescale;
if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(initPTS)) {
this.initPTS[frag.cc] = initPTS;
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].INIT_PTS_FOUND, {
frag: frag,
id: id,
initPTS: initPTS,
timescale: timescale
});
}
} // Avoid buffering if backtracking this fragment
if (video && remuxResult.independent !== false) {
if (level.details) {
var startPTS = video.startPTS,
endPTS = video.endPTS,
startDTS = video.startDTS,
endDTS = video.endDTS;
if (part) {
part.elementaryStreams[video.type] = {
startPTS: startPTS,
endPTS: endPTS,
startDTS: startDTS,
endDTS: endDTS
};
} else if (video.dropped && video.independent) {
// Backtrack if dropped frames create a gap after currentTime
var pos = this.getLoadPosition() + this.config.maxBufferHole;
if (pos < startPTS) {
this.backtrack(frag);
return;
} // Set video stream start to fragment start so that truncated samples do not distort the timeline, and mark it partial
frag.setElementaryStreamInfo(video.type, frag.start, endPTS, frag.start, endDTS, true);
}
frag.setElementaryStreamInfo(video.type, startPTS, endPTS, startDTS, endDTS);
this.bufferFragmentData(video, frag, part, chunkMeta);
}
} else if (remuxResult.independent === false) {
this.backtrack(frag);
return;
}
if (audio) {
var _startPTS = audio.startPTS,
_endPTS = audio.endPTS,
_startDTS = audio.startDTS,
_endDTS = audio.endDTS;
if (part) {
part.elementaryStreams[_loader_fragment__WEBPACK_IMPORTED_MODULE_7__["ElementaryStreamTypes"].AUDIO] = {
startPTS: _startPTS,
endPTS: _endPTS,
startDTS: _startDTS,
endDTS: _endDTS
};
}
frag.setElementaryStreamInfo(_loader_fragment__WEBPACK_IMPORTED_MODULE_7__["ElementaryStreamTypes"].AUDIO, _startPTS, _endPTS, _startDTS, _endDTS);
this.bufferFragmentData(audio, frag, part, chunkMeta);
}
if (id3 !== null && id3 !== void 0 && (_id3$samples = id3.samples) !== null && _id3$samples !== void 0 && _id3$samples.length) {
var emittedID3 = {
frag: frag,
id: id,
samples: id3.samples
};
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].FRAG_PARSING_METADATA, emittedID3);
}
if (text) {
var emittedText = {
frag: frag,
id: id,
samples: text.samples
};
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].FRAG_PARSING_USERDATA, emittedText);
}
};
_proto._bufferInitSegment = function _bufferInitSegment(currentLevel, tracks, frag, chunkMeta) {
var _this3 = this;
if (this.state !== _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].PARSING) {
return;
}
this.audioOnly = !!tracks.audio && !tracks.video; // if audio track is expected to come from audio stream controller, discard any coming from main
if (this.altAudio && !this.audioOnly) {
delete tracks.audio;
} // include levelCodec in audio and video tracks
var audio = tracks.audio,
video = tracks.video,
audiovideo = tracks.audiovideo;
if (audio) {
var audioCodec = currentLevel.audioCodec;
var ua = navigator.userAgent.toLowerCase();
if (this.audioCodecSwitch) {
if (audioCodec) {
if (audioCodec.indexOf('mp4a.40.5') !== -1) {
audioCodec = 'mp4a.40.2';
} else {
audioCodec = 'mp4a.40.5';
}
} // In the case that AAC and HE-AAC audio codecs are signalled in manifest,
// force HE-AAC, as it seems that most browsers prefers it.
// don't force HE-AAC if mono stream, or in Firefox
if (audio.metadata.channelCount !== 1 && ua.indexOf('firefox') === -1) {
audioCodec = 'mp4a.40.5';
}
} // HE-AAC is broken on Android, always signal audio codec as AAC even if variant manifest states otherwise
if (ua.indexOf('android') !== -1 && audio.container !== 'audio/mpeg') {
// Exclude mpeg audio
audioCodec = 'mp4a.40.2';
this.log("Android: force audio codec to " + audioCodec);
}
if (currentLevel.audioCodec && currentLevel.audioCodec !== audioCodec) {
this.log("Swapping manifest audio codec \"" + currentLevel.audioCodec + "\" for \"" + audioCodec + "\"");
}
audio.levelCodec = audioCodec;
audio.id = 'main';
this.log("Init audio buffer, container:" + audio.container + ", codecs[selected/level/parsed]=[" + (audioCodec || '') + "/" + (currentLevel.audioCodec || '') + "/" + audio.codec + "]");
}
if (video) {
video.levelCodec = currentLevel.videoCodec;
video.id = 'main';
this.log("Init video buffer, container:" + video.container + ", codecs[level/parsed]=[" + (currentLevel.videoCodec || '') + "/" + video.codec + "]");
}
if (audiovideo) {
this.log("Init audiovideo buffer, container:" + audiovideo.container + ", codecs[level/parsed]=[" + (currentLevel.attrs.CODECS || '') + "/" + audiovideo.codec + "]");
}
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].BUFFER_CODECS, tracks); // loop through tracks that are going to be provided to bufferController
Object.keys(tracks).forEach(function (trackName) {
var track = tracks[trackName];
var initSegment = track.initSegment;
if (initSegment !== null && initSegment !== void 0 && initSegment.byteLength) {
_this3.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].BUFFER_APPENDING, {
type: trackName,
data: initSegment,
frag: frag,
part: null,
chunkMeta: chunkMeta,
parent: frag.type
});
}
}); // trigger handler right now
this.tick();
};
_proto.backtrack = function backtrack(frag) {
// Causes findFragments to backtrack through fragments to find the keyframe
this.resetTransmuxer();
this.flushBufferGap(frag);
var data = this.fragmentTracker.backtrack(frag);
this.fragPrevious = null;
this.nextLoadPosition = frag.start;
if (data) {
this.resetFragmentLoading(frag);
} else {
// Change state to BACKTRACKING so that fragmentEntity.backtrack data can be added after _doFragLoad
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].BACKTRACKING;
}
};
_proto.checkFragmentChanged = function checkFragmentChanged() {
var video = this.media;
var fragPlayingCurrent = null;
if (video && video.readyState > 1 && video.seeking === false) {
var currentTime = video.currentTime;
/* if video element is in seeked state, currentTime can only increase.
(assuming that playback rate is positive ...)
As sometimes currentTime jumps back to zero after a
media decode error, check this, to avoid seeking back to
wrong position after a media decode error
*/
if (_utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__["BufferHelper"].isBuffered(video, currentTime)) {
fragPlayingCurrent = this.getAppendedFrag(currentTime);
} else if (_utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__["BufferHelper"].isBuffered(video, currentTime + 0.1)) {
/* ensure that FRAG_CHANGED event is triggered at startup,
when first video frame is displayed and playback is paused.
add a tolerance of 100ms, in case current position is not buffered,
check if current pos+100ms is buffered and use that buffer range
for FRAG_CHANGED event reporting */
fragPlayingCurrent = this.getAppendedFrag(currentTime + 0.1);
}
if (fragPlayingCurrent) {
var fragPlaying = this.fragPlaying;
var fragCurrentLevel = fragPlayingCurrent.level;
if (!fragPlaying || fragPlayingCurrent.sn !== fragPlaying.sn || fragPlaying.level !== fragCurrentLevel || fragPlayingCurrent.urlId !== fragPlaying.urlId) {
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].FRAG_CHANGED, {
frag: fragPlayingCurrent
});
if (!fragPlaying || fragPlaying.level !== fragCurrentLevel) {
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].LEVEL_SWITCHED, {
level: fragCurrentLevel
});
}
this.fragPlaying = fragPlayingCurrent;
}
}
}
};
_createClass(StreamController, [{
key: "nextLevel",
get: function get() {
var frag = this.nextBufferedFrag;
if (frag) {
return frag.level;
} else {
return -1;
}
}
}, {
key: "currentLevel",
get: function get() {
var media = this.media;
if (media) {
var fragPlayingCurrent = this.getAppendedFrag(media.currentTime);
if (fragPlayingCurrent) {
return fragPlayingCurrent.level;
}
}
return -1;
}
}, {
key: "nextBufferedFrag",
get: function get() {
var media = this.media;
if (media) {
// first get end range of current fragment
var fragPlayingCurrent = this.getAppendedFrag(media.currentTime);
return this.followingBufferedFrag(fragPlayingCurrent);
} else {
return null;
}
}
}, {
key: "forceStartLoad",
get: function get() {
return this._forceStartLoad;
}
}]);
return StreamController;
}(_base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["default"]);
/***/ }),
/***/ "./src/controller/subtitle-stream-controller.ts":
/*!******************************************************!*\
!*** ./src/controller/subtitle-stream-controller.ts ***!
\******************************************************/
/*! exports provided: SubtitleStreamController */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SubtitleStreamController", function() { return SubtitleStreamController; });
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/* harmony import */ var _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/buffer-helper */ "./src/utils/buffer-helper.ts");
/* harmony import */ var _fragment_finders__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./fragment-finders */ "./src/controller/fragment-finders.ts");
/* harmony import */ var _fragment_tracker__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./fragment-tracker */ "./src/controller/fragment-tracker.ts");
/* harmony import */ var _base_stream_controller__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./base-stream-controller */ "./src/controller/base-stream-controller.ts");
/* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts");
/* harmony import */ var _types_level__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../types/level */ "./src/types/level.ts");
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
var TICK_INTERVAL = 500; // how often to tick in ms
var SubtitleStreamController = /*#__PURE__*/function (_BaseStreamController) {
_inheritsLoose(SubtitleStreamController, _BaseStreamController);
function SubtitleStreamController(hls, fragmentTracker) {
var _this;
_this = _BaseStreamController.call(this, hls, fragmentTracker, '[subtitle-stream-controller]') || this;
_this.levels = [];
_this.currentTrackId = -1;
_this.tracksBuffered = void 0;
_this.config = hls.config;
_this.fragCurrent = null;
_this.fragPrevious = null;
_this.media = null;
_this.mediaBuffer = null;
_this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_5__["State"].STOPPED;
_this.tracksBuffered = [];
_this._registerListeners();
return _this;
}
var _proto = SubtitleStreamController.prototype;
_proto._registerListeners = function _registerListeners() {
var hls = this.hls;
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, this.onError, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].SUBTITLE_TRACK_SWITCH, this.onSubtitleTrackSwitch, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].SUBTITLE_FRAG_PROCESSED, this.onSubtitleFragProcessed, this);
};
_proto._unregisterListeners = function _unregisterListeners() {
var hls = this.hls;
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, this.onError, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].SUBTITLE_TRACK_SWITCH, this.onSubtitleTrackSwitch, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].SUBTITLE_FRAG_PROCESSED, this.onSubtitleFragProcessed, this);
};
_proto.startLoad = function startLoad() {
this.stopLoad();
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_5__["State"].IDLE; // Check if we already have a track with necessary details to load fragments
var currentTrack = this.levels[this.currentTrackId];
if (currentTrack !== null && currentTrack !== void 0 && currentTrack.details) {
this.setInterval(TICK_INTERVAL);
this.tick();
}
};
_proto.onHandlerDestroyed = function onHandlerDestroyed() {
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_5__["State"].STOPPED;
this._unregisterListeners();
_BaseStreamController.prototype.onHandlerDestroyed.call(this);
};
_proto.onSubtitleFragProcessed = function onSubtitleFragProcessed(event, data) {
var frag = data.frag,
success = data.success;
this.fragPrevious = frag;
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_5__["State"].IDLE;
if (!success) {
return;
}
var buffered = this.tracksBuffered[this.currentTrackId];
if (!buffered) {
return;
} // Create/update a buffered array matching the interface used by BufferHelper.bufferedInfo
// so we can re-use the logic used to detect how much have been buffered
var timeRange;
var fragStart = frag.start;
for (var i = 0; i < buffered.length; i++) {
if (fragStart >= buffered[i].start && fragStart <= buffered[i].end) {
timeRange = buffered[i];
break;
}
}
var fragEnd = frag.start + frag.duration;
if (timeRange) {
timeRange.end = fragEnd;
} else {
timeRange = {
start: fragStart,
end: fragEnd
};
buffered.push(timeRange);
}
};
_proto.onMediaAttached = function onMediaAttached(event, _ref) {
var media = _ref.media;
this.media = media;
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_5__["State"].IDLE;
};
_proto.onMediaDetaching = function onMediaDetaching() {
var _this2 = this;
if (!this.media) {
return;
}
this.fragmentTracker.removeAllFragments();
this.fragPrevious = null;
this.currentTrackId = -1;
this.levels.forEach(function (level) {
_this2.tracksBuffered[level.id] = [];
});
this.media = null;
this.mediaBuffer = null;
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_5__["State"].STOPPED;
} // If something goes wrong, proceed to next frag, if we were processing one.
;
_proto.onError = function onError(event, data) {
var _this$fragCurrent;
var frag = data.frag; // don't handle error not related to subtitle fragment
if (!frag || frag.type !== _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].SUBTITLE) {
return;
}
if ((_this$fragCurrent = this.fragCurrent) !== null && _this$fragCurrent !== void 0 && _this$fragCurrent.loader) {
this.fragCurrent.loader.abort();
}
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_5__["State"].IDLE;
} // Got all new subtitle levels.
;
_proto.onSubtitleTracksUpdated = function onSubtitleTracksUpdated(event, _ref2) {
var _this3 = this;
var subtitleTracks = _ref2.subtitleTracks;
this.tracksBuffered = [];
this.levels = subtitleTracks.map(function (mediaPlaylist) {
return new _types_level__WEBPACK_IMPORTED_MODULE_7__["Level"](mediaPlaylist);
});
this.fragmentTracker.removeAllFragments();
this.fragPrevious = null;
this.levels.forEach(function (level) {
_this3.tracksBuffered[level.id] = [];
});
this.mediaBuffer = null;
};
_proto.onSubtitleTrackSwitch = function onSubtitleTrackSwitch(event, data) {
this.currentTrackId = data.id;
if (!this.levels.length || this.currentTrackId === -1) {
this.clearInterval();
return;
} // Check if track has the necessary details to load fragments
var currentTrack = this.levels[this.currentTrackId];
if (currentTrack !== null && currentTrack !== void 0 && currentTrack.details) {
this.mediaBuffer = this.mediaBufferTimeRanges;
this.setInterval(TICK_INTERVAL);
} else {
this.mediaBuffer = null;
}
} // Got a new set of subtitle fragments.
;
_proto.onSubtitleTrackLoaded = function onSubtitleTrackLoaded(event, data) {
var _currentTrack$details;
var id = data.id,
details = data.details;
var currentTrackId = this.currentTrackId,
levels = this.levels;
if (!levels.length || !details) {
return;
}
var currentTrack = levels[currentTrackId];
if (id >= levels.length || id !== currentTrackId || !currentTrack) {
return;
}
this.mediaBuffer = this.mediaBufferTimeRanges;
if (details.live || (_currentTrack$details = currentTrack.details) !== null && _currentTrack$details !== void 0 && _currentTrack$details.live) {
if (details.deltaUpdateFailed) {
return;
} // TODO: Subtitle Fragments should be assigned startPTS and endPTS once VTT/TTML is parsed
// otherwise this depends on DISCONTINUITY or PROGRAM-DATE-TIME tags to align playlists
this.alignPlaylists(details, currentTrack.details);
}
currentTrack.details = details;
this.levelLastLoaded = id;
this.setInterval(TICK_INTERVAL);
};
_proto._handleFragmentLoadComplete = function _handleFragmentLoadComplete(fragLoadedData) {
var frag = fragLoadedData.frag,
payload = fragLoadedData.payload;
var decryptData = frag.decryptdata;
var hls = this.hls;
if (this.fragContextChanged(frag)) {
return;
} // check to see if the payload needs to be decrypted
if (payload && payload.byteLength > 0 && decryptData && decryptData.key && decryptData.iv && decryptData.method === 'AES-128') {
var startTime = performance.now(); // decrypt the subtitles
this.decrypter.webCryptoDecrypt(new Uint8Array(payload), decryptData.key.buffer, decryptData.iv.buffer).then(function (decryptedData) {
var endTime = performance.now();
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FRAG_DECRYPTED, {
frag: frag,
payload: decryptedData,
stats: {
tstart: startTime,
tdecrypt: endTime
}
});
});
}
};
_proto.doTick = function doTick() {
if (!this.media) {
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_5__["State"].IDLE;
return;
}
if (this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_5__["State"].IDLE) {
var _foundFrag;
var config = this.config,
currentTrackId = this.currentTrackId,
fragmentTracker = this.fragmentTracker,
media = this.media,
levels = this.levels;
if (!levels.length || !levels[currentTrackId] || !levels[currentTrackId].details) {
return;
}
var maxBufferHole = config.maxBufferHole,
maxFragLookUpTolerance = config.maxFragLookUpTolerance;
var maxConfigBuffer = Math.min(config.maxBufferLength, config.maxMaxBufferLength);
var bufferedInfo = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_2__["BufferHelper"].bufferedInfo(this.mediaBufferTimeRanges, media.currentTime, maxBufferHole);
var targetBufferTime = bufferedInfo.end,
bufferLen = bufferedInfo.len;
if (bufferLen > maxConfigBuffer) {
return;
}
var trackDetails = levels[currentTrackId].details;
console.assert(trackDetails, 'Subtitle track details are defined on idle subtitle stream controller tick');
var fragments = trackDetails.fragments;
var fragLen = fragments.length;
var end = fragments[fragLen - 1].start + fragments[fragLen - 1].duration;
var foundFrag;
var fragPrevious = this.fragPrevious;
if (targetBufferTime < end) {
if (fragPrevious && trackDetails.hasProgramDateTime) {
foundFrag = Object(_fragment_finders__WEBPACK_IMPORTED_MODULE_3__["findFragmentByPDT"])(fragments, fragPrevious.endProgramDateTime, maxFragLookUpTolerance);
}
if (!foundFrag) {
foundFrag = Object(_fragment_finders__WEBPACK_IMPORTED_MODULE_3__["findFragmentByPTS"])(fragPrevious, fragments, targetBufferTime, maxFragLookUpTolerance);
}
} else {
foundFrag = fragments[fragLen - 1];
}
if ((_foundFrag = foundFrag) !== null && _foundFrag !== void 0 && _foundFrag.encrypted) {
_utils_logger__WEBPACK_IMPORTED_MODULE_1__["logger"].log("Loading key for " + foundFrag.sn);
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_5__["State"].KEY_LOADING;
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].KEY_LOADING, {
frag: foundFrag
});
} else if (foundFrag && fragmentTracker.getState(foundFrag) === _fragment_tracker__WEBPACK_IMPORTED_MODULE_4__["FragmentState"].NOT_LOADED) {
// only load if fragment is not loaded
this.loadFragment(foundFrag, trackDetails, targetBufferTime);
}
}
};
_proto.loadFragment = function loadFragment(frag, levelDetails, targetBufferTime) {
this.fragCurrent = frag;
_BaseStreamController.prototype.loadFragment.call(this, frag, levelDetails, targetBufferTime);
};
_proto.stopLoad = function stopLoad() {
this.fragPrevious = null;
_BaseStreamController.prototype.stopLoad.call(this);
};
_createClass(SubtitleStreamController, [{
key: "mediaBufferTimeRanges",
get: function get() {
return this.tracksBuffered[this.currentTrackId] || [];
}
}]);
return SubtitleStreamController;
}(_base_stream_controller__WEBPACK_IMPORTED_MODULE_5__["default"]);
/***/ }),
/***/ "./src/controller/subtitle-track-controller.ts":
/*!*****************************************************!*\
!*** ./src/controller/subtitle-track-controller.ts ***!
\*****************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/texttrack-utils */ "./src/utils/texttrack-utils.ts");
/* harmony import */ var _base_playlist_controller__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./base-playlist-controller */ "./src/controller/base-playlist-controller.ts");
/* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts");
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
var SubtitleTrackController = /*#__PURE__*/function (_BasePlaylistControll) {
_inheritsLoose(SubtitleTrackController, _BasePlaylistControll);
// Enable/disable subtitle display rendering
function SubtitleTrackController(hls) {
var _this;
_this = _BasePlaylistControll.call(this, hls, '[subtitle-track-controller]') || this;
_this.media = null;
_this.tracks = [];
_this.groupId = null;
_this.tracksInGroup = [];
_this.trackId = -1;
_this.selectDefaultTrack = true;
_this.queuedDefaultTrack = -1;
_this.trackChangeListener = function () {
return _this.onTextTracksChanged();
};
_this.useTextTrackPolling = false;
_this.subtitlePollingInterval = -1;
_this.subtitleDisplay = true;
_this.registerListeners();
return _this;
}
var _proto = SubtitleTrackController.prototype;
_proto.destroy = function destroy() {
this.unregisterListeners();
this.tracks.length = 0;
this.tracksInGroup.length = 0; // @ts-ignore
this.trackChangeListener = null;
_BasePlaylistControll.prototype.destroy.call(this);
};
_proto.registerListeners = function registerListeners() {
var hls = this.hls;
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MANIFEST_LOADING, this.onManifestLoading, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MANIFEST_PARSED, this.onManifestParsed, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].LEVEL_LOADING, this.onLevelLoading, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].LEVEL_SWITCHING, this.onLevelSwitching, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, this.onError, this);
};
_proto.unregisterListeners = function unregisterListeners() {
var hls = this.hls;
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MANIFEST_LOADING, this.onManifestLoading, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MANIFEST_PARSED, this.onManifestParsed, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].LEVEL_LOADING, this.onLevelLoading, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].LEVEL_SWITCHING, this.onLevelSwitching, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, this.onError, this);
} // Listen for subtitle track change, then extract the current track ID.
;
_proto.onMediaAttached = function onMediaAttached(event, data) {
var _this2 = this;
this.media = data.media;
if (!this.media) {
return;
}
if (this.queuedDefaultTrack > -1) {
this.subtitleTrack = this.queuedDefaultTrack;
this.queuedDefaultTrack = -1;
}
this.useTextTrackPolling = !(this.media.textTracks && 'onchange' in this.media.textTracks);
if (this.useTextTrackPolling) {
self.clearInterval(this.subtitlePollingInterval);
this.subtitlePollingInterval = self.setInterval(function () {
_this2.trackChangeListener();
}, 500);
} else {
this.media.textTracks.addEventListener('change', this.trackChangeListener);
}
};
_proto.onMediaDetaching = function onMediaDetaching() {
if (!this.media) {
return;
}
if (this.useTextTrackPolling) {
self.clearInterval(this.subtitlePollingInterval);
} else {
this.media.textTracks.removeEventListener('change', this.trackChangeListener);
}
if (this.trackId > -1) {
this.queuedDefaultTrack = this.trackId;
}
var textTracks = filterSubtitleTracks(this.media.textTracks); // Clear loaded cues on media detachment from tracks
textTracks.forEach(function (track) {
Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_1__["clearCurrentCues"])(track);
}); // Disable all subtitle tracks before detachment so when reattached only tracks in that content are enabled.
this.subtitleTrack = -1;
this.media = null;
};
_proto.onManifestLoading = function onManifestLoading() {
this.tracks = [];
this.groupId = null;
this.tracksInGroup = [];
this.trackId = -1;
this.selectDefaultTrack = true;
} // Fired whenever a new manifest is loaded.
;
_proto.onManifestParsed = function onManifestParsed(event, data) {
this.tracks = data.subtitleTracks;
};
_proto.onSubtitleTrackLoaded = function onSubtitleTrackLoaded(event, data) {
var id = data.id,
details = data.details;
var trackId = this.trackId;
var currentTrack = this.tracksInGroup[trackId];
if (!currentTrack) {
this.warn("Invalid subtitle track id " + id);
return;
}
var curDetails = currentTrack.details;
currentTrack.details = data.details;
this.log("subtitle track " + id + " loaded [" + details.startSN + "-" + details.endSN + "]");
if (id === this.trackId) {
this.retryCount = 0;
this.playlistLoaded(id, data, curDetails);
}
};
_proto.onLevelLoading = function onLevelLoading(event, data) {
this.switchLevel(data.level);
};
_proto.onLevelSwitching = function onLevelSwitching(event, data) {
this.switchLevel(data.level);
};
_proto.switchLevel = function switchLevel(levelIndex) {
var levelInfo = this.hls.levels[levelIndex];
if (!(levelInfo !== null && levelInfo !== void 0 && levelInfo.textGroupIds)) {
return;
}
var textGroupId = levelInfo.textGroupIds[levelInfo.urlId];
if (this.groupId !== textGroupId) {
var lastTrack = this.tracksInGroup ? this.tracksInGroup[this.trackId] : undefined;
var initialTrackId = this.findTrackId(lastTrack === null || lastTrack === void 0 ? void 0 : lastTrack.name) || this.findTrackId();
var subtitleTracks = this.tracks.filter(function (track) {
return !textGroupId || track.groupId === textGroupId;
});
this.groupId = textGroupId;
this.tracksInGroup = subtitleTracks;
var subtitleTracksUpdated = {
subtitleTracks: subtitleTracks
};
this.log("Updating subtitle tracks, " + subtitleTracks.length + " track(s) found in \"" + textGroupId + "\" group-id");
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].SUBTITLE_TRACKS_UPDATED, subtitleTracksUpdated);
if (initialTrackId !== -1) {
this.setSubtitleTrack(initialTrackId, lastTrack);
}
}
};
_proto.findTrackId = function findTrackId(name) {
var audioTracks = this.tracksInGroup;
for (var i = 0; i < audioTracks.length; i++) {
var track = audioTracks[i];
if (!this.selectDefaultTrack || track.default) {
if (!name || name === track.name) {
return track.id;
}
}
}
return -1;
};
_proto.onError = function onError(event, data) {
_BasePlaylistControll.prototype.onError.call(this, event, data);
if (data.fatal || !data.context) {
return;
}
if (data.context.type === _types_loader__WEBPACK_IMPORTED_MODULE_3__["PlaylistContextType"].SUBTITLE_TRACK && data.context.id === this.trackId && data.context.groupId === this.groupId) {
this.retryLoadingOrFail(data);
}
}
/** get alternate subtitle tracks list from playlist **/
;
_proto.loadPlaylist = function loadPlaylist(hlsUrlParameters) {
var currentTrack = this.tracksInGroup[this.trackId];
if (this.shouldLoadTrack(currentTrack)) {
var id = currentTrack.id;
var groupId = currentTrack.groupId;
var url = currentTrack.url;
if (hlsUrlParameters) {
try {
url = hlsUrlParameters.addDirectives(url);
} catch (error) {
this.warn("Could not construct new URL with HLS Delivery Directives: " + error);
}
}
this.log("Loading subtitle playlist for id " + id);
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].SUBTITLE_TRACK_LOADING, {
url: url,
id: id,
groupId: groupId,
deliveryDirectives: hlsUrlParameters || null
});
}
}
/**
* Disables the old subtitleTrack and sets current mode on the next subtitleTrack.
* This operates on the DOM textTracks.
* A value of -1 will disable all subtitle tracks.
*/
;
_proto.toggleTrackModes = function toggleTrackModes(newId) {
var _this3 = this;
var media = this.media,
subtitleDisplay = this.subtitleDisplay,
trackId = this.trackId;
if (!media) {
return;
}
var textTracks = filterSubtitleTracks(media.textTracks);
var groupTracks = textTracks.filter(function (track) {
return track.groupId === _this3.groupId;
});
if (newId === -1) {
[].slice.call(textTracks).forEach(function (track) {
track.mode = 'disabled';
});
} else {
var oldTrack = groupTracks[trackId];
if (oldTrack) {
oldTrack.mode = 'disabled';
}
}
var nextTrack = groupTracks[newId];
if (nextTrack) {
nextTrack.mode = subtitleDisplay ? 'showing' : 'hidden';
}
}
/**
* This method is responsible for validating the subtitle index and periodically reloading if live.
* Dispatches the SUBTITLE_TRACK_SWITCH event, which instructs the subtitle-stream-controller to load the selected track.
*/
;
_proto.setSubtitleTrack = function setSubtitleTrack(newId, lastTrack) {
var _tracks$newId;
var tracks = this.tracksInGroup; // setting this.subtitleTrack will trigger internal logic
// if media has not been attached yet, it will fail
// we keep a reference to the default track id
// and we'll set subtitleTrack when onMediaAttached is triggered
if (!this.media) {
this.queuedDefaultTrack = newId;
return;
}
if (this.trackId !== newId) {
this.toggleTrackModes(newId);
} // exit if track id as already set or invalid
if (this.trackId === newId && (newId === -1 || (_tracks$newId = tracks[newId]) !== null && _tracks$newId !== void 0 && _tracks$newId.details) || newId < -1 || newId >= tracks.length) {
return;
} // stopping live reloading timer if any
this.clearTimer();
var track = tracks[newId];
this.log("Switching to subtitle track " + newId);
this.trackId = newId;
if (track) {
var url = track.url,
type = track.type,
id = track.id;
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].SUBTITLE_TRACK_SWITCH, {
id: id,
type: type,
url: url
});
var hlsUrlParameters = this.switchParams(track.url, lastTrack === null || lastTrack === void 0 ? void 0 : lastTrack.details);
this.loadPlaylist(hlsUrlParameters);
} else {
// switch to -1
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].SUBTITLE_TRACK_SWITCH, {
id: newId
});
}
};
_proto.onTextTracksChanged = function onTextTracksChanged() {
// Media is undefined when switching streams via loadSource()
if (!this.media || !this.hls.config.renderTextTracksNatively) {
return;
}
var trackId = -1;
var tracks = filterSubtitleTracks(this.media.textTracks);
for (var id = 0; id < tracks.length; id++) {
if (tracks[id].mode === 'hidden') {
// Do not break in case there is a following track with showing.
trackId = id;
} else if (tracks[id].mode === 'showing') {
trackId = id;
break;
}
} // Setting current subtitleTrack will invoke code.
this.subtitleTrack = trackId;
};
_createClass(SubtitleTrackController, [{
key: "subtitleTracks",
get: function get() {
return this.tracksInGroup;
}
/** get/set index of the selected subtitle track (based on index in subtitle track lists) **/
}, {
key: "subtitleTrack",
get: function get() {
return this.trackId;
},
set: function set(newId) {
this.selectDefaultTrack = false;
var lastTrack = this.tracksInGroup ? this.tracksInGroup[this.trackId] : undefined;
this.setSubtitleTrack(newId, lastTrack);
}
}]);
return SubtitleTrackController;
}(_base_playlist_controller__WEBPACK_IMPORTED_MODULE_2__["default"]);
function filterSubtitleTracks(textTrackList) {
var tracks = [];
for (var i = 0; i < textTrackList.length; i++) {
var track = textTrackList[i]; // Edge adds a track without a label; we don't want to use it
if (track.kind === 'subtitles' && track.label) {
tracks.push(textTrackList[i]);
}
}
return tracks;
}
/* harmony default export */ __webpack_exports__["default"] = (SubtitleTrackController);
/***/ }),
/***/ "./src/controller/timeline-controller.ts":
/*!***********************************************!*\
!*** ./src/controller/timeline-controller.ts ***!
\***********************************************/
/*! exports provided: TimelineController */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TimelineController", function() { return TimelineController; });
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _utils_cea_608_parser__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/cea-608-parser */ "./src/utils/cea-608-parser.ts");
/* harmony import */ var _utils_output_filter__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/output-filter */ "./src/utils/output-filter.ts");
/* harmony import */ var _utils_webvtt_parser__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/webvtt-parser */ "./src/utils/webvtt-parser.ts");
/* harmony import */ var _utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/texttrack-utils */ "./src/utils/texttrack-utils.ts");
/* harmony import */ var _utils_imsc1_ttml_parser__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../utils/imsc1-ttml-parser */ "./src/utils/imsc1-ttml-parser.ts");
/* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
var TimelineController = /*#__PURE__*/function () {
function TimelineController(hls) {
this.hls = void 0;
this.media = null;
this.config = void 0;
this.enabled = true;
this.Cues = void 0;
this.textTracks = [];
this.tracks = [];
this.initPTS = [];
this.timescale = [];
this.unparsedVttFrags = [];
this.captionsTracks = {};
this.nonNativeCaptionsTracks = {};
this.cea608Parser1 = void 0;
this.cea608Parser2 = void 0;
this.lastSn = -1;
this.prevCC = -1;
this.vttCCs = newVTTCCs();
this.captionsProperties = void 0;
this.hls = hls;
this.config = hls.config;
this.Cues = hls.config.cueHandler;
this.captionsProperties = {
textTrack1: {
label: this.config.captionsTextTrack1Label,
languageCode: this.config.captionsTextTrack1LanguageCode
},
textTrack2: {
label: this.config.captionsTextTrack2Label,
languageCode: this.config.captionsTextTrack2LanguageCode
},
textTrack3: {
label: this.config.captionsTextTrack3Label,
languageCode: this.config.captionsTextTrack3LanguageCode
},
textTrack4: {
label: this.config.captionsTextTrack4Label,
languageCode: this.config.captionsTextTrack4LanguageCode
}
};
if (this.config.enableCEA708Captions) {
var channel1 = new _utils_output_filter__WEBPACK_IMPORTED_MODULE_3__["default"](this, 'textTrack1');
var channel2 = new _utils_output_filter__WEBPACK_IMPORTED_MODULE_3__["default"](this, 'textTrack2');
var channel3 = new _utils_output_filter__WEBPACK_IMPORTED_MODULE_3__["default"](this, 'textTrack3');
var channel4 = new _utils_output_filter__WEBPACK_IMPORTED_MODULE_3__["default"](this, 'textTrack4');
this.cea608Parser1 = new _utils_cea_608_parser__WEBPACK_IMPORTED_MODULE_2__["default"](1, channel1, channel2);
this.cea608Parser2 = new _utils_cea_608_parser__WEBPACK_IMPORTED_MODULE_2__["default"](3, channel3, channel4);
}
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_ATTACHING, this.onMediaAttaching, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADING, this.onManifestLoading, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADED, this.onManifestLoaded, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_LOADING, this.onFragLoading, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_LOADED, this.onFragLoaded, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_PARSING_USERDATA, this.onFragParsingUserdata, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_DECRYPTED, this.onFragDecrypted, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].INIT_PTS_FOUND, this.onInitPtsFound, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_TRACKS_CLEARED, this.onSubtitleTracksCleared, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_FLUSHING, this.onBufferFlushing, this);
}
var _proto = TimelineController.prototype;
_proto.destroy = function destroy() {
var hls = this.hls;
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_ATTACHING, this.onMediaAttaching, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADING, this.onManifestLoading, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADED, this.onManifestLoaded, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_LOADING, this.onFragLoading, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_LOADED, this.onFragLoaded, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_PARSING_USERDATA, this.onFragParsingUserdata, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_DECRYPTED, this.onFragDecrypted, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].INIT_PTS_FOUND, this.onInitPtsFound, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_TRACKS_CLEARED, this.onSubtitleTracksCleared, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_FLUSHING, this.onBufferFlushing, this); // @ts-ignore
this.hls = this.config = this.cea608Parser1 = this.cea608Parser2 = null;
};
_proto.addCues = function addCues(trackName, startTime, endTime, screen, cueRanges) {
// skip cues which overlap more than 50% with previously parsed time ranges
var merged = false;
for (var i = cueRanges.length; i--;) {
var cueRange = cueRanges[i];
var overlap = intersection(cueRange[0], cueRange[1], startTime, endTime);
if (overlap >= 0) {
cueRange[0] = Math.min(cueRange[0], startTime);
cueRange[1] = Math.max(cueRange[1], endTime);
merged = true;
if (overlap / (endTime - startTime) > 0.5) {
return;
}
}
}
if (!merged) {
cueRanges.push([startTime, endTime]);
}
if (this.config.renderTextTracksNatively) {
var track = this.captionsTracks[trackName];
this.Cues.newCue(track, startTime, endTime, screen);
} else {
var cues = this.Cues.newCue(null, startTime, endTime, screen);
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].CUES_PARSED, {
type: 'captions',
cues: cues,
track: trackName
});
}
} // Triggered when an initial PTS is found; used for synchronisation of WebVTT.
;
_proto.onInitPtsFound = function onInitPtsFound(event, _ref) {
var _this = this;
var frag = _ref.frag,
id = _ref.id,
initPTS = _ref.initPTS,
timescale = _ref.timescale;
var unparsedVttFrags = this.unparsedVttFrags;
if (id === 'main') {
this.initPTS[frag.cc] = initPTS;
this.timescale[frag.cc] = timescale;
} // Due to asynchronous processing, initial PTS may arrive later than the first VTT fragments are loaded.
// Parse any unparsed fragments upon receiving the initial PTS.
if (unparsedVttFrags.length) {
this.unparsedVttFrags = [];
unparsedVttFrags.forEach(function (frag) {
_this.onFragLoaded(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_LOADED, frag);
});
}
};
_proto.getExistingTrack = function getExistingTrack(trackName) {
var media = this.media;
if (media) {
for (var i = 0; i < media.textTracks.length; i++) {
var textTrack = media.textTracks[i];
if (textTrack[trackName]) {
return textTrack;
}
}
}
return null;
};
_proto.createCaptionsTrack = function createCaptionsTrack(trackName) {
if (this.config.renderTextTracksNatively) {
this.createNativeTrack(trackName);
} else {
this.createNonNativeTrack(trackName);
}
};
_proto.createNativeTrack = function createNativeTrack(trackName) {
if (this.captionsTracks[trackName]) {
return;
}
var captionsProperties = this.captionsProperties,
captionsTracks = this.captionsTracks,
media = this.media;
var _captionsProperties$t = captionsProperties[trackName],
label = _captionsProperties$t.label,
languageCode = _captionsProperties$t.languageCode; // Enable reuse of existing text track.
var existingTrack = this.getExistingTrack(trackName);
if (!existingTrack) {
var textTrack = this.createTextTrack('captions', label, languageCode);
if (textTrack) {
// Set a special property on the track so we know it's managed by Hls.js
textTrack[trackName] = true;
captionsTracks[trackName] = textTrack;
}
} else {
captionsTracks[trackName] = existingTrack;
Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_5__["clearCurrentCues"])(captionsTracks[trackName]);
Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_5__["sendAddTrackEvent"])(captionsTracks[trackName], media);
}
};
_proto.createNonNativeTrack = function createNonNativeTrack(trackName) {
if (this.nonNativeCaptionsTracks[trackName]) {
return;
} // Create a list of a single track for the provider to consume
var trackProperties = this.captionsProperties[trackName];
if (!trackProperties) {
return;
}
var label = trackProperties.label;
var track = {
_id: trackName,
label: label,
kind: 'captions',
default: trackProperties.media ? !!trackProperties.media.default : false,
closedCaptions: trackProperties.media
};
this.nonNativeCaptionsTracks[trackName] = track;
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].NON_NATIVE_TEXT_TRACKS_FOUND, {
tracks: [track]
});
};
_proto.createTextTrack = function createTextTrack(kind, label, lang) {
var media = this.media;
if (!media) {
return;
}
return media.addTextTrack(kind, label, lang);
};
_proto.onMediaAttaching = function onMediaAttaching(event, data) {
this.media = data.media;
this._cleanTracks();
};
_proto.onMediaDetaching = function onMediaDetaching() {
var captionsTracks = this.captionsTracks;
Object.keys(captionsTracks).forEach(function (trackName) {
Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_5__["clearCurrentCues"])(captionsTracks[trackName]);
delete captionsTracks[trackName];
});
this.nonNativeCaptionsTracks = {};
};
_proto.onManifestLoading = function onManifestLoading() {
this.lastSn = -1; // Detect discontinuity in fragment parsing
this.prevCC = -1;
this.vttCCs = newVTTCCs(); // Detect discontinuity in subtitle manifests
this._cleanTracks();
this.tracks = [];
this.captionsTracks = {};
this.nonNativeCaptionsTracks = {};
this.textTracks = [];
this.unparsedVttFrags = this.unparsedVttFrags || [];
this.initPTS = [];
this.timescale = [];
if (this.cea608Parser1 && this.cea608Parser2) {
this.cea608Parser1.reset();
this.cea608Parser2.reset();
}
};
_proto._cleanTracks = function _cleanTracks() {
// clear outdated subtitles
var media = this.media;
if (!media) {
return;
}
var textTracks = media.textTracks;
if (textTracks) {
for (var i = 0; i < textTracks.length; i++) {
Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_5__["clearCurrentCues"])(textTracks[i]);
}
}
};
_proto.onSubtitleTracksUpdated = function onSubtitleTracksUpdated(event, data) {
var _this2 = this;
this.textTracks = [];
var tracks = data.subtitleTracks || [];
var hasIMSC1 = tracks.some(function (track) {
return track.textCodec === _utils_imsc1_ttml_parser__WEBPACK_IMPORTED_MODULE_6__["IMSC1_CODEC"];
});
if (this.config.enableWebVTT || hasIMSC1 && this.config.enableIMSC1) {
var sameTracks = this.tracks && tracks && this.tracks.length === tracks.length;
this.tracks = tracks || [];
if (this.config.renderTextTracksNatively) {
var inUseTracks = this.media ? this.media.textTracks : [];
this.tracks.forEach(function (track, index) {
var textTrack;
if (index < inUseTracks.length) {
var inUseTrack = null;
for (var i = 0; i < inUseTracks.length; i++) {
if (canReuseVttTextTrack(inUseTracks[i], track)) {
inUseTrack = inUseTracks[i];
break;
}
} // Reuse tracks with the same label, but do not reuse 608/708 tracks
if (inUseTrack) {
textTrack = inUseTrack;
}
}
if (textTrack) {
Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_5__["clearCurrentCues"])(textTrack);
} else {
textTrack = _this2.createTextTrack('subtitles', track.name, track.lang);
if (textTrack) {
textTrack.mode = 'disabled';
}
}
if (textTrack) {
textTrack.groupId = track.groupId;
_this2.textTracks.push(textTrack);
}
});
} else if (!sameTracks && this.tracks && this.tracks.length) {
// Create a list of tracks for the provider to consume
var tracksList = this.tracks.map(function (track) {
return {
label: track.name,
kind: track.type.toLowerCase(),
default: track.default,
subtitleTrack: track
};
});
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].NON_NATIVE_TEXT_TRACKS_FOUND, {
tracks: tracksList
});
}
}
};
_proto.onManifestLoaded = function onManifestLoaded(event, data) {
var _this3 = this;
if (this.config.enableCEA708Captions && data.captions) {
data.captions.forEach(function (captionsTrack) {
var instreamIdMatch = /(?:CC|SERVICE)([1-4])/.exec(captionsTrack.instreamId);
if (!instreamIdMatch) {
return;
}
var trackName = "textTrack" + instreamIdMatch[1];
var trackProperties = _this3.captionsProperties[trackName];
if (!trackProperties) {
return;
}
trackProperties.label = captionsTrack.name;
if (captionsTrack.lang) {
// optional attribute
trackProperties.languageCode = captionsTrack.lang;
}
trackProperties.media = captionsTrack;
});
}
};
_proto.onFragLoading = function onFragLoading(event, data) {
var cea608Parser1 = this.cea608Parser1,
cea608Parser2 = this.cea608Parser2,
lastSn = this.lastSn;
if (!this.enabled || !(cea608Parser1 && cea608Parser2)) {
return;
} // if this frag isn't contiguous, clear the parser so cues with bad start/end times aren't added to the textTrack
if (data.frag.type === _types_loader__WEBPACK_IMPORTED_MODULE_7__["PlaylistLevelType"].MAIN) {
var sn = data.frag.sn;
if (sn !== lastSn + 1) {
cea608Parser1.reset();
cea608Parser2.reset();
}
this.lastSn = sn;
}
};
_proto.onFragLoaded = function onFragLoaded(event, data) {
var frag = data.frag,
payload = data.payload;
var initPTS = this.initPTS,
unparsedVttFrags = this.unparsedVttFrags;
if (frag.type === _types_loader__WEBPACK_IMPORTED_MODULE_7__["PlaylistLevelType"].SUBTITLE) {
// If fragment is subtitle type, parse as WebVTT.
if (payload.byteLength) {
// We need an initial synchronisation PTS. Store fragments as long as none has arrived.
if (!Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(initPTS[frag.cc])) {
unparsedVttFrags.push(data);
if (initPTS.length) {
// finish unsuccessfully, otherwise the subtitle-stream-controller could be blocked from loading new frags.
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_FRAG_PROCESSED, {
success: false,
frag: frag,
error: new Error('Missing initial subtitle PTS')
});
}
return;
}
var decryptData = frag.decryptdata; // If the subtitles are not encrypted, parse VTTs now. Otherwise, we need to wait.
if (decryptData == null || decryptData.key == null || decryptData.method !== 'AES-128') {
var trackPlaylistMedia = this.tracks[frag.level];
var vttCCs = this.vttCCs;
if (!vttCCs[frag.cc]) {
vttCCs[frag.cc] = {
start: frag.start,
prevCC: this.prevCC,
new: true
};
this.prevCC = frag.cc;
}
if (trackPlaylistMedia && trackPlaylistMedia.textCodec === _utils_imsc1_ttml_parser__WEBPACK_IMPORTED_MODULE_6__["IMSC1_CODEC"]) {
this._parseIMSC1(frag, payload);
} else {
this._parseVTTs(frag, payload, vttCCs);
}
}
} else {
// In case there is no payload, finish unsuccessfully.
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_FRAG_PROCESSED, {
success: false,
frag: frag,
error: new Error('Empty subtitle payload')
});
}
}
};
_proto._parseIMSC1 = function _parseIMSC1(frag, payload) {
var _this4 = this;
var hls = this.hls;
Object(_utils_imsc1_ttml_parser__WEBPACK_IMPORTED_MODULE_6__["parseIMSC1"])(payload, this.initPTS[frag.cc], this.timescale[frag.cc], function (cues) {
_this4._appendCues(cues, frag.level);
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_FRAG_PROCESSED, {
success: true,
frag: frag
});
}, function (error) {
_utils_logger__WEBPACK_IMPORTED_MODULE_8__["logger"].log("Failed to parse IMSC1: " + error);
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_FRAG_PROCESSED, {
success: false,
frag: frag,
error: error
});
});
};
_proto._parseVTTs = function _parseVTTs(frag, payload, vttCCs) {
var _this5 = this;
var hls = this.hls; // Parse the WebVTT file contents.
Object(_utils_webvtt_parser__WEBPACK_IMPORTED_MODULE_4__["parseWebVTT"])(payload, this.initPTS[frag.cc], this.timescale[frag.cc], vttCCs, frag.cc, frag.start, function (cues) {
_this5._appendCues(cues, frag.level);
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_FRAG_PROCESSED, {
success: true,
frag: frag
});
}, function (error) {
_this5._fallbackToIMSC1(frag, payload); // Something went wrong while parsing. Trigger event with success false.
_utils_logger__WEBPACK_IMPORTED_MODULE_8__["logger"].log("Failed to parse VTT cue: " + error);
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_FRAG_PROCESSED, {
success: false,
frag: frag,
error: error
});
});
};
_proto._fallbackToIMSC1 = function _fallbackToIMSC1(frag, payload) {
var _this6 = this;
// If textCodec is unknown, try parsing as IMSC1. Set textCodec based on the result
var trackPlaylistMedia = this.tracks[frag.level];
if (!trackPlaylistMedia.textCodec) {
Object(_utils_imsc1_ttml_parser__WEBPACK_IMPORTED_MODULE_6__["parseIMSC1"])(payload, this.initPTS[frag.cc], this.timescale[frag.cc], function () {
trackPlaylistMedia.textCodec = _utils_imsc1_ttml_parser__WEBPACK_IMPORTED_MODULE_6__["IMSC1_CODEC"];
_this6._parseIMSC1(frag, payload);
}, function () {
trackPlaylistMedia.textCodec = 'wvtt';
});
}
};
_proto._appendCues = function _appendCues(cues, fragLevel) {
var hls = this.hls;
if (this.config.renderTextTracksNatively) {
var textTrack = this.textTracks[fragLevel]; // WebVTTParser.parse is an async method and if the currently selected text track mode is set to "disabled"
// before parsing is done then don't try to access currentTrack.cues.getCueById as cues will be null
// and trying to access getCueById method of cues will throw an exception
// Because we check if the mode is disabled, we can force check `cues` below. They can't be null.
if (textTrack.mode === 'disabled') {
return;
}
cues.forEach(function (cue) {
return Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_5__["addCueToTrack"])(textTrack, cue);
});
} else {
var currentTrack = this.tracks[fragLevel];
var track = currentTrack.default ? 'default' : 'subtitles' + fragLevel;
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].CUES_PARSED, {
type: 'subtitles',
cues: cues,
track: track
});
}
};
_proto.onFragDecrypted = function onFragDecrypted(event, data) {
var frag = data.frag;
if (frag.type === _types_loader__WEBPACK_IMPORTED_MODULE_7__["PlaylistLevelType"].SUBTITLE) {
if (!Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(this.initPTS[frag.cc])) {
this.unparsedVttFrags.push(data);
return;
}
this.onFragLoaded(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_LOADED, data);
}
};
_proto.onSubtitleTracksCleared = function onSubtitleTracksCleared() {
this.tracks = [];
this.captionsTracks = {};
};
_proto.onFragParsingUserdata = function onFragParsingUserdata(event, data) {
var cea608Parser1 = this.cea608Parser1,
cea608Parser2 = this.cea608Parser2;
if (!this.enabled || !(cea608Parser1 && cea608Parser2)) {
return;
} // If the event contains captions (found in the bytes property), push all bytes into the parser immediately
// It will create the proper timestamps based on the PTS value
for (var i = 0; i < data.samples.length; i++) {
var ccBytes = data.samples[i].bytes;
if (ccBytes) {
var ccdatas = this.extractCea608Data(ccBytes);
cea608Parser1.addData(data.samples[i].pts, ccdatas[0]);
cea608Parser2.addData(data.samples[i].pts, ccdatas[1]);
}
}
};
_proto.onBufferFlushing = function onBufferFlushing(event, _ref2) {
var startOffset = _ref2.startOffset,
endOffset = _ref2.endOffset,
type = _ref2.type;
// Clear 608 CC cues from the back buffer
// Forward cues are never removed because we can loose streamed 608 content from recent fragments
if (!type || type === 'video') {
var media = this.media;
if (!media || media.currentTime < endOffset) {
return;
}
var captionsTracks = this.captionsTracks;
Object.keys(captionsTracks).forEach(function (trackName) {
return Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_5__["removeCuesInRange"])(captionsTracks[trackName], startOffset, endOffset);
});
}
};
_proto.extractCea608Data = function extractCea608Data(byteArray) {
var count = byteArray[0] & 31;
var position = 2;
var actualCCBytes = [[], []];
for (var j = 0; j < count; j++) {
var tmpByte = byteArray[position++];
var ccbyte1 = 0x7f & byteArray[position++];
var ccbyte2 = 0x7f & byteArray[position++];
var ccValid = (4 & tmpByte) !== 0;
var ccType = 3 & tmpByte;
if (ccbyte1 === 0 && ccbyte2 === 0) {
continue;
}
if (ccValid) {
if (ccType === 0 || ccType === 1) {
actualCCBytes[ccType].push(ccbyte1);
actualCCBytes[ccType].push(ccbyte2);
}
}
}
return actualCCBytes;
};
return TimelineController;
}();
function canReuseVttTextTrack(inUseTrack, manifestTrack) {
return inUseTrack && inUseTrack.label === manifestTrack.name && !(inUseTrack.textTrack1 || inUseTrack.textTrack2);
}
function intersection(x1, x2, y1, y2) {
return Math.min(x2, y2) - Math.max(x1, y1);
}
function newVTTCCs() {
return {
ccOffset: 0,
presentationOffset: 0,
0: {
start: 0,
prevCC: -1,
new: false
}
};
}
/***/ }),
/***/ "./src/crypt/aes-crypto.ts":
/*!*********************************!*\
!*** ./src/crypt/aes-crypto.ts ***!
\*********************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return AESCrypto; });
var AESCrypto = /*#__PURE__*/function () {
function AESCrypto(subtle, iv) {
this.subtle = void 0;
this.aesIV = void 0;
this.subtle = subtle;
this.aesIV = iv;
}
var _proto = AESCrypto.prototype;
_proto.decrypt = function decrypt(data, key) {
return this.subtle.decrypt({
name: 'AES-CBC',
iv: this.aesIV
}, key, data);
};
return AESCrypto;
}();
/***/ }),
/***/ "./src/crypt/aes-decryptor.ts":
/*!************************************!*\
!*** ./src/crypt/aes-decryptor.ts ***!
\************************************/
/*! exports provided: removePadding, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "removePadding", function() { return removePadding; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return AESDecryptor; });
/* harmony import */ var _utils_typed_array__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/typed-array */ "./src/utils/typed-array.ts");
// PKCS7
function removePadding(array) {
var outputBytes = array.byteLength;
var paddingBytes = outputBytes && new DataView(array.buffer).getUint8(outputBytes - 1);
if (paddingBytes) {
return Object(_utils_typed_array__WEBPACK_IMPORTED_MODULE_0__["sliceUint8"])(array, 0, outputBytes - paddingBytes);
}
return array;
}
var AESDecryptor = /*#__PURE__*/function () {
function AESDecryptor() {
this.rcon = [0x0, 0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];
this.subMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];
this.invSubMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];
this.sBox = new Uint32Array(256);
this.invSBox = new Uint32Array(256);
this.key = new Uint32Array(0);
this.ksRows = 0;
this.keySize = 0;
this.keySchedule = void 0;
this.invKeySchedule = void 0;
this.initTable();
} // Using view.getUint32() also swaps the byte order.
var _proto = AESDecryptor.prototype;
_proto.uint8ArrayToUint32Array_ = function uint8ArrayToUint32Array_(arrayBuffer) {
var view = new DataView(arrayBuffer);
var newArray = new Uint32Array(4);
for (var i = 0; i < 4; i++) {
newArray[i] = view.getUint32(i * 4);
}
return newArray;
};
_proto.initTable = function initTable() {
var sBox = this.sBox;
var invSBox = this.invSBox;
var subMix = this.subMix;
var subMix0 = subMix[0];
var subMix1 = subMix[1];
var subMix2 = subMix[2];
var subMix3 = subMix[3];
var invSubMix = this.invSubMix;
var invSubMix0 = invSubMix[0];
var invSubMix1 = invSubMix[1];
var invSubMix2 = invSubMix[2];
var invSubMix3 = invSubMix[3];
var d = new Uint32Array(256);
var x = 0;
var xi = 0;
var i = 0;
for (i = 0; i < 256; i++) {
if (i < 128) {
d[i] = i << 1;
} else {
d[i] = i << 1 ^ 0x11b;
}
}
for (i = 0; i < 256; i++) {
var sx = xi ^ xi << 1 ^ xi << 2 ^ xi << 3 ^ xi << 4;
sx = sx >>> 8 ^ sx & 0xff ^ 0x63;
sBox[x] = sx;
invSBox[sx] = x; // Compute multiplication
var x2 = d[x];
var x4 = d[x2];
var x8 = d[x4]; // Compute sub/invSub bytes, mix columns tables
var t = d[sx] * 0x101 ^ sx * 0x1010100;
subMix0[x] = t << 24 | t >>> 8;
subMix1[x] = t << 16 | t >>> 16;
subMix2[x] = t << 8 | t >>> 24;
subMix3[x] = t; // Compute inv sub bytes, inv mix columns tables
t = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100;
invSubMix0[sx] = t << 24 | t >>> 8;
invSubMix1[sx] = t << 16 | t >>> 16;
invSubMix2[sx] = t << 8 | t >>> 24;
invSubMix3[sx] = t; // Compute next counter
if (!x) {
x = xi = 1;
} else {
x = x2 ^ d[d[d[x8 ^ x2]]];
xi ^= d[d[xi]];
}
}
};
_proto.expandKey = function expandKey(keyBuffer) {
// convert keyBuffer to Uint32Array
var key = this.uint8ArrayToUint32Array_(keyBuffer);
var sameKey = true;
var offset = 0;
while (offset < key.length && sameKey) {
sameKey = key[offset] === this.key[offset];
offset++;
}
if (sameKey) {
return;
}
this.key = key;
var keySize = this.keySize = key.length;
if (keySize !== 4 && keySize !== 6 && keySize !== 8) {
throw new Error('Invalid aes key size=' + keySize);
}
var ksRows = this.ksRows = (keySize + 6 + 1) * 4;
var ksRow;
var invKsRow;
var keySchedule = this.keySchedule = new Uint32Array(ksRows);
var invKeySchedule = this.invKeySchedule = new Uint32Array(ksRows);
var sbox = this.sBox;
var rcon = this.rcon;
var invSubMix = this.invSubMix;
var invSubMix0 = invSubMix[0];
var invSubMix1 = invSubMix[1];
var invSubMix2 = invSubMix[2];
var invSubMix3 = invSubMix[3];
var prev;
var t;
for (ksRow = 0; ksRow < ksRows; ksRow++) {
if (ksRow < keySize) {
prev = keySchedule[ksRow] = key[ksRow];
continue;
}
t = prev;
if (ksRow % keySize === 0) {
// Rot word
t = t << 8 | t >>> 24; // Sub word
t = sbox[t >>> 24] << 24 | sbox[t >>> 16 & 0xff] << 16 | sbox[t >>> 8 & 0xff] << 8 | sbox[t & 0xff]; // Mix Rcon
t ^= rcon[ksRow / keySize | 0] << 24;
} else if (keySize > 6 && ksRow % keySize === 4) {
// Sub word
t = sbox[t >>> 24] << 24 | sbox[t >>> 16 & 0xff] << 16 | sbox[t >>> 8 & 0xff] << 8 | sbox[t & 0xff];
}
keySchedule[ksRow] = prev = (keySchedule[ksRow - keySize] ^ t) >>> 0;
}
for (invKsRow = 0; invKsRow < ksRows; invKsRow++) {
ksRow = ksRows - invKsRow;
if (invKsRow & 3) {
t = keySchedule[ksRow];
} else {
t = keySchedule[ksRow - 4];
}
if (invKsRow < 4 || ksRow <= 4) {
invKeySchedule[invKsRow] = t;
} else {
invKeySchedule[invKsRow] = invSubMix0[sbox[t >>> 24]] ^ invSubMix1[sbox[t >>> 16 & 0xff]] ^ invSubMix2[sbox[t >>> 8 & 0xff]] ^ invSubMix3[sbox[t & 0xff]];
}
invKeySchedule[invKsRow] = invKeySchedule[invKsRow] >>> 0;
}
} // Adding this as a method greatly improves performance.
;
_proto.networkToHostOrderSwap = function networkToHostOrderSwap(word) {
return word << 24 | (word & 0xff00) << 8 | (word & 0xff0000) >> 8 | word >>> 24;
};
_proto.decrypt = function decrypt(inputArrayBuffer, offset, aesIV) {
var nRounds = this.keySize + 6;
var invKeySchedule = this.invKeySchedule;
var invSBOX = this.invSBox;
var invSubMix = this.invSubMix;
var invSubMix0 = invSubMix[0];
var invSubMix1 = invSubMix[1];
var invSubMix2 = invSubMix[2];
var invSubMix3 = invSubMix[3];
var initVector = this.uint8ArrayToUint32Array_(aesIV);
var initVector0 = initVector[0];
var initVector1 = initVector[1];
var initVector2 = initVector[2];
var initVector3 = initVector[3];
var inputInt32 = new Int32Array(inputArrayBuffer);
var outputInt32 = new Int32Array(inputInt32.length);
var t0, t1, t2, t3;
var s0, s1, s2, s3;
var inputWords0, inputWords1, inputWords2, inputWords3;
var ksRow, i;
var swapWord = this.networkToHostOrderSwap;
while (offset < inputInt32.length) {
inputWords0 = swapWord(inputInt32[offset]);
inputWords1 = swapWord(inputInt32[offset + 1]);
inputWords2 = swapWord(inputInt32[offset + 2]);
inputWords3 = swapWord(inputInt32[offset + 3]);
s0 = inputWords0 ^ invKeySchedule[0];
s1 = inputWords3 ^ invKeySchedule[1];
s2 = inputWords2 ^ invKeySchedule[2];
s3 = inputWords1 ^ invKeySchedule[3];
ksRow = 4; // Iterate through the rounds of decryption
for (i = 1; i < nRounds; i++) {
t0 = invSubMix0[s0 >>> 24] ^ invSubMix1[s1 >> 16 & 0xff] ^ invSubMix2[s2 >> 8 & 0xff] ^ invSubMix3[s3 & 0xff] ^ invKeySchedule[ksRow];
t1 = invSubMix0[s1 >>> 24] ^ invSubMix1[s2 >> 16 & 0xff] ^ invSubMix2[s3 >> 8 & 0xff] ^ invSubMix3[s0 & 0xff] ^ invKeySchedule[ksRow + 1];
t2 = invSubMix0[s2 >>> 24] ^ invSubMix1[s3 >> 16 & 0xff] ^ invSubMix2[s0 >> 8 & 0xff] ^ invSubMix3[s1 & 0xff] ^ invKeySchedule[ksRow + 2];
t3 = invSubMix0[s3 >>> 24] ^ invSubMix1[s0 >> 16 & 0xff] ^ invSubMix2[s1 >> 8 & 0xff] ^ invSubMix3[s2 & 0xff] ^ invKeySchedule[ksRow + 3]; // Update state
s0 = t0;
s1 = t1;
s2 = t2;
s3 = t3;
ksRow = ksRow + 4;
} // Shift rows, sub bytes, add round key
t0 = invSBOX[s0 >>> 24] << 24 ^ invSBOX[s1 >> 16 & 0xff] << 16 ^ invSBOX[s2 >> 8 & 0xff] << 8 ^ invSBOX[s3 & 0xff] ^ invKeySchedule[ksRow];
t1 = invSBOX[s1 >>> 24] << 24 ^ invSBOX[s2 >> 16 & 0xff] << 16 ^ invSBOX[s3 >> 8 & 0xff] << 8 ^ invSBOX[s0 & 0xff] ^ invKeySchedule[ksRow + 1];
t2 = invSBOX[s2 >>> 24] << 24 ^ invSBOX[s3 >> 16 & 0xff] << 16 ^ invSBOX[s0 >> 8 & 0xff] << 8 ^ invSBOX[s1 & 0xff] ^ invKeySchedule[ksRow + 2];
t3 = invSBOX[s3 >>> 24] << 24 ^ invSBOX[s0 >> 16 & 0xff] << 16 ^ invSBOX[s1 >> 8 & 0xff] << 8 ^ invSBOX[s2 & 0xff] ^ invKeySchedule[ksRow + 3]; // Write
outputInt32[offset] = swapWord(t0 ^ initVector0);
outputInt32[offset + 1] = swapWord(t3 ^ initVector1);
outputInt32[offset + 2] = swapWord(t2 ^ initVector2);
outputInt32[offset + 3] = swapWord(t1 ^ initVector3); // reset initVector to last 4 unsigned int
initVector0 = inputWords0;
initVector1 = inputWords1;
initVector2 = inputWords2;
initVector3 = inputWords3;
offset = offset + 4;
}
return outputInt32.buffer;
};
return AESDecryptor;
}();
/***/ }),
/***/ "./src/crypt/decrypter.ts":
/*!********************************!*\
!*** ./src/crypt/decrypter.ts ***!
\********************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Decrypter; });
/* harmony import */ var _aes_crypto__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./aes-crypto */ "./src/crypt/aes-crypto.ts");
/* harmony import */ var _fast_aes_key__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./fast-aes-key */ "./src/crypt/fast-aes-key.ts");
/* harmony import */ var _aes_decryptor__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./aes-decryptor */ "./src/crypt/aes-decryptor.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/mp4-tools */ "./src/utils/mp4-tools.ts");
/* harmony import */ var _utils_typed_array__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/typed-array */ "./src/utils/typed-array.ts");
var CHUNK_SIZE = 16; // 16 bytes, 128 bits
var Decrypter = /*#__PURE__*/function () {
function Decrypter(observer, config, _temp) {
var _ref = _temp === void 0 ? {} : _temp,
_ref$removePKCS7Paddi = _ref.removePKCS7Padding,
removePKCS7Padding = _ref$removePKCS7Paddi === void 0 ? true : _ref$removePKCS7Paddi;
this.logEnabled = true;
this.observer = void 0;
this.config = void 0;
this.removePKCS7Padding = void 0;
this.subtle = null;
this.softwareDecrypter = null;
this.key = null;
this.fastAesKey = null;
this.remainderData = null;
this.currentIV = null;
this.currentResult = null;
this.observer = observer;
this.config = config;
this.removePKCS7Padding = removePKCS7Padding; // built in decryptor expects PKCS7 padding
if (removePKCS7Padding) {
try {
var browserCrypto = self.crypto;
if (browserCrypto) {
this.subtle = browserCrypto.subtle || browserCrypto.webkitSubtle;
}
} catch (e) {
/* no-op */
}
}
if (this.subtle === null) {
this.config.enableSoftwareAES = true;
}
}
var _proto = Decrypter.prototype;
_proto.destroy = function destroy() {
// @ts-ignore
this.observer = null;
};
_proto.isSync = function isSync() {
return this.config.enableSoftwareAES;
};
_proto.flush = function flush() {
var currentResult = this.currentResult;
if (!currentResult) {
this.reset();
return;
}
var data = new Uint8Array(currentResult);
this.reset();
if (this.removePKCS7Padding) {
return Object(_aes_decryptor__WEBPACK_IMPORTED_MODULE_2__["removePadding"])(data);
}
return data;
};
_proto.reset = function reset() {
this.currentResult = null;
this.currentIV = null;
this.remainderData = null;
if (this.softwareDecrypter) {
this.softwareDecrypter = null;
}
};
_proto.decrypt = function decrypt(data, key, iv, callback) {
if (this.config.enableSoftwareAES) {
this.softwareDecrypt(new Uint8Array(data), key, iv);
var decryptResult = this.flush();
if (decryptResult) {
callback(decryptResult.buffer);
}
} else {
this.webCryptoDecrypt(new Uint8Array(data), key, iv).then(callback);
}
};
_proto.softwareDecrypt = function softwareDecrypt(data, key, iv) {
var currentIV = this.currentIV,
currentResult = this.currentResult,
remainderData = this.remainderData;
this.logOnce('JS AES decrypt'); // The output is staggered during progressive parsing - the current result is cached, and emitted on the next call
// This is done in order to strip PKCS7 padding, which is found at the end of each segment. We only know we've reached
// the end on flush(), but by that time we have already received all bytes for the segment.
// Progressive decryption does not work with WebCrypto
if (remainderData) {
data = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_4__["appendUint8Array"])(remainderData, data);
this.remainderData = null;
} // Byte length must be a multiple of 16 (AES-128 = 128 bit blocks = 16 bytes)
var currentChunk = this.getValidChunk(data);
if (!currentChunk.length) {
return null;
}
if (currentIV) {
iv = currentIV;
}
var softwareDecrypter = this.softwareDecrypter;
if (!softwareDecrypter) {
softwareDecrypter = this.softwareDecrypter = new _aes_decryptor__WEBPACK_IMPORTED_MODULE_2__["default"]();
}
softwareDecrypter.expandKey(key);
var result = currentResult;
this.currentResult = softwareDecrypter.decrypt(currentChunk.buffer, 0, iv);
this.currentIV = Object(_utils_typed_array__WEBPACK_IMPORTED_MODULE_5__["sliceUint8"])(currentChunk, -16).buffer;
if (!result) {
return null;
}
return result;
};
_proto.webCryptoDecrypt = function webCryptoDecrypt(data, key, iv) {
var _this = this;
var subtle = this.subtle;
if (this.key !== key || !this.fastAesKey) {
this.key = key;
this.fastAesKey = new _fast_aes_key__WEBPACK_IMPORTED_MODULE_1__["default"](subtle, key);
}
return this.fastAesKey.expandKey().then(function (aesKey) {
// decrypt using web crypto
if (!subtle) {
return Promise.reject(new Error('web crypto not initialized'));
}
var crypto = new _aes_crypto__WEBPACK_IMPORTED_MODULE_0__["default"](subtle, iv);
return crypto.decrypt(data.buffer, aesKey);
}).catch(function (err) {
return _this.onWebCryptoError(err, data, key, iv);
});
};
_proto.onWebCryptoError = function onWebCryptoError(err, data, key, iv) {
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn('[decrypter.ts]: WebCrypto Error, disable WebCrypto API:', err);
this.config.enableSoftwareAES = true;
this.logEnabled = true;
return this.softwareDecrypt(data, key, iv);
};
_proto.getValidChunk = function getValidChunk(data) {
var currentChunk = data;
var splitPoint = data.length - data.length % CHUNK_SIZE;
if (splitPoint !== data.length) {
currentChunk = Object(_utils_typed_array__WEBPACK_IMPORTED_MODULE_5__["sliceUint8"])(data, 0, splitPoint);
this.remainderData = Object(_utils_typed_array__WEBPACK_IMPORTED_MODULE_5__["sliceUint8"])(data, splitPoint);
}
return currentChunk;
};
_proto.logOnce = function logOnce(msg) {
if (!this.logEnabled) {
return;
}
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].log("[decrypter.ts]: " + msg);
this.logEnabled = false;
};
return Decrypter;
}();
/***/ }),
/***/ "./src/crypt/fast-aes-key.ts":
/*!***********************************!*\
!*** ./src/crypt/fast-aes-key.ts ***!
\***********************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return FastAESKey; });
var FastAESKey = /*#__PURE__*/function () {
function FastAESKey(subtle, key) {
this.subtle = void 0;
this.key = void 0;
this.subtle = subtle;
this.key = key;
}
var _proto = FastAESKey.prototype;
_proto.expandKey = function expandKey() {
return this.subtle.importKey('raw', this.key, {
name: 'AES-CBC'
}, false, ['encrypt', 'decrypt']);
};
return FastAESKey;
}();
/***/ }),
/***/ "./src/demux/aacdemuxer.ts":
/*!*********************************!*\
!*** ./src/demux/aacdemuxer.ts ***!
\*********************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _base_audio_demuxer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base-audio-demuxer */ "./src/demux/base-audio-demuxer.ts");
/* harmony import */ var _adts__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./adts */ "./src/demux/adts.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/* harmony import */ var _demux_id3__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../demux/id3 */ "./src/demux/id3.ts");
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
/**
* AAC demuxer
*/
var AACDemuxer = /*#__PURE__*/function (_BaseAudioDemuxer) {
_inheritsLoose(AACDemuxer, _BaseAudioDemuxer);
function AACDemuxer(observer, config) {
var _this;
_this = _BaseAudioDemuxer.call(this) || this;
_this.observer = void 0;
_this.config = void 0;
_this.observer = observer;
_this.config = config;
return _this;
}
var _proto = AACDemuxer.prototype;
_proto.resetInitSegment = function resetInitSegment(audioCodec, videoCodec, duration) {
_BaseAudioDemuxer.prototype.resetInitSegment.call(this, audioCodec, videoCodec, duration);
this._audioTrack = {
container: 'audio/adts',
type: 'audio',
id: 0,
pid: -1,
sequenceNumber: 0,
isAAC: true,
samples: [],
manifestCodec: audioCodec,
duration: duration,
inputTimeScale: 90000,
dropped: 0
};
} // Source for probe info - https://wiki.multimedia.cx/index.php?title=ADTS
;
AACDemuxer.probe = function probe(data) {
if (!data) {
return false;
} // Check for the ADTS sync word
// Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1
// Layer bits (position 14 and 15) in header should be always 0 for ADTS
// More info https://wiki.multimedia.cx/index.php?title=ADTS
var id3Data = _demux_id3__WEBPACK_IMPORTED_MODULE_3__["getID3Data"](data, 0) || [];
var offset = id3Data.length;
for (var length = data.length; offset < length; offset++) {
if (_adts__WEBPACK_IMPORTED_MODULE_1__["probe"](data, offset)) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('ADTS sync word found !');
return true;
}
}
return false;
};
_proto.canParse = function canParse(data, offset) {
return _adts__WEBPACK_IMPORTED_MODULE_1__["canParse"](data, offset);
};
_proto.appendFrame = function appendFrame(track, data, offset) {
_adts__WEBPACK_IMPORTED_MODULE_1__["initTrackConfig"](track, this.observer, data, offset, track.manifestCodec);
return _adts__WEBPACK_IMPORTED_MODULE_1__["appendFrame"](track, data, offset, this.initPTS, this.frameIndex);
};
return AACDemuxer;
}(_base_audio_demuxer__WEBPACK_IMPORTED_MODULE_0__["default"]);
AACDemuxer.minProbeByteLength = 9;
/* harmony default export */ __webpack_exports__["default"] = (AACDemuxer);
/***/ }),
/***/ "./src/demux/adts.ts":
/*!***************************!*\
!*** ./src/demux/adts.ts ***!
\***************************/
/*! exports provided: getAudioConfig, isHeaderPattern, getHeaderLength, getFullFrameLength, canGetFrameLength, isHeader, canParse, probe, initTrackConfig, getFrameDuration, parseFrameHeader, appendFrame */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getAudioConfig", function() { return getAudioConfig; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isHeaderPattern", function() { return isHeaderPattern; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getHeaderLength", function() { return getHeaderLength; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getFullFrameLength", function() { return getFullFrameLength; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "canGetFrameLength", function() { return canGetFrameLength; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isHeader", function() { return isHeader; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "canParse", function() { return canParse; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "probe", function() { return probe; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initTrackConfig", function() { return initTrackConfig; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getFrameDuration", function() { return getFrameDuration; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseFrameHeader", function() { return parseFrameHeader; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "appendFrame", function() { return appendFrame; });
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/**
* ADTS parser helper
* @link https://wiki.multimedia.cx/index.php?title=ADTS
*/
function getAudioConfig(observer, data, offset, audioCodec) {
var adtsObjectType;
var adtsExtensionSampleingIndex;
var adtsChanelConfig;
var config;
var userAgent = navigator.userAgent.toLowerCase();
var manifestCodec = audioCodec;
var adtsSampleingRates = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350]; // byte 2
adtsObjectType = ((data[offset + 2] & 0xc0) >>> 6) + 1;
var adtsSampleingIndex = (data[offset + 2] & 0x3c) >>> 2;
if (adtsSampleingIndex > adtsSampleingRates.length - 1) {
observer.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].MEDIA_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].FRAG_PARSING_ERROR,
fatal: true,
reason: "invalid ADTS sampling index:" + adtsSampleingIndex
});
return;
}
adtsChanelConfig = (data[offset + 2] & 0x01) << 2; // byte 3
adtsChanelConfig |= (data[offset + 3] & 0xc0) >>> 6;
_utils_logger__WEBPACK_IMPORTED_MODULE_0__["logger"].log("manifest codec:" + audioCodec + ",ADTS data:type:" + adtsObjectType + ",sampleingIndex:" + adtsSampleingIndex + "[" + adtsSampleingRates[adtsSampleingIndex] + "Hz],channelConfig:" + adtsChanelConfig); // firefox: freq less than 24kHz = AAC SBR (HE-AAC)
if (/firefox/i.test(userAgent)) {
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/Vivaldi/Opera ...)
always force audio type to be HE-AAC SBR, as some browsers do not support audio codec switch properly (like Chrome ...)
*/
adtsObjectType = 5;
config = new Array(4); // if (manifest codec is HE-AAC or HE-AACv2) OR (manifest codec not specified AND frequency less than 24kHz)
if (audioCodec && (audioCodec.indexOf('mp4a.40.29') !== -1 || audioCodec.indexOf('mp4a.40.5') !== -1) || !audioCodec && 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 || /vivaldi/i.test(userAgent)) || !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,
manifestCodec: manifestCodec
};
}
function isHeaderPattern(data, offset) {
return data[offset] === 0xff && (data[offset + 1] & 0xf6) === 0xf0;
}
function getHeaderLength(data, offset) {
return data[offset + 1] & 0x01 ? 7 : 9;
}
function getFullFrameLength(data, offset) {
return (data[offset + 3] & 0x03) << 11 | data[offset + 4] << 3 | (data[offset + 5] & 0xe0) >>> 5;
}
function canGetFrameLength(data, offset) {
return offset + 5 < data.length;
}
function isHeader(data, offset) {
// Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1
// Layer bits (position 14 and 15) in header should be always 0 for ADTS
// More info https://wiki.multimedia.cx/index.php?title=ADTS
return offset + 1 < data.length && isHeaderPattern(data, offset);
}
function canParse(data, offset) {
return canGetFrameLength(data, offset) && isHeaderPattern(data, offset) && getFullFrameLength(data, offset) < data.length - offset;
}
function probe(data, offset) {
// same as isHeader but we also check that ADTS frame follows last ADTS frame
// or end of data is reached
if (isHeader(data, offset)) {
// ADTS header Length
var headerLength = getHeaderLength(data, offset);
if (offset + headerLength >= data.length) {
return false;
} // ADTS frame Length
var frameLength = getFullFrameLength(data, offset);
if (frameLength <= headerLength) {
return false;
}
var newOffset = offset + frameLength;
return newOffset === data.length || isHeader(data, newOffset);
}
return false;
}
function initTrackConfig(track, observer, data, offset, audioCodec) {
if (!track.samplerate) {
var config = getAudioConfig(observer, data, offset, audioCodec);
if (!config) {
return;
}
track.config = config.config;
track.samplerate = config.samplerate;
track.channelCount = config.channelCount;
track.codec = config.codec;
track.manifestCodec = config.manifestCodec;
_utils_logger__WEBPACK_IMPORTED_MODULE_0__["logger"].log("parsed codec:" + track.codec + ",rate:" + config.samplerate + ",nb channel:" + config.channelCount);
}
}
function getFrameDuration(samplerate) {
return 1024 * 90000 / samplerate;
}
function parseFrameHeader(data, offset, pts, frameIndex, frameDuration) {
var length = data.length; // The protection skip bit tells us if we have 2 bytes of CRC data at the end of the ADTS header
var headerLength = getHeaderLength(data, offset); // retrieve frame size
var frameLength = getFullFrameLength(data, offset);
frameLength -= headerLength;
if (frameLength > 0 && offset + headerLength + frameLength <= length) {
var stamp = pts + frameIndex * frameDuration; // logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}/${(stamp/90).toFixed(0)}`);
return {
headerLength: headerLength,
frameLength: frameLength,
stamp: stamp
};
}
}
function appendFrame(track, data, offset, pts, frameIndex) {
var frameDuration = getFrameDuration(track.samplerate);
var header = parseFrameHeader(data, offset, pts, frameIndex, frameDuration);
if (header) {
var stamp = header.stamp;
var headerLength = header.headerLength;
var frameLength = header.frameLength; // logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}/${(stamp/90).toFixed(0)}`);
var aacSample = {
unit: data.subarray(offset + headerLength, offset + headerLength + frameLength),
pts: stamp,
dts: stamp
};
track.samples.push(aacSample);
return {
sample: aacSample,
length: frameLength + headerLength
};
}
}
/***/ }),
/***/ "./src/demux/base-audio-demuxer.ts":
/*!*****************************************!*\
!*** ./src/demux/base-audio-demuxer.ts ***!
\*****************************************/
/*! exports provided: initPTSFn, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initPTSFn", function() { return initPTSFn; });
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var _demux_id3__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../demux/id3 */ "./src/demux/id3.ts");
/* harmony import */ var _dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./dummy-demuxed-track */ "./src/demux/dummy-demuxed-track.ts");
/* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/mp4-tools */ "./src/utils/mp4-tools.ts");
/* harmony import */ var _utils_typed_array__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/typed-array */ "./src/utils/typed-array.ts");
var BaseAudioDemuxer = /*#__PURE__*/function () {
function BaseAudioDemuxer() {
this._audioTrack = void 0;
this._id3Track = void 0;
this.frameIndex = 0;
this.cachedData = null;
this.initPTS = null;
}
var _proto = BaseAudioDemuxer.prototype;
_proto.resetInitSegment = function resetInitSegment(audioCodec, videoCodec, duration) {
this._id3Track = {
type: 'id3',
id: 0,
pid: -1,
inputTimeScale: 90000,
sequenceNumber: 0,
samples: [],
dropped: 0
};
};
_proto.resetTimeStamp = function resetTimeStamp() {};
_proto.resetContiguity = function resetContiguity() {};
_proto.canParse = function canParse(data, offset) {
return false;
};
_proto.appendFrame = function appendFrame(track, data, offset) {} // feed incoming data to the front of the parsing pipeline
;
_proto.demux = function demux(data, timeOffset) {
if (this.cachedData) {
data = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_3__["appendUint8Array"])(this.cachedData, data);
this.cachedData = null;
}
var id3Data = _demux_id3__WEBPACK_IMPORTED_MODULE_1__["getID3Data"](data, 0);
var offset = id3Data ? id3Data.length : 0;
var lastDataIndex;
var pts;
var track = this._audioTrack;
var id3Track = this._id3Track;
var timestamp = id3Data ? _demux_id3__WEBPACK_IMPORTED_MODULE_1__["getTimeStamp"](id3Data) : undefined;
var length = data.length;
if (this.frameIndex === 0 || this.initPTS === null) {
this.initPTS = initPTSFn(timestamp, timeOffset);
} // more expressive than alternative: id3Data?.length
if (id3Data && id3Data.length > 0) {
id3Track.samples.push({
pts: this.initPTS,
dts: this.initPTS,
data: id3Data
});
}
pts = this.initPTS;
while (offset < length) {
if (this.canParse(data, offset)) {
var frame = this.appendFrame(track, data, offset);
if (frame) {
this.frameIndex++;
pts = frame.sample.pts;
offset += frame.length;
lastDataIndex = offset;
} else {
offset = length;
}
} else if (_demux_id3__WEBPACK_IMPORTED_MODULE_1__["canParse"](data, offset)) {
// after a ID3.canParse, a call to ID3.getID3Data *should* always returns some data
id3Data = _demux_id3__WEBPACK_IMPORTED_MODULE_1__["getID3Data"](data, offset);
id3Track.samples.push({
pts: pts,
dts: pts,
data: id3Data
});
offset += id3Data.length;
lastDataIndex = offset;
} else {
offset++;
}
if (offset === length && lastDataIndex !== length) {
var partialData = Object(_utils_typed_array__WEBPACK_IMPORTED_MODULE_4__["sliceUint8"])(data, lastDataIndex);
if (this.cachedData) {
this.cachedData = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_3__["appendUint8Array"])(this.cachedData, partialData);
} else {
this.cachedData = partialData;
}
}
}
return {
audioTrack: track,
avcTrack: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_2__["dummyTrack"])(),
id3Track: id3Track,
textTrack: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_2__["dummyTrack"])()
};
};
_proto.demuxSampleAes = function demuxSampleAes(data, keyData, timeOffset) {
return Promise.reject(new Error("[" + this + "] This demuxer does not support Sample-AES decryption"));
};
_proto.flush = function flush(timeOffset) {
// Parse cache in case of remaining frames.
if (this.cachedData) {
this.demux(this.cachedData, 0);
}
this.frameIndex = 0;
this.cachedData = null;
return {
audioTrack: this._audioTrack,
avcTrack: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_2__["dummyTrack"])(),
id3Track: this._id3Track,
textTrack: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_2__["dummyTrack"])()
};
};
_proto.destroy = function destroy() {};
return BaseAudioDemuxer;
}();
/**
* Initialize PTS
* <p>
* use timestamp unless it is undefined, NaN or Infinity
* </p>
*/
var initPTSFn = function initPTSFn(timestamp, timeOffset) {
return Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(timestamp) ? timestamp * 90 : timeOffset * 90000;
};
/* harmony default export */ __webpack_exports__["default"] = (BaseAudioDemuxer);
/***/ }),
/***/ "./src/demux/chunk-cache.ts":
/*!**********************************!*\
!*** ./src/demux/chunk-cache.ts ***!
\**********************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return ChunkCache; });
var ChunkCache = /*#__PURE__*/function () {
function ChunkCache() {
this.chunks = [];
this.dataLength = 0;
}
var _proto = ChunkCache.prototype;
_proto.push = function push(chunk) {
this.chunks.push(chunk);
this.dataLength += chunk.length;
};
_proto.flush = function flush() {
var chunks = this.chunks,
dataLength = this.dataLength;
var result;
if (!chunks.length) {
return new Uint8Array(0);
} else if (chunks.length === 1) {
result = chunks[0];
} else {
result = concatUint8Arrays(chunks, dataLength);
}
this.reset();
return result;
};
_proto.reset = function reset() {
this.chunks.length = 0;
this.dataLength = 0;
};
return ChunkCache;
}();
function concatUint8Arrays(chunks, dataLength) {
var result = new Uint8Array(dataLength);
var offset = 0;
for (var i = 0; i < chunks.length; i++) {
var chunk = chunks[i];
result.set(chunk, offset);
offset += chunk.length;
}
return result;
}
/***/ }),
/***/ "./src/demux/dummy-demuxed-track.ts":
/*!******************************************!*\
!*** ./src/demux/dummy-demuxed-track.ts ***!
\******************************************/
/*! exports provided: dummyTrack */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dummyTrack", function() { return dummyTrack; });
function dummyTrack() {
return {
type: '',
id: -1,
pid: -1,
inputTimeScale: 90000,
sequenceNumber: -1,
samples: [],
dropped: 0
};
}
/***/ }),
/***/ "./src/demux/exp-golomb.ts":
/*!*********************************!*\
!*** ./src/demux/exp-golomb.ts ***!
\*********************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/**
* Parser for exponential Golomb codes, a variable-bitwidth number encoding scheme used by h264.
*/
var ExpGolomb = /*#__PURE__*/function () {
function ExpGolomb(data) {
this.data = void 0;
this.bytesAvailable = void 0;
this.word = void 0;
this.bitsAvailable = void 0;
this.data = data; // the number of bytes left to examine in this.data
this.bytesAvailable = data.byteLength; // the current word being examined
this.word = 0; // :uint
// the number of bits left to examine in the current word
this.bitsAvailable = 0; // :uint
} // ():void
var _proto = ExpGolomb.prototype;
_proto.loadWord = function loadWord() {
var data = this.data;
var bytesAvailable = this.bytesAvailable;
var position = data.byteLength - bytesAvailable;
var workingBytes = new Uint8Array(4);
var availableBytes = Math.min(4, bytesAvailable);
if (availableBytes === 0) {
throw new Error('no bytes available');
}
workingBytes.set(data.subarray(position, position + availableBytes));
this.word = new DataView(workingBytes.buffer).getUint32(0); // track the amount of this.data that has been processed
this.bitsAvailable = availableBytes * 8;
this.bytesAvailable -= availableBytes;
} // (count:int):void
;
_proto.skipBits = function skipBits(count) {
var skipBytes; // :int
if (this.bitsAvailable > count) {
this.word <<= count;
this.bitsAvailable -= count;
} else {
count -= this.bitsAvailable;
skipBytes = count >> 3;
count -= skipBytes >> 3;
this.bytesAvailable -= skipBytes;
this.loadWord();
this.word <<= count;
this.bitsAvailable -= count;
}
} // (size:int):uint
;
_proto.readBits = function readBits(size) {
var bits = Math.min(this.bitsAvailable, size); // :uint
var valu = this.word >>> 32 - bits; // :uint
if (size > 32) {
_utils_logger__WEBPACK_IMPORTED_MODULE_0__["logger"].error('Cannot read more than 32 bits at a time');
}
this.bitsAvailable -= bits;
if (this.bitsAvailable > 0) {
this.word <<= bits;
} else if (this.bytesAvailable > 0) {
this.loadWord();
}
bits = size - bits;
if (bits > 0 && this.bitsAvailable) {
return valu << bits | this.readBits(bits);
} else {
return valu;
}
} // ():uint
;
_proto.skipLZ = function skipLZ() {
var leadingZeroCount; // :uint
for (leadingZeroCount = 0; leadingZeroCount < this.bitsAvailable; ++leadingZeroCount) {
if ((this.word & 0x80000000 >>> leadingZeroCount) !== 0) {
// the first bit of working word is 1
this.word <<= leadingZeroCount;
this.bitsAvailable -= leadingZeroCount;
return leadingZeroCount;
}
} // we exhausted word and still have not found a 1
this.loadWord();
return leadingZeroCount + this.skipLZ();
} // ():void
;
_proto.skipUEG = function skipUEG() {
this.skipBits(1 + this.skipLZ());
} // ():void
;
_proto.skipEG = function skipEG() {
this.skipBits(1 + this.skipLZ());
} // ():uint
;
_proto.readUEG = function readUEG() {
var clz = this.skipLZ(); // :uint
return this.readBits(clz + 1) - 1;
} // ():int
;
_proto.readEG = function readEG() {
var valu = this.readUEG(); // :int
if (0x01 & valu) {
// the number is odd if the low order bit is set
return 1 + valu >>> 1; // add 1 to make it even, and divide by 2
} else {
return -1 * (valu >>> 1); // divide by two then make it negative
}
} // Some convenience functions
// :Boolean
;
_proto.readBoolean = function readBoolean() {
return this.readBits(1) === 1;
} // ():int
;
_proto.readUByte = function readUByte() {
return this.readBits(8);
} // ():int
;
_proto.readUShort = function readUShort() {
return this.readBits(16);
} // ():int
;
_proto.readUInt = function readUInt() {
return this.readBits(32);
}
/**
* Advance the ExpGolomb decoder past a scaling list. The scaling
* list is optionally transmitted as part of a sequence parameter
* set and is not relevant to transmuxing.
* @param count the number of entries in this scaling list
* @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1
*/
;
_proto.skipScalingList = function skipScalingList(count) {
var lastScale = 8;
var nextScale = 8;
var deltaScale;
for (var j = 0; j < count; j++) {
if (nextScale !== 0) {
deltaScale = this.readEG();
nextScale = (lastScale + deltaScale + 256) % 256;
}
lastScale = nextScale === 0 ? lastScale : nextScale;
}
}
/**
* Read a sequence parameter set and return some interesting video
* properties. A sequence parameter set is the H264 metadata that
* describes the properties of upcoming video frames.
* @param data {Uint8Array} the bytes of a sequence parameter set
* @return {object} an object with configuration parsed from the
* sequence parameter set, including the dimensions of the
* associated video frames.
*/
;
_proto.readSPS = function readSPS() {
var frameCropLeftOffset = 0;
var frameCropRightOffset = 0;
var frameCropTopOffset = 0;
var frameCropBottomOffset = 0;
var numRefFramesInPicOrderCntCycle;
var scalingListCount;
var i;
var readUByte = this.readUByte.bind(this);
var readBits = this.readBits.bind(this);
var readUEG = this.readUEG.bind(this);
var readBoolean = this.readBoolean.bind(this);
var skipBits = this.skipBits.bind(this);
var skipEG = this.skipEG.bind(this);
var skipUEG = this.skipUEG.bind(this);
var skipScalingList = this.skipScalingList.bind(this);
readUByte();
var profileIdc = readUByte(); // profile_idc
readBits(5); // profileCompat constraint_set[0-4]_flag, u(5)
skipBits(3); // reserved_zero_3bits u(3),
readUByte(); // level_idc u(8)
skipUEG(); // seq_parameter_set_id
// some profiles have more optional data we don't need
if (profileIdc === 100 || profileIdc === 110 || profileIdc === 122 || profileIdc === 244 || profileIdc === 44 || profileIdc === 83 || profileIdc === 86 || profileIdc === 118 || profileIdc === 128) {
var chromaFormatIdc = readUEG();
if (chromaFormatIdc === 3) {
skipBits(1);
} // separate_colour_plane_flag
skipUEG(); // bit_depth_luma_minus8
skipUEG(); // bit_depth_chroma_minus8
skipBits(1); // qpprime_y_zero_transform_bypass_flag
if (readBoolean()) {
// seq_scaling_matrix_present_flag
scalingListCount = chromaFormatIdc !== 3 ? 8 : 12;
for (i = 0; i < scalingListCount; i++) {
if (readBoolean()) {
// seq_scaling_list_present_flag[ i ]
if (i < 6) {
skipScalingList(16);
} else {
skipScalingList(64);
}
}
}
}
}
skipUEG(); // log2_max_frame_num_minus4
var picOrderCntType = readUEG();
if (picOrderCntType === 0) {
readUEG(); // log2_max_pic_order_cnt_lsb_minus4
} else if (picOrderCntType === 1) {
skipBits(1); // delta_pic_order_always_zero_flag
skipEG(); // offset_for_non_ref_pic
skipEG(); // offset_for_top_to_bottom_field
numRefFramesInPicOrderCntCycle = readUEG();
for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) {
skipEG();
} // offset_for_ref_frame[ i ]
}
skipUEG(); // max_num_ref_frames
skipBits(1); // gaps_in_frame_num_value_allowed_flag
var picWidthInMbsMinus1 = readUEG();
var picHeightInMapUnitsMinus1 = readUEG();
var frameMbsOnlyFlag = readBits(1);
if (frameMbsOnlyFlag === 0) {
skipBits(1);
} // mb_adaptive_frame_field_flag
skipBits(1); // direct_8x8_inference_flag
if (readBoolean()) {
// frame_cropping_flag
frameCropLeftOffset = readUEG();
frameCropRightOffset = readUEG();
frameCropTopOffset = readUEG();
frameCropBottomOffset = readUEG();
}
var pixelRatio = [1, 1];
if (readBoolean()) {
// vui_parameters_present_flag
if (readBoolean()) {
// aspect_ratio_info_present_flag
var aspectRatioIdc = readUByte();
switch (aspectRatioIdc) {
case 1:
pixelRatio = [1, 1];
break;
case 2:
pixelRatio = [12, 11];
break;
case 3:
pixelRatio = [10, 11];
break;
case 4:
pixelRatio = [16, 11];
break;
case 5:
pixelRatio = [40, 33];
break;
case 6:
pixelRatio = [24, 11];
break;
case 7:
pixelRatio = [20, 11];
break;
case 8:
pixelRatio = [32, 11];
break;
case 9:
pixelRatio = [80, 33];
break;
case 10:
pixelRatio = [18, 11];
break;
case 11:
pixelRatio = [15, 11];
break;
case 12:
pixelRatio = [64, 33];
break;
case 13:
pixelRatio = [160, 99];
break;
case 14:
pixelRatio = [4, 3];
break;
case 15:
pixelRatio = [3, 2];
break;
case 16:
pixelRatio = [2, 1];
break;
case 255:
{
pixelRatio = [readUByte() << 8 | readUByte(), readUByte() << 8 | readUByte()];
break;
}
}
}
}
return {
width: Math.ceil((picWidthInMbsMinus1 + 1) * 16 - frameCropLeftOffset * 2 - frameCropRightOffset * 2),
height: (2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16 - (frameMbsOnlyFlag ? 2 : 4) * (frameCropTopOffset + frameCropBottomOffset),
pixelRatio: pixelRatio
};
};
_proto.readSliceType = function readSliceType() {
// skip NALu type
this.readUByte(); // discard first_mb_in_slice
this.readUEG(); // return slice_type
return this.readUEG();
};
return ExpGolomb;
}();
/* harmony default export */ __webpack_exports__["default"] = (ExpGolomb);
/***/ }),
/***/ "./src/demux/id3.ts":
/*!**************************!*\
!*** ./src/demux/id3.ts ***!
\**************************/
/*! exports provided: isHeader, isFooter, getID3Data, canParse, getTimeStamp, isTimeStampFrame, getID3Frames, decodeFrame, utf8ArrayToStr, testables */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isHeader", function() { return isHeader; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isFooter", function() { return isFooter; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getID3Data", function() { return getID3Data; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "canParse", function() { return canParse; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getTimeStamp", function() { return getTimeStamp; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isTimeStampFrame", function() { return isTimeStampFrame; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getID3Frames", function() { return getID3Frames; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "decodeFrame", function() { return decodeFrame; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "utf8ArrayToStr", function() { return utf8ArrayToStr; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "testables", function() { return testables; });
// breaking up those two types in order to clarify what is happening in the decoding path.
/**
* Returns true if an ID3 header can be found at offset in data
* @param {Uint8Array} data - The data to search in
* @param {number} offset - The offset at which to start searching
* @return {boolean} - True if an ID3 header is found
*/
var isHeader = function isHeader(data, offset) {
/*
* http://id3.org/id3v2.3.0
* [0] = 'I'
* [1] = 'D'
* [2] = '3'
* [3,4] = {Version}
* [5] = {Flags}
* [6-9] = {ID3 Size}
*
* An ID3v2 tag can be detected with the following pattern:
* $49 44 33 yy yy xx zz zz zz zz
* Where yy is less than $FF, xx is the 'flags' byte and zz is less than $80
*/
if (offset + 10 <= data.length) {
// look for 'ID3' identifier
if (data[offset] === 0x49 && data[offset + 1] === 0x44 && data[offset + 2] === 0x33) {
// check version is within range
if (data[offset + 3] < 0xff && data[offset + 4] < 0xff) {
// check size is within range
if (data[offset + 6] < 0x80 && data[offset + 7] < 0x80 && data[offset + 8] < 0x80 && data[offset + 9] < 0x80) {
return true;
}
}
}
}
return false;
};
/**
* Returns true if an ID3 footer can be found at offset in data
* @param {Uint8Array} data - The data to search in
* @param {number} offset - The offset at which to start searching
* @return {boolean} - True if an ID3 footer is found
*/
var isFooter = function isFooter(data, offset) {
/*
* The footer is a copy of the header, but with a different identifier
*/
if (offset + 10 <= data.length) {
// look for '3DI' identifier
if (data[offset] === 0x33 && data[offset + 1] === 0x44 && data[offset + 2] === 0x49) {
// check version is within range
if (data[offset + 3] < 0xff && data[offset + 4] < 0xff) {
// check size is within range
if (data[offset + 6] < 0x80 && data[offset + 7] < 0x80 && data[offset + 8] < 0x80 && data[offset + 9] < 0x80) {
return true;
}
}
}
}
return false;
};
/**
* Returns any adjacent ID3 tags found in data starting at offset, as one block of data
* @param {Uint8Array} data - The data to search in
* @param {number} offset - The offset at which to start searching
* @return {Uint8Array | undefined} - The block of data containing any ID3 tags found
* or *undefined* if no header is found at the starting offset
*/
var getID3Data = function getID3Data(data, offset) {
var front = offset;
var length = 0;
while (isHeader(data, offset)) {
// ID3 header is 10 bytes
length += 10;
var size = readSize(data, offset + 6);
length += size;
if (isFooter(data, offset + 10)) {
// ID3 footer is 10 bytes
length += 10;
}
offset += length;
}
if (length > 0) {
return data.subarray(front, front + length);
}
return undefined;
};
var readSize = function readSize(data, offset) {
var size = 0;
size = (data[offset] & 0x7f) << 21;
size |= (data[offset + 1] & 0x7f) << 14;
size |= (data[offset + 2] & 0x7f) << 7;
size |= data[offset + 3] & 0x7f;
return size;
};
var canParse = function canParse(data, offset) {
return isHeader(data, offset) && readSize(data, offset + 6) + 10 <= data.length - offset;
};
/**
* Searches for the Elementary Stream timestamp found in the ID3 data chunk
* @param {Uint8Array} data - Block of data containing one or more ID3 tags
* @return {number | undefined} - The timestamp
*/
var getTimeStamp = function getTimeStamp(data) {
var frames = getID3Frames(data);
for (var i = 0; i < frames.length; i++) {
var frame = frames[i];
if (isTimeStampFrame(frame)) {
return readTimeStamp(frame);
}
}
return undefined;
};
/**
* Returns true if the ID3 frame is an Elementary Stream timestamp frame
* @param {ID3 frame} frame
*/
var isTimeStampFrame = function isTimeStampFrame(frame) {
return frame && frame.key === 'PRIV' && frame.info === 'com.apple.streaming.transportStreamTimestamp';
};
var getFrameData = function getFrameData(data) {
/*
Frame ID $xx xx xx xx (four characters)
Size $xx xx xx xx
Flags $xx xx
*/
var type = String.fromCharCode(data[0], data[1], data[2], data[3]);
var size = readSize(data, 4); // skip frame id, size, and flags
var offset = 10;
return {
type: type,
size: size,
data: data.subarray(offset, offset + size)
};
};
/**
* Returns an array of ID3 frames found in all the ID3 tags in the id3Data
* @param {Uint8Array} id3Data - The ID3 data containing one or more ID3 tags
* @return {ID3.Frame[]} - Array of ID3 frame objects
*/
var getID3Frames = function getID3Frames(id3Data) {
var offset = 0;
var frames = [];
while (isHeader(id3Data, offset)) {
var size = readSize(id3Data, offset + 6); // skip past ID3 header
offset += 10;
var end = offset + size; // loop through frames in the ID3 tag
while (offset + 8 < end) {
var frameData = getFrameData(id3Data.subarray(offset));
var frame = decodeFrame(frameData);
if (frame) {
frames.push(frame);
} // skip frame header and frame data
offset += frameData.size + 10;
}
if (isFooter(id3Data, offset)) {
offset += 10;
}
}
return frames;
};
var decodeFrame = function decodeFrame(frame) {
if (frame.type === 'PRIV') {
return decodePrivFrame(frame);
} else if (frame.type[0] === 'W') {
return decodeURLFrame(frame);
}
return decodeTextFrame(frame);
};
var decodePrivFrame = function decodePrivFrame(frame) {
/*
Format: <text string>\0<binary data>
*/
if (frame.size < 2) {
return undefined;
}
var owner = utf8ArrayToStr(frame.data, true);
var privateData = new Uint8Array(frame.data.subarray(owner.length + 1));
return {
key: frame.type,
info: owner,
data: privateData.buffer
};
};
var decodeTextFrame = function decodeTextFrame(frame) {
if (frame.size < 2) {
return undefined;
}
if (frame.type === 'TXXX') {
/*
Format:
[0] = {Text Encoding}
[1-?] = {Description}\0{Value}
*/
var index = 1;
var description = utf8ArrayToStr(frame.data.subarray(index), true);
index += description.length + 1;
var value = utf8ArrayToStr(frame.data.subarray(index));
return {
key: frame.type,
info: description,
data: value
};
}
/*
Format:
[0] = {Text Encoding}
[1-?] = {Value}
*/
var text = utf8ArrayToStr(frame.data.subarray(1));
return {
key: frame.type,
data: text
};
};
var decodeURLFrame = function decodeURLFrame(frame) {
if (frame.type === 'WXXX') {
/*
Format:
[0] = {Text Encoding}
[1-?] = {Description}\0{URL}
*/
if (frame.size < 2) {
return undefined;
}
var index = 1;
var description = utf8ArrayToStr(frame.data.subarray(index), true);
index += description.length + 1;
var value = utf8ArrayToStr(frame.data.subarray(index));
return {
key: frame.type,
info: description,
data: value
};
}
/*
Format:
[0-?] = {URL}
*/
var url = utf8ArrayToStr(frame.data);
return {
key: frame.type,
data: url
};
};
var readTimeStamp = function readTimeStamp(timeStampFrame) {
if (timeStampFrame.data.byteLength === 8) {
var data = new Uint8Array(timeStampFrame.data); // timestamp is 33 bit expressed as a big-endian eight-octet number,
// with the upper 31 bits set to zero.
var pts33Bit = data[3] & 0x1;
var timestamp = (data[4] << 23) + (data[5] << 15) + (data[6] << 7) + data[7];
timestamp /= 45;
if (pts33Bit) {
timestamp += 47721858.84;
} // 2^32 / 90
return Math.round(timestamp);
}
return undefined;
}; // http://stackoverflow.com/questions/8936984/uint8array-to-string-in-javascript/22373197
// http://www.onicos.com/staff/iz/amuse/javascript/expert/utf.txt
/* utf.js - UTF-8 <=> UTF-16 convertion
*
* Copyright (C) 1999 Masanao Izumo <iz@onicos.co.jp>
* Version: 1.0
* LastModified: Dec 25 1999
* This library is free. You can redistribute it and/or modify it.
*/
var utf8ArrayToStr = function utf8ArrayToStr(array, exitOnNull) {
if (exitOnNull === void 0) {
exitOnNull = false;
}
var decoder = getTextDecoder();
if (decoder) {
var decoded = decoder.decode(array);
if (exitOnNull) {
// grab up to the first null
var idx = decoded.indexOf('\0');
return idx !== -1 ? decoded.substring(0, idx) : decoded;
} // remove any null characters
return decoded.replace(/\0/g, '');
}
var len = array.length;
var c;
var char2;
var char3;
var out = '';
var i = 0;
while (i < len) {
c = array[i++];
if (c === 0x00 && exitOnNull) {
return out;
} else if (c === 0x00 || c === 0x03) {
// If the character is 3 (END_OF_TEXT) or 0 (NULL) then skip it
continue;
}
switch (c >> 4) {
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
// 0xxxxxxx
out += String.fromCharCode(c);
break;
case 12:
case 13:
// 110x xxxx 10xx xxxx
char2 = array[i++];
out += String.fromCharCode((c & 0x1f) << 6 | char2 & 0x3f);
break;
case 14:
// 1110 xxxx 10xx xxxx 10xx xxxx
char2 = array[i++];
char3 = array[i++];
out += String.fromCharCode((c & 0x0f) << 12 | (char2 & 0x3f) << 6 | (char3 & 0x3f) << 0);
break;
default:
}
}
return out;
};
var testables = {
decodeTextFrame: decodeTextFrame
};
var decoder;
function getTextDecoder() {
if (!decoder && typeof self.TextDecoder !== 'undefined') {
decoder = new self.TextDecoder('utf-8');
}
return decoder;
}
/***/ }),
/***/ "./src/demux/mp3demuxer.ts":
/*!*********************************!*\
!*** ./src/demux/mp3demuxer.ts ***!
\*********************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _base_audio_demuxer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base-audio-demuxer */ "./src/demux/base-audio-demuxer.ts");
/* harmony import */ var _demux_id3__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../demux/id3 */ "./src/demux/id3.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/* harmony import */ var _mpegaudio__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./mpegaudio */ "./src/demux/mpegaudio.ts");
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
/**
* MP3 demuxer
*/
var MP3Demuxer = /*#__PURE__*/function (_BaseAudioDemuxer) {
_inheritsLoose(MP3Demuxer, _BaseAudioDemuxer);
function MP3Demuxer() {
return _BaseAudioDemuxer.apply(this, arguments) || this;
}
var _proto = MP3Demuxer.prototype;
_proto.resetInitSegment = function resetInitSegment(audioCodec, videoCodec, duration) {
_BaseAudioDemuxer.prototype.resetInitSegment.call(this, audioCodec, videoCodec, duration);
this._audioTrack = {
container: 'audio/mpeg',
type: 'audio',
id: 0,
pid: -1,
sequenceNumber: 0,
isAAC: false,
samples: [],
manifestCodec: audioCodec,
duration: duration,
inputTimeScale: 90000,
dropped: 0
};
};
MP3Demuxer.probe = function probe(data) {
if (!data) {
return false;
} // check if data contains ID3 timestamp and MPEG sync word
// Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1
// Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III)
// More info http://www.mp3-tech.org/programmer/frame_header.html
var id3Data = _demux_id3__WEBPACK_IMPORTED_MODULE_1__["getID3Data"](data, 0) || [];
var offset = id3Data.length;
for (var length = data.length; offset < length; offset++) {
if (_mpegaudio__WEBPACK_IMPORTED_MODULE_3__["probe"](data, offset)) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('MPEG Audio sync word found !');
return true;
}
}
return false;
};
_proto.canParse = function canParse(data, offset) {
return _mpegaudio__WEBPACK_IMPORTED_MODULE_3__["canParse"](data, offset);
};
_proto.appendFrame = function appendFrame(track, data, offset) {
if (this.initPTS === null) {
return;
}
return _mpegaudio__WEBPACK_IMPORTED_MODULE_3__["appendFrame"](track, data, offset, this.initPTS, this.frameIndex);
};
return MP3Demuxer;
}(_base_audio_demuxer__WEBPACK_IMPORTED_MODULE_0__["default"]);
MP3Demuxer.minProbeByteLength = 4;
/* harmony default export */ __webpack_exports__["default"] = (MP3Demuxer);
/***/ }),
/***/ "./src/demux/mp4demuxer.ts":
/*!*********************************!*\
!*** ./src/demux/mp4demuxer.ts ***!
\*********************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/mp4-tools */ "./src/utils/mp4-tools.ts");
/* harmony import */ var _dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./dummy-demuxed-track */ "./src/demux/dummy-demuxed-track.ts");
/**
* MP4 demuxer
*/
var MP4Demuxer = /*#__PURE__*/function () {
function MP4Demuxer(observer, config) {
this.remainderData = null;
this.config = void 0;
this.config = config;
}
var _proto = MP4Demuxer.prototype;
_proto.resetTimeStamp = function resetTimeStamp() {};
_proto.resetInitSegment = function resetInitSegment() {};
_proto.resetContiguity = function resetContiguity() {};
MP4Demuxer.probe = function probe(data) {
// ensure we find a moof box in the first 16 kB
return Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_0__["findBox"])({
data: data,
start: 0,
end: Math.min(data.length, 16384)
}, ['moof']).length > 0;
};
_proto.demux = function demux(data) {
// Load all data into the avc track. The CMAF remuxer will look for the data in the samples object; the rest of the fields do not matter
var avcSamples = data;
var avcTrack = Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__["dummyTrack"])();
if (this.config.progressive) {
// Split the bytestream into two ranges: one encompassing all data up until the start of the last moof, and everything else.
// This is done to guarantee that we're sending valid data to MSE - when demuxing progressively, we have no guarantee
// that the fetch loader gives us flush moof+mdat pairs. If we push jagged data to MSE, it will throw an exception.
if (this.remainderData) {
avcSamples = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_0__["appendUint8Array"])(this.remainderData, data);
}
var segmentedData = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_0__["segmentValidRange"])(avcSamples);
this.remainderData = segmentedData.remainder;
avcTrack.samples = segmentedData.valid || new Uint8Array();
} else {
avcTrack.samples = avcSamples;
}
return {
audioTrack: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__["dummyTrack"])(),
avcTrack: avcTrack,
id3Track: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__["dummyTrack"])(),
textTrack: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__["dummyTrack"])()
};
};
_proto.flush = function flush() {
var avcTrack = Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__["dummyTrack"])();
avcTrack.samples = this.remainderData || new Uint8Array();
this.remainderData = null;
return {
audioTrack: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__["dummyTrack"])(),
avcTrack: avcTrack,
id3Track: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__["dummyTrack"])(),
textTrack: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__["dummyTrack"])()
};
};
_proto.demuxSampleAes = function demuxSampleAes(data, keyData, timeOffset) {
return Promise.reject(new Error('The MP4 demuxer does not support SAMPLE-AES decryption'));
};
_proto.destroy = function destroy() {};
return MP4Demuxer;
}();
MP4Demuxer.minProbeByteLength = 1024;
/* harmony default export */ __webpack_exports__["default"] = (MP4Demuxer);
/***/ }),
/***/ "./src/demux/mpegaudio.ts":
/*!********************************!*\
!*** ./src/demux/mpegaudio.ts ***!
\********************************/
/*! exports provided: appendFrame, parseHeader, isHeaderPattern, isHeader, canParse, probe */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "appendFrame", function() { return appendFrame; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseHeader", function() { return parseHeader; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isHeaderPattern", function() { return isHeaderPattern; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isHeader", function() { return isHeader; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "canParse", function() { return canParse; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "probe", function() { return probe; });
/**
* MPEG parser helper
*/
var chromeVersion = null;
var BitratesMap = [32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160];
var SamplingRateMap = [44100, 48000, 32000, 22050, 24000, 16000, 11025, 12000, 8000];
var SamplesCoefficients = [// MPEG 2.5
[0, // Reserved
72, // Layer3
144, // Layer2
12 // Layer1
], // Reserved
[0, // Reserved
0, // Layer3
0, // Layer2
0 // Layer1
], // MPEG 2
[0, // Reserved
72, // Layer3
144, // Layer2
12 // Layer1
], // MPEG 1
[0, // Reserved
144, // Layer3
144, // Layer2
12 // Layer1
]];
var BytesInSlot = [0, // Reserved
1, // Layer3
1, // Layer2
4 // Layer1
];
function appendFrame(track, data, offset, pts, frameIndex) {
// Using http://www.datavoyage.com/mpgscript/mpeghdr.htm as a reference
if (offset + 24 > data.length) {
return;
}
var header = parseHeader(data, offset);
if (header && offset + header.frameLength <= data.length) {
var frameDuration = header.samplesPerFrame * 90000 / header.sampleRate;
var stamp = pts + frameIndex * frameDuration;
var sample = {
unit: data.subarray(offset, offset + header.frameLength),
pts: stamp,
dts: stamp
};
track.config = [];
track.channelCount = header.channelCount;
track.samplerate = header.sampleRate;
track.samples.push(sample);
return {
sample: sample,
length: header.frameLength
};
}
}
function parseHeader(data, offset) {
var mpegVersion = data[offset + 1] >> 3 & 3;
var mpegLayer = data[offset + 1] >> 1 & 3;
var bitRateIndex = data[offset + 2] >> 4 & 15;
var sampleRateIndex = data[offset + 2] >> 2 & 3;
if (mpegVersion !== 1 && bitRateIndex !== 0 && bitRateIndex !== 15 && sampleRateIndex !== 3) {
var paddingBit = data[offset + 2] >> 1 & 1;
var channelMode = data[offset + 3] >> 6;
var columnInBitrates = mpegVersion === 3 ? 3 - mpegLayer : mpegLayer === 3 ? 3 : 4;
var bitRate = BitratesMap[columnInBitrates * 14 + bitRateIndex - 1] * 1000;
var columnInSampleRates = mpegVersion === 3 ? 0 : mpegVersion === 2 ? 1 : 2;
var sampleRate = SamplingRateMap[columnInSampleRates * 3 + sampleRateIndex];
var channelCount = channelMode === 3 ? 1 : 2; // If bits of channel mode are `11` then it is a single channel (Mono)
var sampleCoefficient = SamplesCoefficients[mpegVersion][mpegLayer];
var bytesInSlot = BytesInSlot[mpegLayer];
var samplesPerFrame = sampleCoefficient * 8 * bytesInSlot;
var frameLength = Math.floor(sampleCoefficient * bitRate / sampleRate + paddingBit) * bytesInSlot;
if (chromeVersion === null) {
var userAgent = navigator.userAgent || '';
var result = userAgent.match(/Chrome\/(\d+)/i);
chromeVersion = result ? parseInt(result[1]) : 0;
}
var needChromeFix = !!chromeVersion && chromeVersion <= 87;
if (needChromeFix && mpegLayer === 2 && bitRate >= 224000 && channelMode === 0) {
// Work around bug in Chromium by setting channelMode to dual-channel (01) instead of stereo (00)
data[offset + 3] = data[offset + 3] | 0x80;
}
return {
sampleRate: sampleRate,
channelCount: channelCount,
frameLength: frameLength,
samplesPerFrame: samplesPerFrame
};
}
}
function isHeaderPattern(data, offset) {
return data[offset] === 0xff && (data[offset + 1] & 0xe0) === 0xe0 && (data[offset + 1] & 0x06) !== 0x00;
}
function isHeader(data, offset) {
// Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1
// Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III)
// More info http://www.mp3-tech.org/programmer/frame_header.html
return offset + 1 < data.length && isHeaderPattern(data, offset);
}
function canParse(data, offset) {
var headerSize = 4;
return isHeaderPattern(data, offset) && data.length - offset >= headerSize;
}
function probe(data, offset) {
// same as isHeader but we also check that MPEG frame follows last MPEG frame
// or end of data is reached
if (offset + 1 < data.length && isHeaderPattern(data, offset)) {
// MPEG header Length
var headerLength = 4; // MPEG frame Length
var header = parseHeader(data, offset);
var frameLength = headerLength;
if (header !== null && header !== void 0 && header.frameLength) {
frameLength = header.frameLength;
}
var newOffset = offset + frameLength;
return newOffset === data.length || isHeader(data, newOffset);
}
return false;
}
/***/ }),
/***/ "./src/demux/sample-aes.ts":
/*!*********************************!*\
!*** ./src/demux/sample-aes.ts ***!
\*********************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _crypt_decrypter__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../crypt/decrypter */ "./src/crypt/decrypter.ts");
/* harmony import */ var _tsdemuxer__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./tsdemuxer */ "./src/demux/tsdemuxer.ts");
/**
* SAMPLE-AES decrypter
*/
var SampleAesDecrypter = /*#__PURE__*/function () {
function SampleAesDecrypter(observer, config, keyData) {
this.keyData = void 0;
this.decrypter = void 0;
this.keyData = keyData;
this.decrypter = new _crypt_decrypter__WEBPACK_IMPORTED_MODULE_0__["default"](observer, config, {
removePKCS7Padding: false
});
}
var _proto = SampleAesDecrypter.prototype;
_proto.decryptBuffer = function decryptBuffer(encryptedData, callback) {
this.decrypter.decrypt(encryptedData, this.keyData.key.buffer, this.keyData.iv.buffer, callback);
} // AAC - encrypt all full 16 bytes blocks starting from offset 16
;
_proto.decryptAacSample = function decryptAacSample(samples, sampleIndex, callback, sync) {
var curUnit = samples[sampleIndex].unit;
var encryptedData = curUnit.subarray(16, curUnit.length - curUnit.length % 16);
var encryptedBuffer = encryptedData.buffer.slice(encryptedData.byteOffset, encryptedData.byteOffset + encryptedData.length);
var localthis = this;
this.decryptBuffer(encryptedBuffer, function (decryptedBuffer) {
var decryptedData = new Uint8Array(decryptedBuffer);
curUnit.set(decryptedData, 16);
if (!sync) {
localthis.decryptAacSamples(samples, sampleIndex + 1, callback);
}
});
};
_proto.decryptAacSamples = function decryptAacSamples(samples, sampleIndex, callback) {
for (;; sampleIndex++) {
if (sampleIndex >= samples.length) {
callback();
return;
}
if (samples[sampleIndex].unit.length < 32) {
continue;
}
var sync = this.decrypter.isSync();
this.decryptAacSample(samples, sampleIndex, callback, sync);
if (!sync) {
return;
}
}
} // AVC - encrypt one 16 bytes block out of ten, starting from offset 32
;
_proto.getAvcEncryptedData = function getAvcEncryptedData(decodedData) {
var encryptedDataLen = Math.floor((decodedData.length - 48) / 160) * 16 + 16;
var encryptedData = new Int8Array(encryptedDataLen);
var outputPos = 0;
for (var inputPos = 32; inputPos <= decodedData.length - 16; inputPos += 160, outputPos += 16) {
encryptedData.set(decodedData.subarray(inputPos, inputPos + 16), outputPos);
}
return encryptedData;
};
_proto.getAvcDecryptedUnit = function getAvcDecryptedUnit(decodedData, decryptedData) {
var uint8DecryptedData = new Uint8Array(decryptedData);
var inputPos = 0;
for (var outputPos = 32; outputPos <= decodedData.length - 16; outputPos += 160, inputPos += 16) {
decodedData.set(uint8DecryptedData.subarray(inputPos, inputPos + 16), outputPos);
}
return decodedData;
};
_proto.decryptAvcSample = function decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit, sync) {
var decodedData = Object(_tsdemuxer__WEBPACK_IMPORTED_MODULE_1__["discardEPB"])(curUnit.data);
var encryptedData = this.getAvcEncryptedData(decodedData);
var localthis = this;
this.decryptBuffer(encryptedData.buffer, function (decryptedBuffer) {
curUnit.data = localthis.getAvcDecryptedUnit(decodedData, decryptedBuffer);
if (!sync) {
localthis.decryptAvcSamples(samples, sampleIndex, unitIndex + 1, callback);
}
});
};
_proto.decryptAvcSamples = function decryptAvcSamples(samples, sampleIndex, unitIndex, callback) {
if (samples instanceof Uint8Array) {
throw new Error('Cannot decrypt samples of type Uint8Array');
}
for (;; sampleIndex++, unitIndex = 0) {
if (sampleIndex >= samples.length) {
callback();
return;
}
var curUnits = samples[sampleIndex].units;
for (;; unitIndex++) {
if (unitIndex >= curUnits.length) {
break;
}
var curUnit = curUnits[unitIndex];
if (curUnit.data.length <= 48 || curUnit.type !== 1 && curUnit.type !== 5) {
continue;
}
var sync = this.decrypter.isSync();
this.decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit, sync);
if (!sync) {
return;
}
}
}
};
return SampleAesDecrypter;
}();
/* harmony default export */ __webpack_exports__["default"] = (SampleAesDecrypter);
/***/ }),
/***/ "./src/demux/transmuxer-interface.ts":
/*!*******************************************!*\
!*** ./src/demux/transmuxer-interface.ts ***!
\*******************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return TransmuxerInterface; });
/* harmony import */ var webworkify_webpack__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! webworkify-webpack */ "./node_modules/webworkify-webpack/index.js");
/* harmony import */ var webworkify_webpack__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(webworkify_webpack__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _demux_transmuxer__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../demux/transmuxer */ "./src/demux/transmuxer.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
/* harmony import */ var _utils_mediasource_helper__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/mediasource-helper */ "./src/utils/mediasource-helper.ts");
/* harmony import */ var eventemitter3__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! eventemitter3 */ "./node_modules/eventemitter3/index.js");
/* harmony import */ var eventemitter3__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(eventemitter3__WEBPACK_IMPORTED_MODULE_6__);
var MediaSource = Object(_utils_mediasource_helper__WEBPACK_IMPORTED_MODULE_5__["getMediaSource"])() || {
isTypeSupported: function isTypeSupported() {
return false;
}
};
var TransmuxerInterface = /*#__PURE__*/function () {
function TransmuxerInterface(hls, id, onTransmuxComplete, onFlush) {
var _this = this;
this.hls = void 0;
this.id = void 0;
this.observer = void 0;
this.frag = null;
this.part = null;
this.worker = void 0;
this.onwmsg = void 0;
this.transmuxer = null;
this.onTransmuxComplete = void 0;
this.onFlush = void 0;
this.hls = hls;
this.id = id;
this.onTransmuxComplete = onTransmuxComplete;
this.onFlush = onFlush;
var config = hls.config;
var forwardMessage = function forwardMessage(ev, data) {
data = data || {};
data.frag = _this.frag;
data.id = _this.id;
hls.trigger(ev, data);
}; // forward events to main thread
this.observer = new eventemitter3__WEBPACK_IMPORTED_MODULE_6__["EventEmitter"]();
this.observer.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_DECRYPTED, forwardMessage);
this.observer.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, forwardMessage);
var typeSupported = {
mp4: MediaSource.isTypeSupported('video/mp4'),
mpeg: MediaSource.isTypeSupported('audio/mpeg'),
mp3: MediaSource.isTypeSupported('audio/mp4; codecs="mp3"')
}; // navigator.vendor is not always available in Web Worker
// refer to https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/navigator
var vendor = navigator.vendor;
if (config.enableWorker && typeof Worker !== 'undefined') {
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].log('demuxing in webworker');
var worker;
try {
worker = this.worker = webworkify_webpack__WEBPACK_IMPORTED_MODULE_0__(/*require.resolve*/(/*! ../demux/transmuxer-worker.ts */ "./src/demux/transmuxer-worker.ts"));
this.onwmsg = this.onWorkerMessage.bind(this);
worker.addEventListener('message', this.onwmsg);
worker.onerror = function (event) {
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_4__["ErrorTypes"].OTHER_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_4__["ErrorDetails"].INTERNAL_EXCEPTION,
fatal: true,
event: 'demuxerWorker',
error: new Error(event.message + " (" + event.filename + ":" + event.lineno + ")")
});
};
worker.postMessage({
cmd: 'init',
typeSupported: typeSupported,
vendor: vendor,
id: id,
config: JSON.stringify(config)
});
} catch (err) {
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn('Error in worker:', err);
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].error('Error while initializing DemuxerWorker, fallback to inline');
if (worker) {
// revoke the Object URL that was used to create transmuxer worker, so as not to leak it
self.URL.revokeObjectURL(worker.objectURL);
}
this.transmuxer = new _demux_transmuxer__WEBPACK_IMPORTED_MODULE_2__["default"](this.observer, typeSupported, config, vendor);
this.worker = null;
}
} else {
this.transmuxer = new _demux_transmuxer__WEBPACK_IMPORTED_MODULE_2__["default"](this.observer, typeSupported, config, vendor);
}
}
var _proto = TransmuxerInterface.prototype;
_proto.destroy = function destroy() {
var w = this.worker;
if (w) {
w.removeEventListener('message', this.onwmsg);
w.terminate();
this.worker = null;
} else {
var transmuxer = this.transmuxer;
if (transmuxer) {
transmuxer.destroy();
this.transmuxer = null;
}
}
var observer = this.observer;
if (observer) {
observer.removeAllListeners();
} // @ts-ignore
this.observer = null;
};
_proto.push = function push(data, initSegmentData, audioCodec, videoCodec, frag, part, duration, accurateTimeOffset, chunkMeta, defaultInitPTS) {
var _this2 = this;
chunkMeta.transmuxing.start = self.performance.now();
var transmuxer = this.transmuxer,
worker = this.worker;
var timeOffset = part ? part.start : frag.start;
var decryptdata = frag.decryptdata;
var lastFrag = this.frag;
var discontinuity = !(lastFrag && frag.cc === lastFrag.cc);
var trackSwitch = !(lastFrag && chunkMeta.level === lastFrag.level);
var snDiff = lastFrag ? chunkMeta.sn - lastFrag.sn : -1;
var partDiff = this.part ? chunkMeta.part - this.part.index : 1;
var contiguous = !trackSwitch && (snDiff === 1 || snDiff === 0 && partDiff === 1);
var now = self.performance.now();
if (trackSwitch || snDiff || frag.stats.parsing.start === 0) {
frag.stats.parsing.start = now;
}
if (part && (partDiff || !contiguous)) {
part.stats.parsing.start = now;
}
var state = new _demux_transmuxer__WEBPACK_IMPORTED_MODULE_2__["TransmuxState"](discontinuity, contiguous, accurateTimeOffset, trackSwitch, timeOffset);
if (!contiguous || discontinuity) {
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].log("[transmuxer-interface, " + frag.type + "]: Starting new transmux session for sn: " + chunkMeta.sn + " p: " + chunkMeta.part + " level: " + chunkMeta.level + " id: " + chunkMeta.id + "\n discontinuity: " + discontinuity + "\n trackSwitch: " + trackSwitch + "\n contiguous: " + contiguous + "\n accurateTimeOffset: " + accurateTimeOffset + "\n timeOffset: " + timeOffset);
var config = new _demux_transmuxer__WEBPACK_IMPORTED_MODULE_2__["TransmuxConfig"](audioCodec, videoCodec, initSegmentData, duration, defaultInitPTS);
this.configureTransmuxer(config);
}
this.frag = frag;
this.part = part; // Frags with sn of 'initSegment' are not transmuxed
if (worker) {
// post fragment payload as transferable objects for ArrayBuffer (no copy)
worker.postMessage({
cmd: 'demux',
data: data,
decryptdata: decryptdata,
chunkMeta: chunkMeta,
state: state
}, data instanceof ArrayBuffer ? [data] : []);
} else if (transmuxer) {
var _transmuxResult = transmuxer.push(data, decryptdata, chunkMeta, state);
if (Object(_demux_transmuxer__WEBPACK_IMPORTED_MODULE_2__["isPromise"])(_transmuxResult)) {
_transmuxResult.then(function (data) {
_this2.handleTransmuxComplete(data);
});
} else {
this.handleTransmuxComplete(_transmuxResult);
}
}
};
_proto.flush = function flush(chunkMeta) {
var _this3 = this;
chunkMeta.transmuxing.start = self.performance.now();
var transmuxer = this.transmuxer,
worker = this.worker;
if (worker) {
worker.postMessage({
cmd: 'flush',
chunkMeta: chunkMeta
});
} else if (transmuxer) {
var _transmuxResult2 = transmuxer.flush(chunkMeta);
if (Object(_demux_transmuxer__WEBPACK_IMPORTED_MODULE_2__["isPromise"])(_transmuxResult2)) {
_transmuxResult2.then(function (data) {
_this3.handleFlushResult(data, chunkMeta);
});
} else {
this.handleFlushResult(_transmuxResult2, chunkMeta);
}
}
};
_proto.handleFlushResult = function handleFlushResult(results, chunkMeta) {
var _this4 = this;
results.forEach(function (result) {
_this4.handleTransmuxComplete(result);
});
this.onFlush(chunkMeta);
};
_proto.onWorkerMessage = function onWorkerMessage(ev) {
var data = ev.data;
var hls = this.hls;
switch (data.event) {
case 'init':
{
// revoke the Object URL that was used to create transmuxer worker, so as not to leak it
self.URL.revokeObjectURL(this.worker.objectURL);
break;
}
case 'transmuxComplete':
{
this.handleTransmuxComplete(data.data);
break;
}
case 'flush':
{
this.onFlush(data.data);
break;
}
/* falls through */
default:
{
data.data = data.data || {};
data.data.frag = this.frag;
data.data.id = this.id;
hls.trigger(data.event, data.data);
break;
}
}
};
_proto.configureTransmuxer = function configureTransmuxer(config) {
var worker = this.worker,
transmuxer = this.transmuxer;
if (worker) {
worker.postMessage({
cmd: 'configure',
config: config
});
} else if (transmuxer) {
transmuxer.configure(config);
}
};
_proto.handleTransmuxComplete = function handleTransmuxComplete(result) {
result.chunkMeta.transmuxing.end = self.performance.now();
this.onTransmuxComplete(result);
};
return TransmuxerInterface;
}();
/***/ }),
/***/ "./src/demux/transmuxer-worker.ts":
/*!****************************************!*\
!*** ./src/demux/transmuxer-worker.ts ***!
\****************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return TransmuxerWorker; });
/* harmony import */ var _demux_transmuxer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../demux/transmuxer */ "./src/demux/transmuxer.ts");
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/* harmony import */ var eventemitter3__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! eventemitter3 */ "./node_modules/eventemitter3/index.js");
/* harmony import */ var eventemitter3__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(eventemitter3__WEBPACK_IMPORTED_MODULE_3__);
function TransmuxerWorker(self) {
var observer = new eventemitter3__WEBPACK_IMPORTED_MODULE_3__["EventEmitter"]();
var forwardMessage = function forwardMessage(ev, data) {
self.postMessage({
event: ev,
data: data
});
}; // forward events to main thread
observer.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_DECRYPTED, forwardMessage);
observer.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, forwardMessage);
self.addEventListener('message', function (ev) {
var data = ev.data;
switch (data.cmd) {
case 'init':
{
var config = JSON.parse(data.config);
self.transmuxer = new _demux_transmuxer__WEBPACK_IMPORTED_MODULE_0__["default"](observer, data.typeSupported, config, data.vendor);
Object(_utils_logger__WEBPACK_IMPORTED_MODULE_2__["enableLogs"])(config.debug);
forwardMessage('init', null);
break;
}
case 'configure':
{
self.transmuxer.configure(data.config);
break;
}
case 'demux':
{
var transmuxResult = self.transmuxer.push(data.data, data.decryptdata, data.chunkMeta, data.state);
if (Object(_demux_transmuxer__WEBPACK_IMPORTED_MODULE_0__["isPromise"])(transmuxResult)) {
transmuxResult.then(function (data) {
emitTransmuxComplete(self, data);
});
} else {
emitTransmuxComplete(self, transmuxResult);
}
break;
}
case 'flush':
{
var id = data.chunkMeta;
var _transmuxResult = self.transmuxer.flush(id);
if (Object(_demux_transmuxer__WEBPACK_IMPORTED_MODULE_0__["isPromise"])(_transmuxResult)) {
_transmuxResult.then(function (results) {
handleFlushResult(self, results, id);
});
} else {
handleFlushResult(self, _transmuxResult, id);
}
break;
}
default:
break;
}
});
}
function emitTransmuxComplete(self, transmuxResult) {
if (isEmptyResult(transmuxResult.remuxResult)) {
return;
}
var transferable = [];
var _transmuxResult$remux = transmuxResult.remuxResult,
audio = _transmuxResult$remux.audio,
video = _transmuxResult$remux.video;
if (audio) {
addToTransferable(transferable, audio);
}
if (video) {
addToTransferable(transferable, video);
}
self.postMessage({
event: 'transmuxComplete',
data: transmuxResult
}, transferable);
} // Converts data to a transferable object https://developers.google.com/web/updates/2011/12/Transferable-Objects-Lightning-Fast)
// in order to minimize message passing overhead
function addToTransferable(transferable, track) {
if (track.data1) {
transferable.push(track.data1.buffer);
}
if (track.data2) {
transferable.push(track.data2.buffer);
}
}
function handleFlushResult(self, results, chunkMeta) {
results.forEach(function (result) {
emitTransmuxComplete(self, result);
});
self.postMessage({
event: 'flush',
data: chunkMeta
});
}
function isEmptyResult(remuxResult) {
return !remuxResult.audio && !remuxResult.video && !remuxResult.text && !remuxResult.id3 && !remuxResult.initSegment;
}
/***/ }),
/***/ "./src/demux/transmuxer.ts":
/*!*********************************!*\
!*** ./src/demux/transmuxer.ts ***!
\*********************************/
/*! exports provided: default, isPromise, TransmuxConfig, TransmuxState */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Transmuxer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isPromise", function() { return isPromise; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TransmuxConfig", function() { return TransmuxConfig; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TransmuxState", function() { return TransmuxState; });
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
/* harmony import */ var _crypt_decrypter__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../crypt/decrypter */ "./src/crypt/decrypter.ts");
/* harmony import */ var _demux_aacdemuxer__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../demux/aacdemuxer */ "./src/demux/aacdemuxer.ts");
/* harmony import */ var _demux_mp4demuxer__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../demux/mp4demuxer */ "./src/demux/mp4demuxer.ts");
/* harmony import */ var _demux_tsdemuxer__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../demux/tsdemuxer */ "./src/demux/tsdemuxer.ts");
/* harmony import */ var _demux_mp3demuxer__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../demux/mp3demuxer */ "./src/demux/mp3demuxer.ts");
/* harmony import */ var _remux_mp4_remuxer__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../remux/mp4-remuxer */ "./src/remux/mp4-remuxer.ts");
/* harmony import */ var _remux_passthrough_remuxer__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../remux/passthrough-remuxer */ "./src/remux/passthrough-remuxer.ts");
/* harmony import */ var _chunk_cache__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./chunk-cache */ "./src/demux/chunk-cache.ts");
/* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../utils/mp4-tools */ "./src/utils/mp4-tools.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
var now; // performance.now() not available on WebWorker, at least on Safari Desktop
try {
now = self.performance.now.bind(self.performance);
} catch (err) {
_utils_logger__WEBPACK_IMPORTED_MODULE_11__["logger"].debug('Unable to use Performance API on this environment');
now = self.Date.now;
}
var muxConfig = [{
demux: _demux_tsdemuxer__WEBPACK_IMPORTED_MODULE_5__["default"],
remux: _remux_mp4_remuxer__WEBPACK_IMPORTED_MODULE_7__["default"]
}, {
demux: _demux_mp4demuxer__WEBPACK_IMPORTED_MODULE_4__["default"],
remux: _remux_passthrough_remuxer__WEBPACK_IMPORTED_MODULE_8__["default"]
}, {
demux: _demux_aacdemuxer__WEBPACK_IMPORTED_MODULE_3__["default"],
remux: _remux_mp4_remuxer__WEBPACK_IMPORTED_MODULE_7__["default"]
}, {
demux: _demux_mp3demuxer__WEBPACK_IMPORTED_MODULE_6__["default"],
remux: _remux_mp4_remuxer__WEBPACK_IMPORTED_MODULE_7__["default"]
}];
var minProbeByteLength = 1024;
muxConfig.forEach(function (_ref) {
var demux = _ref.demux;
minProbeByteLength = Math.max(minProbeByteLength, demux.minProbeByteLength);
});
var Transmuxer = /*#__PURE__*/function () {
function Transmuxer(observer, typeSupported, config, vendor) {
this.observer = void 0;
this.typeSupported = void 0;
this.config = void 0;
this.vendor = void 0;
this.demuxer = void 0;
this.remuxer = void 0;
this.decrypter = void 0;
this.probe = void 0;
this.decryptionPromise = null;
this.transmuxConfig = void 0;
this.currentTransmuxState = void 0;
this.cache = new _chunk_cache__WEBPACK_IMPORTED_MODULE_9__["default"]();
this.observer = observer;
this.typeSupported = typeSupported;
this.config = config;
this.vendor = vendor;
}
var _proto = Transmuxer.prototype;
_proto.configure = function configure(transmuxConfig) {
this.transmuxConfig = transmuxConfig;
if (this.decrypter) {
this.decrypter.reset();
}
};
_proto.push = function push(data, decryptdata, chunkMeta, state) {
var _this = this;
var stats = chunkMeta.transmuxing;
stats.executeStart = now();
var uintData = new Uint8Array(data);
var cache = this.cache,
config = this.config,
currentTransmuxState = this.currentTransmuxState,
transmuxConfig = this.transmuxConfig;
if (state) {
this.currentTransmuxState = state;
}
var keyData = getEncryptionType(uintData, decryptdata);
if (keyData && keyData.method === 'AES-128') {
var decrypter = this.getDecrypter(); // Software decryption is synchronous; webCrypto is not
if (config.enableSoftwareAES) {
// Software decryption is progressive. Progressive decryption may not return a result on each call. Any cached
// data is handled in the flush() call
var decryptedData = decrypter.softwareDecrypt(uintData, keyData.key.buffer, keyData.iv.buffer);
if (!decryptedData) {
stats.executeEnd = now();
return emptyResult(chunkMeta);
}
uintData = new Uint8Array(decryptedData);
} else {
this.decryptionPromise = decrypter.webCryptoDecrypt(uintData, keyData.key.buffer, keyData.iv.buffer).then(function (decryptedData) {
// Calling push here is important; if flush() is called while this is still resolving, this ensures that
// the decrypted data has been transmuxed
var result = _this.push(decryptedData, null, chunkMeta);
_this.decryptionPromise = null;
return result;
});
return this.decryptionPromise;
}
}
var _ref2 = state || currentTransmuxState,
contiguous = _ref2.contiguous,
discontinuity = _ref2.discontinuity,
trackSwitch = _ref2.trackSwitch,
accurateTimeOffset = _ref2.accurateTimeOffset,
timeOffset = _ref2.timeOffset;
var audioCodec = transmuxConfig.audioCodec,
videoCodec = transmuxConfig.videoCodec,
defaultInitPts = transmuxConfig.defaultInitPts,
duration = transmuxConfig.duration,
initSegmentData = transmuxConfig.initSegmentData; // Reset muxers before probing to ensure that their state is clean, even if flushing occurs before a successful probe
if (discontinuity || trackSwitch) {
this.resetInitSegment(initSegmentData, audioCodec, videoCodec, duration);
}
if (discontinuity) {
this.resetInitialTimestamp(defaultInitPts);
}
if (!contiguous) {
this.resetContiguity();
}
if (this.needsProbing(uintData, discontinuity, trackSwitch)) {
if (cache.dataLength) {
var cachedData = cache.flush();
uintData = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_10__["appendUint8Array"])(cachedData, uintData);
}
this.configureTransmuxer(uintData, transmuxConfig);
}
var result = this.transmux(uintData, keyData, timeOffset, accurateTimeOffset, chunkMeta);
var currentState = this.currentTransmuxState;
currentState.contiguous = true;
currentState.discontinuity = false;
currentState.trackSwitch = false;
stats.executeEnd = now();
return result;
} // Due to data caching, flush calls can produce more than one TransmuxerResult (hence the Array type)
;
_proto.flush = function flush(chunkMeta) {
var _this2 = this;
var stats = chunkMeta.transmuxing;
stats.executeStart = now();
var decrypter = this.decrypter,
cache = this.cache,
currentTransmuxState = this.currentTransmuxState,
decryptionPromise = this.decryptionPromise;
if (decryptionPromise) {
// Upon resolution, the decryption promise calls push() and returns its TransmuxerResult up the stack. Therefore
// only flushing is required for async decryption
return decryptionPromise.then(function () {
return _this2.flush(chunkMeta);
});
}
var transmuxResults = [];
var timeOffset = currentTransmuxState.timeOffset;
if (decrypter) {
// The decrypter may have data cached, which needs to be demuxed. In this case we'll have two TransmuxResults
// This happens in the case that we receive only 1 push call for a segment (either for non-progressive downloads,
// or for progressive downloads with small segments)
var decryptedData = decrypter.flush();
if (decryptedData) {
// Push always returns a TransmuxerResult if decryptdata is null
transmuxResults.push(this.push(decryptedData, null, chunkMeta));
}
}
var bytesSeen = cache.dataLength;
cache.reset();
var demuxer = this.demuxer,
remuxer = this.remuxer;
if (!demuxer || !remuxer) {
// If probing failed, and each demuxer saw enough bytes to be able to probe, then Hls.js has been given content its not able to handle
if (bytesSeen >= minProbeByteLength) {
this.observer.emit(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, _events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].MEDIA_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].FRAG_PARSING_ERROR,
fatal: true,
reason: 'no demux matching with content found'
});
}
stats.executeEnd = now();
return [emptyResult(chunkMeta)];
}
var demuxResultOrPromise = demuxer.flush(timeOffset);
if (isPromise(demuxResultOrPromise)) {
// Decrypt final SAMPLE-AES samples
return demuxResultOrPromise.then(function (demuxResult) {
_this2.flushRemux(transmuxResults, demuxResult, chunkMeta);
return transmuxResults;
});
}
this.flushRemux(transmuxResults, demuxResultOrPromise, chunkMeta);
return transmuxResults;
};
_proto.flushRemux = function flushRemux(transmuxResults, demuxResult, chunkMeta) {
var audioTrack = demuxResult.audioTrack,
avcTrack = demuxResult.avcTrack,
id3Track = demuxResult.id3Track,
textTrack = demuxResult.textTrack;
var _this$currentTransmux = this.currentTransmuxState,
accurateTimeOffset = _this$currentTransmux.accurateTimeOffset,
timeOffset = _this$currentTransmux.timeOffset;
_utils_logger__WEBPACK_IMPORTED_MODULE_11__["logger"].log("[transmuxer.ts]: Flushed fragment " + chunkMeta.sn + (chunkMeta.part > -1 ? ' p: ' + chunkMeta.part : '') + " of level " + chunkMeta.level);
var remuxResult = this.remuxer.remux(audioTrack, avcTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, true);
transmuxResults.push({
remuxResult: remuxResult,
chunkMeta: chunkMeta
});
chunkMeta.transmuxing.executeEnd = now();
};
_proto.resetInitialTimestamp = function resetInitialTimestamp(defaultInitPts) {
var demuxer = this.demuxer,
remuxer = this.remuxer;
if (!demuxer || !remuxer) {
return;
}
demuxer.resetTimeStamp(defaultInitPts);
remuxer.resetTimeStamp(defaultInitPts);
};
_proto.resetContiguity = function resetContiguity() {
var demuxer = this.demuxer,
remuxer = this.remuxer;
if (!demuxer || !remuxer) {
return;
}
demuxer.resetContiguity();
remuxer.resetNextTimestamp();
};
_proto.resetInitSegment = function resetInitSegment(initSegmentData, audioCodec, videoCodec, duration) {
var demuxer = this.demuxer,
remuxer = this.remuxer;
if (!demuxer || !remuxer) {
return;
}
demuxer.resetInitSegment(audioCodec, videoCodec, duration);
remuxer.resetInitSegment(initSegmentData, audioCodec, videoCodec);
};
_proto.destroy = function destroy() {
if (this.demuxer) {
this.demuxer.destroy();
this.demuxer = undefined;
}
if (this.remuxer) {
this.remuxer.destroy();
this.remuxer = undefined;
}
};
_proto.transmux = function transmux(data, keyData, timeOffset, accurateTimeOffset, chunkMeta) {
var result;
if (keyData && keyData.method === 'SAMPLE-AES') {
result = this.transmuxSampleAes(data, keyData, timeOffset, accurateTimeOffset, chunkMeta);
} else {
result = this.transmuxUnencrypted(data, timeOffset, accurateTimeOffset, chunkMeta);
}
return result;
};
_proto.transmuxUnencrypted = function transmuxUnencrypted(data, timeOffset, accurateTimeOffset, chunkMeta) {
var _demux = this.demuxer.demux(data, timeOffset, false),
audioTrack = _demux.audioTrack,
avcTrack = _demux.avcTrack,
id3Track = _demux.id3Track,
textTrack = _demux.textTrack;
var remuxResult = this.remuxer.remux(audioTrack, avcTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, false);
return {
remuxResult: remuxResult,
chunkMeta: chunkMeta
};
};
_proto.transmuxSampleAes = function transmuxSampleAes(data, decryptData, timeOffset, accurateTimeOffset, chunkMeta) {
var _this3 = this;
return this.demuxer.demuxSampleAes(data, decryptData, timeOffset).then(function (demuxResult) {
var remuxResult = _this3.remuxer.remux(demuxResult.audioTrack, demuxResult.avcTrack, demuxResult.id3Track, demuxResult.textTrack, timeOffset, accurateTimeOffset, false);
return {
remuxResult: remuxResult,
chunkMeta: chunkMeta
};
});
};
_proto.configureTransmuxer = function configureTransmuxer(data, transmuxConfig) {
var config = this.config,
observer = this.observer,
typeSupported = this.typeSupported,
vendor = this.vendor;
var audioCodec = transmuxConfig.audioCodec,
defaultInitPts = transmuxConfig.defaultInitPts,
duration = transmuxConfig.duration,
initSegmentData = transmuxConfig.initSegmentData,
videoCodec = transmuxConfig.videoCodec; // probe for content type
var mux;
for (var i = 0, len = muxConfig.length; i < len; i++) {
if (muxConfig[i].demux.probe(data)) {
mux = muxConfig[i];
break;
}
}
if (!mux) {
// If probing previous configs fail, use mp4 passthrough
_utils_logger__WEBPACK_IMPORTED_MODULE_11__["logger"].warn('Failed to find demuxer by probing frag, treating as mp4 passthrough');
mux = {
demux: _demux_mp4demuxer__WEBPACK_IMPORTED_MODULE_4__["default"],
remux: _remux_passthrough_remuxer__WEBPACK_IMPORTED_MODULE_8__["default"]
};
} // so let's check that current remuxer and demuxer are still valid
var demuxer = this.demuxer;
var remuxer = this.remuxer;
var Remuxer = mux.remux;
var Demuxer = mux.demux;
if (!remuxer || !(remuxer instanceof Remuxer)) {
this.remuxer = new Remuxer(observer, config, typeSupported, vendor);
}
if (!demuxer || !(demuxer instanceof Demuxer)) {
this.demuxer = new Demuxer(observer, config, typeSupported);
this.probe = Demuxer.probe;
} // Ensure that muxers are always initialized with an initSegment
this.resetInitSegment(initSegmentData, audioCodec, videoCodec, duration);
this.resetInitialTimestamp(defaultInitPts);
};
_proto.needsProbing = function needsProbing(data, discontinuity, trackSwitch) {
// in case of continuity change, or track switch
// we might switch from content type (AAC container to TS container, or TS to fmp4 for example)
return !this.demuxer || !this.remuxer || discontinuity || trackSwitch;
};
_proto.getDecrypter = function getDecrypter() {
var decrypter = this.decrypter;
if (!decrypter) {
decrypter = this.decrypter = new _crypt_decrypter__WEBPACK_IMPORTED_MODULE_2__["default"](this.observer, this.config);
}
return decrypter;
};
return Transmuxer;
}();
function getEncryptionType(data, decryptData) {
var encryptionType = null;
if (data.byteLength > 0 && decryptData != null && decryptData.key != null && decryptData.iv !== null && decryptData.method != null) {
encryptionType = decryptData;
}
return encryptionType;
}
var emptyResult = function emptyResult(chunkMeta) {
return {
remuxResult: {},
chunkMeta: chunkMeta
};
};
function isPromise(p) {
return 'then' in p && p.then instanceof Function;
}
var TransmuxConfig = function TransmuxConfig(audioCodec, videoCodec, initSegmentData, duration, defaultInitPts) {
this.audioCodec = void 0;
this.videoCodec = void 0;
this.initSegmentData = void 0;
this.duration = void 0;
this.defaultInitPts = void 0;
this.audioCodec = audioCodec;
this.videoCodec = videoCodec;
this.initSegmentData = initSegmentData;
this.duration = duration;
this.defaultInitPts = defaultInitPts;
};
var TransmuxState = function TransmuxState(discontinuity, contiguous, accurateTimeOffset, trackSwitch, timeOffset) {
this.discontinuity = void 0;
this.contiguous = void 0;
this.accurateTimeOffset = void 0;
this.trackSwitch = void 0;
this.timeOffset = void 0;
this.discontinuity = discontinuity;
this.contiguous = contiguous;
this.accurateTimeOffset = accurateTimeOffset;
this.trackSwitch = trackSwitch;
this.timeOffset = timeOffset;
};
/***/ }),
/***/ "./src/demux/tsdemuxer.ts":
/*!********************************!*\
!*** ./src/demux/tsdemuxer.ts ***!
\********************************/
/*! exports provided: discardEPB, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "discardEPB", function() { return discardEPB; });
/* harmony import */ var _adts__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./adts */ "./src/demux/adts.ts");
/* harmony import */ var _mpegaudio__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./mpegaudio */ "./src/demux/mpegaudio.ts");
/* harmony import */ var _exp_golomb__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./exp-golomb */ "./src/demux/exp-golomb.ts");
/* harmony import */ var _id3__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./id3 */ "./src/demux/id3.ts");
/* harmony import */ var _sample_aes__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./sample-aes */ "./src/demux/sample-aes.ts");
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../utils/mp4-tools */ "./src/utils/mp4-tools.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
/**
* highly optimized TS demuxer:
* parse PAT, PMT
* extract PES packet from audio and video PIDs
* extract AVC/H264 NAL units and AAC/ADTS samples from PES packet
* trigger the remuxer upon parsing completion
* it also tries to workaround as best as it can audio codec switch (HE-AAC to AAC and vice versa), without having to restart the MediaSource.
* it also controls the remuxing process :
* upon discontinuity or level switch detection, it will also notifies the remuxer so that it can reset its state.
*/
// We are using fixed track IDs for driving the MP4 remuxer
// instead of following the TS PIDs.
// There is no reason not to do this and some browsers/SourceBuffer-demuxers
// may not like if there are TrackID "switches"
// See https://github.com/video-dev/hls.js/issues/1331
// Here we are mapping our internal track types to constant MP4 track IDs
// With MSE currently one can only have one track of each, and we are muxing
// whatever video/audio rendition in them.
var RemuxerTrackIdConfig = {
video: 1,
audio: 2,
id3: 3,
text: 4
};
var TSDemuxer = /*#__PURE__*/function () {
function TSDemuxer(observer, config, typeSupported) {
this.observer = void 0;
this.config = void 0;
this.typeSupported = void 0;
this.sampleAes = null;
this.pmtParsed = false;
this.audioCodec = void 0;
this.videoCodec = void 0;
this._duration = 0;
this.aacLastPTS = null;
this._initPTS = null;
this._initDTS = null;
this._pmtId = -1;
this._avcTrack = void 0;
this._audioTrack = void 0;
this._id3Track = void 0;
this._txtTrack = void 0;
this.aacOverFlow = null;
this.avcSample = null;
this.remainderData = null;
this.observer = observer;
this.config = config;
this.typeSupported = typeSupported;
}
TSDemuxer.probe = function probe(data) {
var syncOffset = TSDemuxer.syncOffset(data);
if (syncOffset < 0) {
return false;
} else {
if (syncOffset) {
_utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].warn("MPEG2-TS detected but first sync word found @ offset " + syncOffset + ", junk ahead ?");
}
return true;
}
};
TSDemuxer.syncOffset = function syncOffset(data) {
// scan 1000 first bytes
var scanwindow = Math.min(1000, data.length - 3 * 188);
var i = 0;
while (i < scanwindow) {
// a TS fragment should contain at least 3 TS packets, a PAT, a PMT, and one PID, each starting with 0x47
if (data[i] === 0x47 && data[i + 188] === 0x47 && data[i + 2 * 188] === 0x47) {
return i;
} else {
i++;
}
}
return -1;
}
/**
* Creates a track model internal to demuxer used to drive remuxing input
*
* @param type 'audio' | 'video' | 'id3' | 'text'
* @param duration
* @return TSDemuxer's internal track model
*/
;
TSDemuxer.createTrack = function createTrack(type, duration) {
return {
container: type === 'video' || type === 'audio' ? 'video/mp2t' : undefined,
type: type,
id: RemuxerTrackIdConfig[type],
pid: -1,
inputTimeScale: 90000,
sequenceNumber: 0,
samples: [],
dropped: 0,
duration: type === 'audio' ? duration : undefined
};
}
/**
* Initializes a new init segment on the demuxer/remuxer interface. Needed for discontinuities/track-switches (or at stream start)
* Resets all internal track instances of the demuxer.
*/
;
var _proto = TSDemuxer.prototype;
_proto.resetInitSegment = function resetInitSegment(audioCodec, videoCodec, duration) {
this.pmtParsed = false;
this._pmtId = -1;
this._avcTrack = TSDemuxer.createTrack('video', duration);
this._audioTrack = TSDemuxer.createTrack('audio', duration);
this._id3Track = TSDemuxer.createTrack('id3', duration);
this._txtTrack = TSDemuxer.createTrack('text', duration);
this._audioTrack.isAAC = true; // flush any partial content
this.aacOverFlow = null;
this.aacLastPTS = null;
this.avcSample = null;
this.audioCodec = audioCodec;
this.videoCodec = videoCodec;
this._duration = duration;
};
_proto.resetTimeStamp = function resetTimeStamp() {};
_proto.resetContiguity = function resetContiguity() {
var _audioTrack = this._audioTrack,
_avcTrack = this._avcTrack,
_id3Track = this._id3Track;
if (_audioTrack) {
_audioTrack.pesData = null;
}
if (_avcTrack) {
_avcTrack.pesData = null;
}
if (_id3Track) {
_id3Track.pesData = null;
}
this.aacOverFlow = null;
this.aacLastPTS = null;
};
_proto.demux = function demux(data, timeOffset, isSampleAes, flush) {
if (isSampleAes === void 0) {
isSampleAes = false;
}
if (flush === void 0) {
flush = false;
}
if (!isSampleAes) {
this.sampleAes = null;
}
var pes;
var avcTrack = this._avcTrack;
var audioTrack = this._audioTrack;
var id3Track = this._id3Track;
var avcId = avcTrack.pid;
var avcData = avcTrack.pesData;
var audioId = audioTrack.pid;
var id3Id = id3Track.pid;
var audioData = audioTrack.pesData;
var id3Data = id3Track.pesData;
var unknownPIDs = false;
var pmtParsed = this.pmtParsed;
var pmtId = this._pmtId;
var len = data.length;
if (this.remainderData) {
data = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_6__["appendUint8Array"])(this.remainderData, data);
len = data.length;
this.remainderData = null;
}
if (len < 188 && !flush) {
this.remainderData = data;
return {
audioTrack: audioTrack,
avcTrack: avcTrack,
id3Track: id3Track,
textTrack: this._txtTrack
};
}
var syncOffset = Math.max(0, TSDemuxer.syncOffset(data));
len -= (len + syncOffset) % 188;
if (len < data.byteLength && !flush) {
this.remainderData = new Uint8Array(data.buffer, len, data.buffer.byteLength - len);
} // loop through TS packets
for (var start = syncOffset; start < len; start += 188) {
if (data[start] === 0x47) {
var stt = !!(data[start + 1] & 0x40); // pid is a 13-bit field starting at the last bit of TS[1]
var pid = ((data[start + 1] & 0x1f) << 8) + data[start + 2];
var atf = (data[start + 3] & 0x30) >> 4; // if an adaption field is present, its length is specified by the fifth byte of the TS packet header.
var offset = void 0;
if (atf > 1) {
offset = start + 5 + data[start + 4]; // continue if there is only adaptation field
if (offset === start + 188) {
continue;
}
} else {
offset = start + 4;
}
switch (pid) {
case avcId:
if (stt) {
if (avcData && (pes = parsePES(avcData))) {
this.parseAVCPES(pes, false);
}
avcData = {
data: [],
size: 0
};
}
if (avcData) {
avcData.data.push(data.subarray(offset, start + 188));
avcData.size += start + 188 - offset;
}
break;
case audioId:
if (stt) {
if (audioData && (pes = parsePES(audioData))) {
if (audioTrack.isAAC) {
this.parseAACPES(pes);
} else {
this.parseMPEGPES(pes);
}
}
audioData = {
data: [],
size: 0
};
}
if (audioData) {
audioData.data.push(data.subarray(offset, start + 188));
audioData.size += start + 188 - offset;
}
break;
case id3Id:
if (stt) {
if (id3Data && (pes = parsePES(id3Data))) {
this.parseID3PES(pes);
}
id3Data = {
data: [],
size: 0
};
}
if (id3Data) {
id3Data.data.push(data.subarray(offset, start + 188));
id3Data.size += start + 188 - offset;
}
break;
case 0:
if (stt) {
offset += data[offset] + 1;
}
pmtId = this._pmtId = parsePAT(data, offset);
break;
case pmtId:
{
if (stt) {
offset += data[offset] + 1;
}
var parsedPIDs = parsePMT(data, offset, this.typeSupported.mpeg === true || this.typeSupported.mp3 === true, isSampleAes); // only update track id if track PID found while parsing PMT
// this is to avoid resetting the PID to -1 in case
// track PID transiently disappears from the stream
// this could happen in case of transient missing audio samples for example
// NOTE this is only the PID of the track as found in TS,
// but we are not using this for MP4 track IDs.
avcId = parsedPIDs.avc;
if (avcId > 0) {
avcTrack.pid = avcId;
}
audioId = parsedPIDs.audio;
if (audioId > 0) {
audioTrack.pid = audioId;
audioTrack.isAAC = parsedPIDs.isAAC;
}
id3Id = parsedPIDs.id3;
if (id3Id > 0) {
id3Track.pid = id3Id;
}
if (unknownPIDs && !pmtParsed) {
_utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].log('reparse from beginning');
unknownPIDs = false; // we set it to -188, the += 188 in the for loop will reset start to 0
start = syncOffset - 188;
}
pmtParsed = this.pmtParsed = true;
break;
}
case 17:
case 0x1fff:
break;
default:
unknownPIDs = true;
break;
}
} else {
this.observer.emit(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].ERROR, _events__WEBPACK_IMPORTED_MODULE_5__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_8__["ErrorTypes"].MEDIA_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_8__["ErrorDetails"].FRAG_PARSING_ERROR,
fatal: false,
reason: 'TS packet did not start with 0x47'
});
}
}
avcTrack.pesData = avcData;
audioTrack.pesData = audioData;
id3Track.pesData = id3Data;
var demuxResult = {
audioTrack: audioTrack,
avcTrack: avcTrack,
id3Track: id3Track,
textTrack: this._txtTrack
};
this.extractRemainingSamples(demuxResult);
return demuxResult;
};
_proto.flush = function flush() {
var remainderData = this.remainderData;
this.remainderData = null;
var result;
if (remainderData) {
result = this.demux(remainderData, -1, false, true);
} else {
result = {
audioTrack: this._audioTrack,
avcTrack: this._avcTrack,
textTrack: this._txtTrack,
id3Track: this._id3Track
};
}
this.extractRemainingSamples(result);
if (this.sampleAes) {
return this.decrypt(result, this.sampleAes);
}
return result;
};
_proto.extractRemainingSamples = function extractRemainingSamples(demuxResult) {
var audioTrack = demuxResult.audioTrack,
avcTrack = demuxResult.avcTrack,
id3Track = demuxResult.id3Track;
var avcData = avcTrack.pesData;
var audioData = audioTrack.pesData;
var id3Data = id3Track.pesData; // try to parse last PES packets
var pes;
if (avcData && (pes = parsePES(avcData))) {
this.parseAVCPES(pes, true);
avcTrack.pesData = null;
} else {
// either avcData null or PES truncated, keep it for next frag parsing
avcTrack.pesData = avcData;
}
if (audioData && (pes = parsePES(audioData))) {
if (audioTrack.isAAC) {
this.parseAACPES(pes);
} else {
this.parseMPEGPES(pes);
}
audioTrack.pesData = null;
} else {
if (audioData !== null && audioData !== void 0 && audioData.size) {
_utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].log('last AAC PES packet truncated,might overlap between fragments');
} // either audioData null or PES truncated, keep it for next frag parsing
audioTrack.pesData = audioData;
}
if (id3Data && (pes = parsePES(id3Data))) {
this.parseID3PES(pes);
id3Track.pesData = null;
} else {
// either id3Data null or PES truncated, keep it for next frag parsing
id3Track.pesData = id3Data;
}
};
_proto.demuxSampleAes = function demuxSampleAes(data, keyData, timeOffset) {
var demuxResult = this.demux(data, timeOffset, true);
var sampleAes = this.sampleAes = new _sample_aes__WEBPACK_IMPORTED_MODULE_4__["default"](this.observer, this.config, keyData);
return this.decrypt(demuxResult, sampleAes);
};
_proto.decrypt = function decrypt(demuxResult, sampleAes) {
return new Promise(function (resolve) {
var audioTrack = demuxResult.audioTrack,
avcTrack = demuxResult.avcTrack;
if (audioTrack.samples && audioTrack.isAAC) {
sampleAes.decryptAacSamples(audioTrack.samples, 0, function () {
if (avcTrack.samples) {
sampleAes.decryptAvcSamples(avcTrack.samples, 0, 0, function () {
resolve(demuxResult);
});
} else {
resolve(demuxResult);
}
});
} else if (avcTrack.samples) {
sampleAes.decryptAvcSamples(avcTrack.samples, 0, 0, function () {
resolve(demuxResult);
});
}
});
};
_proto.destroy = function destroy() {
this._initPTS = this._initDTS = null;
this._duration = 0;
};
_proto.parseAVCPES = function parseAVCPES(pes, last) {
var _this = this;
var track = this._avcTrack;
var units = this.parseAVCNALu(pes.data);
var debug = false;
var avcSample = this.avcSample;
var push;
var spsfound = false; // free pes.data to save up some memory
pes.data = null; // if new NAL units found and last sample still there, let's push ...
// this helps parsing streams with missing AUD (only do this if AUD never found)
if (avcSample && units.length && !track.audFound) {
pushAccessUnit(avcSample, track);
avcSample = this.avcSample = createAVCSample(false, pes.pts, pes.dts, '');
}
units.forEach(function (unit) {
switch (unit.type) {
// NDR
case 1:
{
push = true;
if (!avcSample) {
avcSample = _this.avcSample = createAVCSample(true, pes.pts, pes.dts, '');
}
if (debug) {
avcSample.debug += 'NDR ';
}
avcSample.frame = true;
var data = unit.data; // only check slice type to detect KF in case SPS found in same packet (any keyframe is preceded by SPS ...)
if (spsfound && data.length > 4) {
// retrieve slice type by parsing beginning of NAL unit (follow H264 spec, slice_header definition) to detect keyframe embedded in NDR
var sliceType = new _exp_golomb__WEBPACK_IMPORTED_MODULE_2__["default"](data).readSliceType(); // 2 : I slice, 4 : SI slice, 7 : I slice, 9: SI slice
// SI slice : A slice that is coded using intra prediction only and using quantisation of the prediction samples.
// An SI slice can be coded such that its decoded samples can be constructed identically to an SP slice.
// I slice: A slice that is not an SI slice that is decoded using intra prediction only.
// if (sliceType === 2 || sliceType === 7) {
if (sliceType === 2 || sliceType === 4 || sliceType === 7 || sliceType === 9) {
avcSample.key = true;
}
}
break; // IDR
}
case 5:
push = true; // handle PES not starting with AUD
if (!avcSample) {
avcSample = _this.avcSample = createAVCSample(true, pes.pts, pes.dts, '');
}
if (debug) {
avcSample.debug += 'IDR ';
}
avcSample.key = true;
avcSample.frame = true;
break;
// SEI
case 6:
{
push = true;
if (debug && avcSample) {
avcSample.debug += 'SEI ';
}
var expGolombDecoder = new _exp_golomb__WEBPACK_IMPORTED_MODULE_2__["default"](discardEPB(unit.data)); // skip frameType
expGolombDecoder.readUByte();
var payloadType = 0;
var payloadSize = 0;
var endOfCaptions = false;
var b = 0;
while (!endOfCaptions && expGolombDecoder.bytesAvailable > 1) {
payloadType = 0;
do {
b = expGolombDecoder.readUByte();
payloadType += b;
} while (b === 0xff); // Parse payload size.
payloadSize = 0;
do {
b = expGolombDecoder.readUByte();
payloadSize += b;
} while (b === 0xff); // TODO: there can be more than one payload in an SEI packet...
// TODO: need to read type and size in a while loop to get them all
if (payloadType === 4 && expGolombDecoder.bytesAvailable !== 0) {
endOfCaptions = true;
var countryCode = expGolombDecoder.readUByte();
if (countryCode === 181) {
var providerCode = expGolombDecoder.readUShort();
if (providerCode === 49) {
var userStructure = expGolombDecoder.readUInt();
if (userStructure === 0x47413934) {
var userDataType = expGolombDecoder.readUByte(); // Raw CEA-608 bytes wrapped in CEA-708 packet
if (userDataType === 3) {
var firstByte = expGolombDecoder.readUByte();
var secondByte = expGolombDecoder.readUByte();
var totalCCs = 31 & firstByte;
var byteArray = [firstByte, secondByte];
for (var i = 0; i < totalCCs; i++) {
// 3 bytes per CC
byteArray.push(expGolombDecoder.readUByte());
byteArray.push(expGolombDecoder.readUByte());
byteArray.push(expGolombDecoder.readUByte());
}
insertSampleInOrder(_this._txtTrack.samples, {
type: 3,
pts: pes.pts,
bytes: byteArray
});
}
}
}
}
} else if (payloadType === 5 && expGolombDecoder.bytesAvailable !== 0) {
endOfCaptions = true;
if (payloadSize > 16) {
var uuidStrArray = [];
for (var _i = 0; _i < 16; _i++) {
uuidStrArray.push(expGolombDecoder.readUByte().toString(16));
if (_i === 3 || _i === 5 || _i === 7 || _i === 9) {
uuidStrArray.push('-');
}
}
var length = payloadSize - 16;
var userDataPayloadBytes = new Uint8Array(length);
for (var _i2 = 0; _i2 < length; _i2++) {
userDataPayloadBytes[_i2] = expGolombDecoder.readUByte();
}
insertSampleInOrder(_this._txtTrack.samples, {
pts: pes.pts,
payloadType: payloadType,
uuid: uuidStrArray.join(''),
userData: Object(_id3__WEBPACK_IMPORTED_MODULE_3__["utf8ArrayToStr"])(userDataPayloadBytes),
userDataBytes: userDataPayloadBytes
});
}
} else if (payloadSize < expGolombDecoder.bytesAvailable) {
for (var _i3 = 0; _i3 < payloadSize; _i3++) {
expGolombDecoder.readUByte();
}
}
}
break; // SPS
}
case 7:
push = true;
spsfound = true;
if (debug && avcSample) {
avcSample.debug += 'SPS ';
}
if (!track.sps) {
var _expGolombDecoder = new _exp_golomb__WEBPACK_IMPORTED_MODULE_2__["default"](unit.data);
var config = _expGolombDecoder.readSPS();
track.width = config.width;
track.height = config.height;
track.pixelRatio = config.pixelRatio; // TODO: `track.sps` is defined as a `number[]`, but we're setting it to a `Uint8Array[]`.
track.sps = [unit.data];
track.duration = _this._duration;
var codecarray = unit.data.subarray(1, 4);
var codecstring = 'avc1.';
for (var _i4 = 0; _i4 < 3; _i4++) {
var h = codecarray[_i4].toString(16);
if (h.length < 2) {
h = '0' + h;
}
codecstring += h;
}
track.codec = codecstring;
}
break;
// PPS
case 8:
push = true;
if (debug && avcSample) {
avcSample.debug += 'PPS ';
}
if (!track.pps) {
// TODO: `track.pss` is defined as a `number[]`, but we're setting it to a `Uint8Array[]`.
track.pps = [unit.data];
}
break;
// AUD
case 9:
push = false;
track.audFound = true;
if (avcSample) {
pushAccessUnit(avcSample, track);
}
avcSample = _this.avcSample = createAVCSample(false, pes.pts, pes.dts, debug ? 'AUD ' : '');
break;
// Filler Data
case 12:
push = false;
break;
default:
push = false;
if (avcSample) {
avcSample.debug += 'unknown NAL ' + unit.type + ' ';
}
break;
}
if (avcSample && push) {
var _units = avcSample.units;
_units.push(unit);
}
}); // if last PES packet, push samples
if (last && avcSample) {
pushAccessUnit(avcSample, track);
this.avcSample = null;
}
};
_proto.getLastNalUnit = function getLastNalUnit() {
var _avcSample;
var avcSample = this.avcSample;
var lastUnit; // try to fallback to previous sample if current one is empty
if (!avcSample || avcSample.units.length === 0) {
var samples = this._avcTrack.samples;
avcSample = samples[samples.length - 1];
}
if ((_avcSample = avcSample) !== null && _avcSample !== void 0 && _avcSample.units) {
var units = avcSample.units;
lastUnit = units[units.length - 1];
}
return lastUnit;
};
_proto.parseAVCNALu = function parseAVCNALu(array) {
var len = array.byteLength;
var track = this._avcTrack;
var state = track.naluState || 0;
var lastState = state;
var units = [];
var i = 0;
var value;
var overflow;
var unitType;
var lastUnitStart = -1;
var lastUnitType = 0; // logger.log('PES:' + Hex.hexDump(array));
if (state === -1) {
// special use case where we found 3 or 4-byte start codes exactly at the end of previous PES packet
lastUnitStart = 0; // NALu type is value read from offset 0
lastUnitType = array[0] & 0x1f;
state = 0;
i = 1;
}
while (i < len) {
value = array[i++]; // optimization. state 0 and 1 are the predominant case. let's handle them outside of the switch/case
if (!state) {
state = value ? 0 : 1;
continue;
}
if (state === 1) {
state = value ? 0 : 2;
continue;
} // here we have state either equal to 2 or 3
if (!value) {
state = 3;
} else if (value === 1) {
if (lastUnitStart >= 0) {
var unit = {
data: array.subarray(lastUnitStart, i - state - 1),
type: lastUnitType
}; // logger.log('pushing NALU, type/size:' + unit.type + '/' + unit.data.byteLength);
units.push(unit);
} else {
// lastUnitStart is undefined => this is the first start code found in this PES packet
// first check if start code delimiter is overlapping between 2 PES packets,
// ie it started in last packet (lastState not zero)
// and ended at the beginning of this PES packet (i <= 4 - lastState)
var lastUnit = this.getLastNalUnit();
if (lastUnit) {
if (lastState && i <= 4 - lastState) {
// start delimiter overlapping between PES packets
// strip start delimiter bytes from the end of last NAL unit
// check if lastUnit had a state different from zero
if (lastUnit.state) {
// strip last bytes
lastUnit.data = lastUnit.data.subarray(0, lastUnit.data.byteLength - lastState);
}
} // If NAL units are not starting right at the beginning of the PES packet, push preceding data into previous NAL unit.
overflow = i - state - 1;
if (overflow > 0) {
// logger.log('first NALU found with overflow:' + overflow);
var tmp = new Uint8Array(lastUnit.data.byteLength + overflow);
tmp.set(lastUnit.data, 0);
tmp.set(array.subarray(0, overflow), lastUnit.data.byteLength);
lastUnit.data = tmp;
}
}
} // check if we can read unit type
if (i < len) {
unitType = array[i] & 0x1f; // logger.log('find NALU @ offset:' + i + ',type:' + unitType);
lastUnitStart = i;
lastUnitType = unitType;
state = 0;
} else {
// not enough byte to read unit type. let's read it on next PES parsing
state = -1;
}
} else {
state = 0;
}
}
if (lastUnitStart >= 0 && state >= 0) {
var _unit = {
data: array.subarray(lastUnitStart, len),
type: lastUnitType,
state: state
};
units.push(_unit); // logger.log('pushing NALU, type/size/state:' + unit.type + '/' + unit.data.byteLength + '/' + state);
} // no NALu found
if (units.length === 0) {
// append pes.data to previous NAL unit
var _lastUnit = this.getLastNalUnit();
if (_lastUnit) {
var _tmp = new Uint8Array(_lastUnit.data.byteLength + array.byteLength);
_tmp.set(_lastUnit.data, 0);
_tmp.set(array, _lastUnit.data.byteLength);
_lastUnit.data = _tmp;
}
}
track.naluState = state;
return units;
};
_proto.parseAACPES = function parseAACPES(pes) {
var startOffset = 0;
var track = this._audioTrack;
var aacLastPTS = this.aacLastPTS;
var aacOverFlow = this.aacOverFlow;
var data = pes.data;
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)
var offset;
var len;
for (offset = startOffset, len = data.length; offset < len - 1; offset++) {
if (_adts__WEBPACK_IMPORTED_MODULE_0__["isHeader"](data, offset)) {
break;
}
} // if ADTS header does not start straight from the beginning of the PES payload, raise an error
if (offset) {
var reason;
var fatal;
if (offset < len - 1) {
reason = "AAC PES did not start with ADTS header,offset:" + offset;
fatal = false;
} else {
reason = 'no ADTS header found in AAC PES';
fatal = true;
}
_utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].warn("parsing error:" + reason);
this.observer.emit(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].ERROR, _events__WEBPACK_IMPORTED_MODULE_5__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_8__["ErrorTypes"].MEDIA_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_8__["ErrorDetails"].FRAG_PARSING_ERROR,
fatal: fatal,
reason: reason
});
if (fatal) {
return;
}
}
_adts__WEBPACK_IMPORTED_MODULE_0__["initTrackConfig"](track, this.observer, data, offset, this.audioCodec);
var frameIndex = 0;
var frameDuration = _adts__WEBPACK_IMPORTED_MODULE_0__["getFrameDuration"](track.samplerate); // if last AAC frame is overflowing, we should ensure timestamps are contiguous:
// first sample PTS should be equal to last sample PTS + frameDuration
var pts;
if (pes.pts !== undefined) {
pts = pes.pts;
} else if (aacLastPTS !== null) {
pts = aacLastPTS;
} else {
_utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].warn('[tsdemuxer]: AAC PES unknown PTS');
return;
}
if (aacOverFlow && aacLastPTS !== null) {
var newPTS = aacLastPTS + frameDuration;
if (Math.abs(newPTS - pts) > 1) {
_utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].log("[tsdemuxer]: AAC: align PTS for overlapping frames by " + Math.round((newPTS - pts) / 90));
pts = newPTS;
}
} // scan for aac samples
var stamp = null;
while (offset < len) {
if (_adts__WEBPACK_IMPORTED_MODULE_0__["isHeader"](data, offset)) {
if (offset + 5 < len) {
var frame = _adts__WEBPACK_IMPORTED_MODULE_0__["appendFrame"](track, data, offset, pts, frameIndex);
if (frame) {
offset += frame.length;
stamp = frame.sample.pts;
frameIndex++;
continue;
}
} // We are at an ADTS header, but do not have enough data for a frame
// Remaining data will be added to aacOverFlow
break;
} else {
// nothing found, keep looking
offset++;
}
}
this.aacOverFlow = offset < len ? data.subarray(offset, len) : null;
this.aacLastPTS = stamp;
};
_proto.parseMPEGPES = function parseMPEGPES(pes) {
var data = pes.data;
var length = data.length;
var frameIndex = 0;
var offset = 0;
var pts = pes.pts;
if (pts === undefined) {
_utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].warn('[tsdemuxer]: MPEG PES unknown PTS');
return;
}
while (offset < length) {
if (_mpegaudio__WEBPACK_IMPORTED_MODULE_1__["isHeader"](data, offset)) {
var frame = _mpegaudio__WEBPACK_IMPORTED_MODULE_1__["appendFrame"](this._audioTrack, data, offset, pts, frameIndex);
if (frame) {
offset += frame.length;
frameIndex++;
} else {
// logger.log('Unable to parse Mpeg audio frame');
break;
}
} else {
// nothing found, keep looking
offset++;
}
}
};
_proto.parseID3PES = function parseID3PES(pes) {
if (pes.pts === undefined) {
_utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].warn('[tsdemuxer]: ID3 PES unknown PTS');
return;
}
this._id3Track.samples.push(pes);
};
return TSDemuxer;
}();
TSDemuxer.minProbeByteLength = 188;
function createAVCSample(key, pts, dts, debug) {
return {
key: key,
frame: false,
pts: pts,
dts: dts,
units: [],
debug: debug,
length: 0
};
}
function parsePAT(data, offset) {
// skip the PSI header and parse the first PMT entry
return (data[offset + 10] & 0x1f) << 8 | data[offset + 11]; // logger.log('PMT PID:' + this._pmtId);
}
function parsePMT(data, offset, mpegSupported, isSampleAes) {
var result = {
audio: -1,
avc: -1,
id3: -1,
isAAC: true
};
var sectionLength = (data[offset + 1] & 0x0f) << 8 | data[offset + 2];
var tableEnd = offset + 3 + sectionLength - 4; // to determine where the table is, we have to figure out how
// long the program info descriptors are
var programInfoLength = (data[offset + 10] & 0x0f) << 8 | data[offset + 11]; // advance the offset to the first entry in the mapping table
offset += 12 + programInfoLength;
while (offset < tableEnd) {
var pid = (data[offset + 1] & 0x1f) << 8 | data[offset + 2];
switch (data[offset]) {
case 0xcf:
// SAMPLE-AES AAC
if (!isSampleAes) {
_utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].log('ADTS AAC with AES-128-CBC frame encryption found in unencrypted stream');
break;
}
/* falls through */
case 0x0f:
// ISO/IEC 13818-7 ADTS AAC (MPEG-2 lower bit-rate audio)
// logger.log('AAC PID:' + pid);
if (result.audio === -1) {
result.audio = pid;
}
break;
// Packetized metadata (ID3)
case 0x15:
// logger.log('ID3 PID:' + pid);
if (result.id3 === -1) {
result.id3 = pid;
}
break;
case 0xdb:
// SAMPLE-AES AVC
if (!isSampleAes) {
_utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].log('H.264 with AES-128-CBC slice encryption found in unencrypted stream');
break;
}
/* falls through */
case 0x1b:
// ITU-T Rec. H.264 and ISO/IEC 14496-10 (lower bit-rate video)
// logger.log('AVC PID:' + pid);
if (result.avc === -1) {
result.avc = pid;
}
break;
// ISO/IEC 11172-3 (MPEG-1 audio)
// or ISO/IEC 13818-3 (MPEG-2 halved sample rate audio)
case 0x03:
case 0x04:
// logger.log('MPEG PID:' + pid);
if (!mpegSupported) {
_utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].log('MPEG audio found, not supported in this browser');
} else if (result.audio === -1) {
result.audio = pid;
result.isAAC = false;
}
break;
case 0x24:
_utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].warn('Unsupported HEVC stream type found');
break;
default:
// logger.log('unknown stream type:' + data[offset]);
break;
} // move to the next table entry
// skip past the elementary stream descriptors, if present
offset += ((data[offset + 3] & 0x0f) << 8 | data[offset + 4]) + 5;
}
return result;
}
function parsePES(stream) {
var i = 0;
var frag;
var pesLen;
var pesHdrLen;
var pesPts;
var pesDts;
var data = stream.data; // safety check
if (!stream || stream.size === 0) {
return null;
} // we might need up to 19 bytes to read PES header
// if first chunk of data is less than 19 bytes, let's merge it with following ones until we get 19 bytes
// usually only one merge is needed (and this is rare ...)
while (data[0].length < 19 && data.length > 1) {
var newData = new Uint8Array(data[0].length + data[1].length);
newData.set(data[0]);
newData.set(data[1], data[0].length);
data[0] = newData;
data.splice(1, 1);
} // retrieve PTS/DTS from first fragment
frag = data[0];
var pesPrefix = (frag[0] << 16) + (frag[1] << 8) + frag[2];
if (pesPrefix === 1) {
pesLen = (frag[4] << 8) + frag[5]; // if PES parsed length is not zero and greater than total received length, stop parsing. PES might be truncated
// minus 6 : PES header size
if (pesLen && pesLen > stream.size - 6) {
return null;
}
var pesFlags = frag[7];
if (pesFlags & 0xc0) {
/* PES header described here : http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
as PTS / DTS is 33 bit we cannot use bitwise operator in JS,
as Bitwise operators treat their operands as a sequence of 32 bits */
pesPts = (frag[9] & 0x0e) * 536870912 + // 1 << 29
(frag[10] & 0xff) * 4194304 + // 1 << 22
(frag[11] & 0xfe) * 16384 + // 1 << 14
(frag[12] & 0xff) * 128 + // 1 << 7
(frag[13] & 0xfe) / 2;
if (pesFlags & 0x40) {
pesDts = (frag[14] & 0x0e) * 536870912 + // 1 << 29
(frag[15] & 0xff) * 4194304 + // 1 << 22
(frag[16] & 0xfe) * 16384 + // 1 << 14
(frag[17] & 0xff) * 128 + // 1 << 7
(frag[18] & 0xfe) / 2;
if (pesPts - pesDts > 60 * 90000) {
_utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].warn(Math.round((pesPts - pesDts) / 90000) + "s delta between PTS and DTS, align them");
pesPts = pesDts;
}
} else {
pesDts = pesPts;
}
}
pesHdrLen = frag[8]; // 9 bytes : 6 bytes for PES header + 3 bytes for PES extension
var payloadStartOffset = pesHdrLen + 9;
if (stream.size <= payloadStartOffset) {
return null;
}
stream.size -= payloadStartOffset; // reassemble PES packet
var pesData = new Uint8Array(stream.size);
for (var j = 0, dataLen = data.length; j < dataLen; j++) {
frag = data[j];
var len = frag.byteLength;
if (payloadStartOffset) {
if (payloadStartOffset > len) {
// trim full frag if PES header bigger than frag
payloadStartOffset -= len;
continue;
} else {
// trim partial frag if PES header smaller than frag
frag = frag.subarray(payloadStartOffset);
len -= payloadStartOffset;
payloadStartOffset = 0;
}
}
pesData.set(frag, i);
i += len;
}
if (pesLen) {
// payload size : remove PES header + PES extension
pesLen -= pesHdrLen + 3;
}
return {
data: pesData,
pts: pesPts,
dts: pesDts,
len: pesLen
};
}
return null;
}
function pushAccessUnit(avcSample, avcTrack) {
if (avcSample.units.length && avcSample.frame) {
// if sample does not have PTS/DTS, patch with last sample PTS/DTS
if (avcSample.pts === undefined) {
var samples = avcTrack.samples;
var nbSamples = samples.length;
if (nbSamples) {
var lastSample = samples[nbSamples - 1];
avcSample.pts = lastSample.pts;
avcSample.dts = lastSample.dts;
} else {
// dropping samples, no timestamp found
avcTrack.dropped++;
return;
}
}
avcTrack.samples.push(avcSample);
}
if (avcSample.debug.length) {
_utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].log(avcSample.pts + '/' + avcSample.dts + ':' + avcSample.debug);
}
}
function insertSampleInOrder(arr, data) {
var len = arr.length;
if (len > 0) {
if (data.pts >= arr[len - 1].pts) {
arr.push(data);
} else {
for (var pos = len - 1; pos >= 0; pos--) {
if (data.pts < arr[pos].pts) {
arr.splice(pos, 0, data);
break;
}
}
}
} else {
arr.push(data);
}
}
/**
* remove Emulation Prevention bytes from a RBSP
*/
function discardEPB(data) {
var length = data.byteLength;
var EPBPositions = [];
var i = 1; // Find all `Emulation Prevention Bytes`
while (i < length - 2) {
if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
EPBPositions.push(i + 2);
i += 2;
} else {
i++;
}
} // If no Emulation Prevention Bytes were found just return the original
// array
if (EPBPositions.length === 0) {
return data;
} // Create a new array to hold the NAL unit data
var newLength = length - EPBPositions.length;
var newData = new Uint8Array(newLength);
var sourceIndex = 0;
for (i = 0; i < newLength; sourceIndex++, i++) {
if (sourceIndex === EPBPositions[0]) {
// Skip this byte
sourceIndex++; // Remove this position index
EPBPositions.shift();
}
newData[i] = data[sourceIndex];
}
return newData;
}
/* harmony default export */ __webpack_exports__["default"] = (TSDemuxer);
/***/ }),
/***/ "./src/errors.ts":
/*!***********************!*\
!*** ./src/errors.ts ***!
\***********************/
/*! exports provided: ErrorTypes, ErrorDetails */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ErrorTypes", function() { return ErrorTypes; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ErrorDetails", function() { return ErrorDetails; });
var ErrorTypes;
/**
* @enum {ErrorDetails}
* @typedef {string} ErrorDetail
*/
(function (ErrorTypes) {
ErrorTypes["NETWORK_ERROR"] = "networkError";
ErrorTypes["MEDIA_ERROR"] = "mediaError";
ErrorTypes["KEY_SYSTEM_ERROR"] = "keySystemError";
ErrorTypes["MUX_ERROR"] = "muxError";
ErrorTypes["OTHER_ERROR"] = "otherError";
})(ErrorTypes || (ErrorTypes = {}));
var ErrorDetails;
(function (ErrorDetails) {
ErrorDetails["KEY_SYSTEM_NO_KEYS"] = "keySystemNoKeys";
ErrorDetails["KEY_SYSTEM_NO_ACCESS"] = "keySystemNoAccess";
ErrorDetails["KEY_SYSTEM_NO_SESSION"] = "keySystemNoSession";
ErrorDetails["KEY_SYSTEM_LICENSE_REQUEST_FAILED"] = "keySystemLicenseRequestFailed";
ErrorDetails["KEY_SYSTEM_NO_INIT_DATA"] = "keySystemNoInitData";
ErrorDetails["MANIFEST_LOAD_ERROR"] = "manifestLoadError";
ErrorDetails["MANIFEST_LOAD_TIMEOUT"] = "manifestLoadTimeOut";
ErrorDetails["MANIFEST_PARSING_ERROR"] = "manifestParsingError";
ErrorDetails["MANIFEST_INCOMPATIBLE_CODECS_ERROR"] = "manifestIncompatibleCodecsError";
ErrorDetails["LEVEL_EMPTY_ERROR"] = "levelEmptyError";
ErrorDetails["LEVEL_LOAD_ERROR"] = "levelLoadError";
ErrorDetails["LEVEL_LOAD_TIMEOUT"] = "levelLoadTimeOut";
ErrorDetails["LEVEL_SWITCH_ERROR"] = "levelSwitchError";
ErrorDetails["AUDIO_TRACK_LOAD_ERROR"] = "audioTrackLoadError";
ErrorDetails["AUDIO_TRACK_LOAD_TIMEOUT"] = "audioTrackLoadTimeOut";
ErrorDetails["SUBTITLE_LOAD_ERROR"] = "subtitleTrackLoadError";
ErrorDetails["SUBTITLE_TRACK_LOAD_TIMEOUT"] = "subtitleTrackLoadTimeOut";
ErrorDetails["FRAG_LOAD_ERROR"] = "fragLoadError";
ErrorDetails["FRAG_LOAD_TIMEOUT"] = "fragLoadTimeOut";
ErrorDetails["FRAG_DECRYPT_ERROR"] = "fragDecryptError";
ErrorDetails["FRAG_PARSING_ERROR"] = "fragParsingError";
ErrorDetails["REMUX_ALLOC_ERROR"] = "remuxAllocError";
ErrorDetails["KEY_LOAD_ERROR"] = "keyLoadError";
ErrorDetails["KEY_LOAD_TIMEOUT"] = "keyLoadTimeOut";
ErrorDetails["BUFFER_ADD_CODEC_ERROR"] = "bufferAddCodecError";
ErrorDetails["BUFFER_INCOMPATIBLE_CODECS_ERROR"] = "bufferIncompatibleCodecsError";
ErrorDetails["BUFFER_APPEND_ERROR"] = "bufferAppendError";
ErrorDetails["BUFFER_APPENDING_ERROR"] = "bufferAppendingError";
ErrorDetails["BUFFER_STALLED_ERROR"] = "bufferStalledError";
ErrorDetails["BUFFER_FULL_ERROR"] = "bufferFullError";
ErrorDetails["BUFFER_SEEK_OVER_HOLE"] = "bufferSeekOverHole";
ErrorDetails["BUFFER_NUDGE_ON_STALL"] = "bufferNudgeOnStall";
ErrorDetails["INTERNAL_EXCEPTION"] = "internalException";
ErrorDetails["INTERNAL_ABORTED"] = "aborted";
ErrorDetails["UNKNOWN"] = "unknown";
})(ErrorDetails || (ErrorDetails = {}));
/***/ }),
/***/ "./src/events.ts":
/*!***********************!*\
!*** ./src/events.ts ***!
\***********************/
/*! exports provided: Events */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Events", function() { return Events; });
/**
* @readonly
* @enum {string}
*/
var Events;
(function (Events) {
Events["MEDIA_ATTACHING"] = "hlsMediaAttaching";
Events["MEDIA_ATTACHED"] = "hlsMediaAttached";
Events["MEDIA_DETACHING"] = "hlsMediaDetaching";
Events["MEDIA_DETACHED"] = "hlsMediaDetached";
Events["BUFFER_RESET"] = "hlsBufferReset";
Events["BUFFER_CODECS"] = "hlsBufferCodecs";
Events["BUFFER_CREATED"] = "hlsBufferCreated";
Events["BUFFER_APPENDING"] = "hlsBufferAppending";
Events["BUFFER_APPENDED"] = "hlsBufferAppended";
Events["BUFFER_EOS"] = "hlsBufferEos";
Events["BUFFER_FLUSHING"] = "hlsBufferFlushing";
Events["BUFFER_FLUSHED"] = "hlsBufferFlushed";
Events["MANIFEST_LOADING"] = "hlsManifestLoading";
Events["MANIFEST_LOADED"] = "hlsManifestLoaded";
Events["MANIFEST_PARSED"] = "hlsManifestParsed";
Events["LEVEL_SWITCHING"] = "hlsLevelSwitching";
Events["LEVEL_SWITCHED"] = "hlsLevelSwitched";
Events["LEVEL_LOADING"] = "hlsLevelLoading";
Events["LEVEL_LOADED"] = "hlsLevelLoaded";
Events["LEVEL_UPDATED"] = "hlsLevelUpdated";
Events["LEVEL_PTS_UPDATED"] = "hlsLevelPtsUpdated";
Events["LEVELS_UPDATED"] = "hlsLevelsUpdated";
Events["AUDIO_TRACKS_UPDATED"] = "hlsAudioTracksUpdated";
Events["AUDIO_TRACK_SWITCHING"] = "hlsAudioTrackSwitching";
Events["AUDIO_TRACK_SWITCHED"] = "hlsAudioTrackSwitched";
Events["AUDIO_TRACK_LOADING"] = "hlsAudioTrackLoading";
Events["AUDIO_TRACK_LOADED"] = "hlsAudioTrackLoaded";
Events["SUBTITLE_TRACKS_UPDATED"] = "hlsSubtitleTracksUpdated";
Events["SUBTITLE_TRACKS_CLEARED"] = "hlsSubtitleTracksCleared";
Events["SUBTITLE_TRACK_SWITCH"] = "hlsSubtitleTrackSwitch";
Events["SUBTITLE_TRACK_LOADING"] = "hlsSubtitleTrackLoading";
Events["SUBTITLE_TRACK_LOADED"] = "hlsSubtitleTrackLoaded";
Events["SUBTITLE_FRAG_PROCESSED"] = "hlsSubtitleFragProcessed";
Events["CUES_PARSED"] = "hlsCuesParsed";
Events["NON_NATIVE_TEXT_TRACKS_FOUND"] = "hlsNonNativeTextTracksFound";
Events["INIT_PTS_FOUND"] = "hlsInitPtsFound";
Events["FRAG_LOADING"] = "hlsFragLoading";
Events["FRAG_LOAD_EMERGENCY_ABORTED"] = "hlsFragLoadEmergencyAborted";
Events["FRAG_LOADED"] = "hlsFragLoaded";
Events["FRAG_DECRYPTED"] = "hlsFragDecrypted";
Events["FRAG_PARSING_INIT_SEGMENT"] = "hlsFragParsingInitSegment";
Events["FRAG_PARSING_USERDATA"] = "hlsFragParsingUserdata";
Events["FRAG_PARSING_METADATA"] = "hlsFragParsingMetadata";
Events["FRAG_PARSED"] = "hlsFragParsed";
Events["FRAG_BUFFERED"] = "hlsFragBuffered";
Events["FRAG_CHANGED"] = "hlsFragChanged";
Events["FPS_DROP"] = "hlsFpsDrop";
Events["FPS_DROP_LEVEL_CAPPING"] = "hlsFpsDropLevelCapping";
Events["ERROR"] = "hlsError";
Events["DESTROYING"] = "hlsDestroying";
Events["KEY_LOADING"] = "hlsKeyLoading";
Events["KEY_LOADED"] = "hlsKeyLoaded";
Events["LIVE_BACK_BUFFER_REACHED"] = "hlsLiveBackBufferReached";
Events["BACK_BUFFER_REACHED"] = "hlsBackBufferReached";
})(Events || (Events = {}));
/***/ }),
/***/ "./src/hls.ts":
/*!********************!*\
!*** ./src/hls.ts ***!
\********************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Hls; });
/* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! url-toolkit */ "./node_modules/url-toolkit/src/url-toolkit.js");
/* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(url_toolkit__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./errors */ "./src/errors.ts");
/* harmony import */ var _loader_playlist_loader__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./loader/playlist-loader */ "./src/loader/playlist-loader.ts");
/* harmony import */ var _loader_key_loader__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./loader/key-loader */ "./src/loader/key-loader.ts");
/* harmony import */ var _controller_fragment_tracker__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./controller/fragment-tracker */ "./src/controller/fragment-tracker.ts");
/* harmony import */ var _controller_stream_controller__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./controller/stream-controller */ "./src/controller/stream-controller.ts");
/* harmony import */ var _controller_level_controller__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./controller/level-controller */ "./src/controller/level-controller.ts");
/* harmony import */ var _is_supported__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./is-supported */ "./src/is-supported.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./utils/logger */ "./src/utils/logger.ts");
/* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./config */ "./src/config.ts");
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./events */ "./src/events.ts");
/* harmony import */ var eventemitter3__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! eventemitter3 */ "./node_modules/eventemitter3/index.js");
/* harmony import */ var eventemitter3__WEBPACK_IMPORTED_MODULE_11___default = /*#__PURE__*/__webpack_require__.n(eventemitter3__WEBPACK_IMPORTED_MODULE_11__);
/* harmony import */ var _controller_id3_track_controller__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./controller/id3-track-controller */ "./src/controller/id3-track-controller.ts");
/* harmony import */ var _controller_latency_controller__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./controller/latency-controller */ "./src/controller/latency-controller.ts");
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
/**
* @module Hls
* @class
* @constructor
*/
var Hls = /*#__PURE__*/function () {
Hls.isSupported = function isSupported() {
return Object(_is_supported__WEBPACK_IMPORTED_MODULE_7__["isSupported"])();
};
/**
* Creates an instance of an HLS client that can attach to exactly one `HTMLMediaElement`.
*
* @constructs Hls
* @param {HlsConfig} config
*/
function Hls(userConfig) {
if (userConfig === void 0) {
userConfig = {};
}
this.config = void 0;
this.userConfig = void 0;
this.coreComponents = void 0;
this.networkControllers = void 0;
this._emitter = new eventemitter3__WEBPACK_IMPORTED_MODULE_11__["EventEmitter"]();
this._autoLevelCapping = void 0;
this.abrController = void 0;
this.capLevelController = void 0;
this.latencyController = void 0;
this.levelController = void 0;
this.streamController = void 0;
this.audioTrackController = void 0;
this.subtitleTrackController = void 0;
this.emeController = void 0;
this._media = null;
this.url = null;
var config = this.config = Object(_config__WEBPACK_IMPORTED_MODULE_9__["mergeConfig"])(Hls.DefaultConfig, userConfig);
this.userConfig = userConfig;
Object(_utils_logger__WEBPACK_IMPORTED_MODULE_8__["enableLogs"])(config.debug);
this._autoLevelCapping = -1;
if (config.progressive) {
Object(_config__WEBPACK_IMPORTED_MODULE_9__["enableStreamingMode"])(config);
} // core controllers and network loaders
var abrController = this.abrController = new config.abrController(this); // eslint-disable-line new-cap
var bufferController = new config.bufferController(this); // eslint-disable-line new-cap
var capLevelController = this.capLevelController = new config.capLevelController(this); // eslint-disable-line new-cap
var fpsController = new config.fpsController(this); // eslint-disable-line new-cap
var playListLoader = new _loader_playlist_loader__WEBPACK_IMPORTED_MODULE_2__["default"](this);
var keyLoader = new _loader_key_loader__WEBPACK_IMPORTED_MODULE_3__["default"](this);
var id3TrackController = new _controller_id3_track_controller__WEBPACK_IMPORTED_MODULE_12__["default"](this); // network controllers
var levelController = this.levelController = new _controller_level_controller__WEBPACK_IMPORTED_MODULE_6__["default"](this); // FragmentTracker must be defined before StreamController because the order of event handling is important
var fragmentTracker = new _controller_fragment_tracker__WEBPACK_IMPORTED_MODULE_4__["FragmentTracker"](this);
var streamController = this.streamController = new _controller_stream_controller__WEBPACK_IMPORTED_MODULE_5__["default"](this, fragmentTracker); // Cap level controller uses streamController to flush the buffer
capLevelController.setStreamController(streamController); // fpsController uses streamController to switch when frames are being dropped
fpsController.setStreamController(streamController);
var networkControllers = [levelController, streamController];
this.networkControllers = networkControllers;
var coreComponents = [playListLoader, keyLoader, abrController, bufferController, capLevelController, fpsController, id3TrackController, fragmentTracker];
this.audioTrackController = this.createController(config.audioTrackController, null, networkControllers);
this.createController(config.audioStreamController, fragmentTracker, networkControllers); // subtitleTrackController must be defined before because the order of event handling is important
this.subtitleTrackController = this.createController(config.subtitleTrackController, null, networkControllers);
this.createController(config.subtitleStreamController, fragmentTracker, networkControllers);
this.createController(config.timelineController, null, coreComponents);
this.emeController = this.createController(config.emeController, null, coreComponents);
this.latencyController = this.createController(_controller_latency_controller__WEBPACK_IMPORTED_MODULE_13__["default"], null, coreComponents);
this.coreComponents = coreComponents;
}
var _proto = Hls.prototype;
_proto.createController = function createController(ControllerClass, fragmentTracker, components) {
if (ControllerClass) {
var controllerInstance = fragmentTracker ? new ControllerClass(this, fragmentTracker) : new ControllerClass(this);
if (components) {
components.push(controllerInstance);
}
return controllerInstance;
}
return null;
} // Delegate the EventEmitter through the public API of Hls.js
;
_proto.on = function on(event, listener, context) {
if (context === void 0) {
context = this;
}
this._emitter.on(event, listener, context);
};
_proto.once = function once(event, listener, context) {
if (context === void 0) {
context = this;
}
this._emitter.once(event, listener, context);
};
_proto.removeAllListeners = function removeAllListeners(event) {
this._emitter.removeAllListeners(event);
};
_proto.off = function off(event, listener, context, once) {
if (context === void 0) {
context = this;
}
this._emitter.off(event, listener, context, once);
};
_proto.listeners = function listeners(event) {
return this._emitter.listeners(event);
};
_proto.emit = function emit(event, name, eventObject) {
return this._emitter.emit(event, name, eventObject);
};
_proto.trigger = function trigger(event, eventObject) {
if (this.config.debug) {
return this.emit(event, event, eventObject);
} else {
try {
return this.emit(event, event, eventObject);
} catch (e) {
_utils_logger__WEBPACK_IMPORTED_MODULE_8__["logger"].error('An internal error happened while handling event ' + event + '. Error message: "' + e.message + '". Here is a stacktrace:', e);
this.trigger(_events__WEBPACK_IMPORTED_MODULE_10__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].OTHER_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].INTERNAL_EXCEPTION,
fatal: false,
event: event,
error: e
});
}
}
return false;
};
_proto.listenerCount = function listenerCount(event) {
return this._emitter.listenerCount(event);
}
/**
* Dispose of the instance
*/
;
_proto.destroy = function destroy() {
_utils_logger__WEBPACK_IMPORTED_MODULE_8__["logger"].log('destroy');
this.trigger(_events__WEBPACK_IMPORTED_MODULE_10__["Events"].DESTROYING, undefined);
this.detachMedia();
this.removeAllListeners();
this._autoLevelCapping = -1;
this.url = null;
if (this.networkControllers) {
this.networkControllers.forEach(function (component) {
return component.destroy();
}); // @ts-ignore
this.networkControllers = null;
}
if (this.coreComponents) {
this.coreComponents.forEach(function (component) {
return component.destroy();
}); // @ts-ignore
this.coreComponents = null;
}
}
/**
* Attaches Hls.js to a media element
* @param {HTMLMediaElement} media
*/
;
_proto.attachMedia = function attachMedia(media) {
_utils_logger__WEBPACK_IMPORTED_MODULE_8__["logger"].log('attachMedia');
this._media = media;
this.trigger(_events__WEBPACK_IMPORTED_MODULE_10__["Events"].MEDIA_ATTACHING, {
media: media
});
}
/**
* Detach Hls.js from the media
*/
;
_proto.detachMedia = function detachMedia() {
_utils_logger__WEBPACK_IMPORTED_MODULE_8__["logger"].log('detachMedia');
this.trigger(_events__WEBPACK_IMPORTED_MODULE_10__["Events"].MEDIA_DETACHING, undefined);
this._media = null;
}
/**
* Set the source URL. Can be relative or absolute.
* @param {string} url
*/
;
_proto.loadSource = function loadSource(url) {
this.stopLoad();
var media = this.media;
if (media && this.url) {
this.detachMedia();
this.attachMedia(media);
}
url = url_toolkit__WEBPACK_IMPORTED_MODULE_0__["buildAbsoluteURL"](self.location.href, url, {
alwaysNormalize: true
});
_utils_logger__WEBPACK_IMPORTED_MODULE_8__["logger"].log("loadSource:" + url);
this.url = url; // when attaching to a source URL, trigger a playlist load
this.trigger(_events__WEBPACK_IMPORTED_MODULE_10__["Events"].MANIFEST_LOADING, {
url: url
});
}
/**
* Start loading data from the stream source.
* Depending on default config, client starts loading automatically when a source is set.
*
* @param {number} startPosition Set the start position to stream from
* @default -1 None (from earliest point)
*/
;
_proto.startLoad = function startLoad(startPosition) {
if (startPosition === void 0) {
startPosition = -1;
}
_utils_logger__WEBPACK_IMPORTED_MODULE_8__["logger"].log("startLoad(" + startPosition + ")");
this.networkControllers.forEach(function (controller) {
controller.startLoad(startPosition);
});
}
/**
* Stop loading of any stream data.
*/
;
_proto.stopLoad = function stopLoad() {
_utils_logger__WEBPACK_IMPORTED_MODULE_8__["logger"].log('stopLoad');
this.networkControllers.forEach(function (controller) {
controller.stopLoad();
});
}
/**
* Swap through possible audio codecs in the stream (for example to switch from stereo to 5.1)
*/
;
_proto.swapAudioCodec = function swapAudioCodec() {
_utils_logger__WEBPACK_IMPORTED_MODULE_8__["logger"].log('swapAudioCodec');
this.streamController.swapAudioCodec();
}
/**
* When the media-element fails, this allows to detach and then re-attach it
* as one call (convenience method).
*
* Automatic recovery of media-errors by this process is configurable.
*/
;
_proto.recoverMediaError = function recoverMediaError() {
_utils_logger__WEBPACK_IMPORTED_MODULE_8__["logger"].log('recoverMediaError');
var media = this._media;
this.detachMedia();
if (media) {
this.attachMedia(media);
}
};
_proto.removeLevel = function removeLevel(levelIndex, urlId) {
if (urlId === void 0) {
urlId = 0;
}
this.levelController.removeLevel(levelIndex, urlId);
}
/**
* @type {Level[]}
*/
;
_createClass(Hls, [{
key: "levels",
get: function get() {
var levels = this.levelController.levels;
return levels ? levels : [];
}
/**
* Index of quality level currently played
* @type {number}
*/
}, {
key: "currentLevel",
get: function get() {
return this.streamController.currentLevel;
}
/**
* Set quality level index immediately .
* This will flush the current buffer to replace the quality asap.
* That means playback will interrupt at least shortly to re-buffer and re-sync eventually.
* @type {number} -1 for automatic level selection
*/
,
set: function set(newLevel) {
_utils_logger__WEBPACK_IMPORTED_MODULE_8__["logger"].log("set currentLevel:" + newLevel);
this.loadLevel = newLevel;
this.abrController.clearTimer();
this.streamController.immediateLevelSwitch();
}
/**
* Index of next quality level loaded as scheduled by stream controller.
* @type {number}
*/
}, {
key: "nextLevel",
get: function get() {
return this.streamController.nextLevel;
}
/**
* Set quality level index for next loaded data.
* This will switch the video quality asap, without interrupting playback.
* May abort current loading of data, and flush parts of buffer (outside currently played fragment region).
* @type {number} -1 for automatic level selection
*/
,
set: function set(newLevel) {
_utils_logger__WEBPACK_IMPORTED_MODULE_8__["logger"].log("set nextLevel:" + newLevel);
this.levelController.manualLevel = newLevel;
this.streamController.nextLevelSwitch();
}
/**
* Return the quality level of the currently or last (of none is loaded currently) segment
* @type {number}
*/
}, {
key: "loadLevel",
get: function get() {
return this.levelController.level;
}
/**
* Set quality level index for next loaded data in a conservative way.
* This will switch the quality without flushing, but interrupt current loading.
* Thus the moment when the quality switch will appear in effect will only be after the already existing buffer.
* @type {number} newLevel -1 for automatic level selection
*/
,
set: function set(newLevel) {
_utils_logger__WEBPACK_IMPORTED_MODULE_8__["logger"].log("set loadLevel:" + newLevel);
this.levelController.manualLevel = newLevel;
}
/**
* get next quality level loaded
* @type {number}
*/
}, {
key: "nextLoadLevel",
get: function get() {
return this.levelController.nextLoadLevel;
}
/**
* Set quality level of next loaded segment in a fully "non-destructive" way.
* Same as `loadLevel` but will wait for next switch (until current loading is done).
* @type {number} level
*/
,
set: function set(level) {
this.levelController.nextLoadLevel = level;
}
/**
* Return "first level": like a default level, if not set,
* falls back to index of first level referenced in manifest
* @type {number}
*/
}, {
key: "firstLevel",
get: function get() {
return Math.max(this.levelController.firstLevel, this.minAutoLevel);
}
/**
* Sets "first-level", see getter.
* @type {number}
*/
,
set: function set(newLevel) {
_utils_logger__WEBPACK_IMPORTED_MODULE_8__["logger"].log("set firstLevel:" + newLevel);
this.levelController.firstLevel = newLevel;
}
/**
* Return start level (level of first fragment that will be played back)
* if not overrided by user, first level appearing in manifest will be used as start level
* if -1 : automatic start level selection, playback will start from level matching download bandwidth
* (determined from download of first segment)
* @type {number}
*/
}, {
key: "startLevel",
get: function get() {
return this.levelController.startLevel;
}
/**
* set start level (level of first fragment that will be played back)
* if not overrided by user, first level appearing in manifest will be used as start level
* if -1 : automatic start level selection, playback will start from level matching download bandwidth
* (determined from download of first segment)
* @type {number} newLevel
*/
,
set: function set(newLevel) {
_utils_logger__WEBPACK_IMPORTED_MODULE_8__["logger"].log("set startLevel:" + newLevel); // if not in automatic start level detection, ensure startLevel is greater than minAutoLevel
if (newLevel !== -1) {
newLevel = Math.max(newLevel, this.minAutoLevel);
}
this.levelController.startLevel = newLevel;
}
/**
* Get the current setting for capLevelToPlayerSize
*
* @type {boolean}
*/
}, {
key: "capLevelToPlayerSize",
get: function get() {
return this.config.capLevelToPlayerSize;
}
/**
* set dynamically set capLevelToPlayerSize against (`CapLevelController`)
*
* @type {boolean}
*/
,
set: function set(shouldStartCapping) {
var newCapLevelToPlayerSize = !!shouldStartCapping;
if (newCapLevelToPlayerSize !== this.config.capLevelToPlayerSize) {
if (newCapLevelToPlayerSize) {
this.capLevelController.startCapping(); // If capping occurs, nextLevelSwitch will happen based on size.
} else {
this.capLevelController.stopCapping();
this.autoLevelCapping = -1;
this.streamController.nextLevelSwitch(); // Now we're uncapped, get the next level asap.
}
this.config.capLevelToPlayerSize = newCapLevelToPlayerSize;
}
}
/**
* Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)
* @type {number}
*/
}, {
key: "autoLevelCapping",
get: function get() {
return this._autoLevelCapping;
}
/**
* get bandwidth estimate
* @type {number}
*/
,
set:
/**
* Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)
* @type {number}
*/
function set(newLevel) {
if (this._autoLevelCapping !== newLevel) {
_utils_logger__WEBPACK_IMPORTED_MODULE_8__["logger"].log("set autoLevelCapping:" + newLevel);
this._autoLevelCapping = newLevel;
}
}
/**
* True when automatic level selection enabled
* @type {boolean}
*/
}, {
key: "bandwidthEstimate",
get: function get() {
var bwEstimator = this.abrController.bwEstimator;
if (!bwEstimator) {
return NaN;
}
return bwEstimator.getEstimate();
}
}, {
key: "autoLevelEnabled",
get: function get() {
return this.levelController.manualLevel === -1;
}
/**
* Level set manually (if any)
* @type {number}
*/
}, {
key: "manualLevel",
get: function get() {
return this.levelController.manualLevel;
}
/**
* min level selectable in auto mode according to config.minAutoBitrate
* @type {number}
*/
}, {
key: "minAutoLevel",
get: function get() {
var levels = this.levels,
minAutoBitrate = this.config.minAutoBitrate;
if (!levels) return 0;
var len = levels.length;
for (var i = 0; i < len; i++) {
if (levels[i].maxBitrate > minAutoBitrate) {
return i;
}
}
return 0;
}
/**
* max level selectable in auto mode according to autoLevelCapping
* @type {number}
*/
}, {
key: "maxAutoLevel",
get: function get() {
var levels = this.levels,
autoLevelCapping = this.autoLevelCapping;
var maxAutoLevel;
if (autoLevelCapping === -1 && levels && levels.length) {
maxAutoLevel = levels.length - 1;
} else {
maxAutoLevel = autoLevelCapping;
}
return maxAutoLevel;
}
/**
* next automatically selected quality level
* @type {number}
*/
}, {
key: "nextAutoLevel",
get: function get() {
// ensure next auto level is between min and max auto level
return Math.min(Math.max(this.abrController.nextAutoLevel, this.minAutoLevel), this.maxAutoLevel);
}
/**
* this setter is used to force next auto level.
* this is useful to force a switch down in auto mode:
* in case of load error on level N, hls.js can set nextAutoLevel to N-1 for example)
* forced value is valid for one fragment. upon succesful frag loading at forced level,
* this value will be resetted to -1 by ABR controller.
* @type {number}
*/
,
set: function set(nextLevel) {
this.abrController.nextAutoLevel = Math.max(this.minAutoLevel, nextLevel);
}
/**
* @type {AudioTrack[]}
*/
}, {
key: "audioTracks",
get: function get() {
var audioTrackController = this.audioTrackController;
return audioTrackController ? audioTrackController.audioTracks : [];
}
/**
* index of the selected audio track (index in audio track lists)
* @type {number}
*/
}, {
key: "audioTrack",
get: function get() {
var audioTrackController = this.audioTrackController;
return audioTrackController ? audioTrackController.audioTrack : -1;
}
/**
* selects an audio track, based on its index in audio track lists
* @type {number}
*/
,
set: function set(audioTrackId) {
var audioTrackController = this.audioTrackController;
if (audioTrackController) {
audioTrackController.audioTrack = audioTrackId;
}
}
/**
* get alternate subtitle tracks list from playlist
* @type {MediaPlaylist[]}
*/
}, {
key: "subtitleTracks",
get: function get() {
var subtitleTrackController = this.subtitleTrackController;
return subtitleTrackController ? subtitleTrackController.subtitleTracks : [];
}
/**
* index of the selected subtitle track (index in subtitle track lists)
* @type {number}
*/
}, {
key: "subtitleTrack",
get: function get() {
var subtitleTrackController = this.subtitleTrackController;
return subtitleTrackController ? subtitleTrackController.subtitleTrack : -1;
},
set:
/**
* select an subtitle track, based on its index in subtitle track lists
* @type {number}
*/
function set(subtitleTrackId) {
var subtitleTrackController = this.subtitleTrackController;
if (subtitleTrackController) {
subtitleTrackController.subtitleTrack = subtitleTrackId;
}
}
/**
* @type {boolean}
*/
}, {
key: "media",
get: function get() {
return this._media;
}
}, {
key: "subtitleDisplay",
get: function get() {
var subtitleTrackController = this.subtitleTrackController;
return subtitleTrackController ? subtitleTrackController.subtitleDisplay : false;
}
/**
* Enable/disable subtitle display rendering
* @type {boolean}
*/
,
set: function set(value) {
var subtitleTrackController = this.subtitleTrackController;
if (subtitleTrackController) {
subtitleTrackController.subtitleDisplay = value;
}
}
/**
* get mode for Low-Latency HLS loading
* @type {boolean}
*/
}, {
key: "lowLatencyMode",
get: function get() {
return this.config.lowLatencyMode;
}
/**
* Enable/disable Low-Latency HLS part playlist and segment loading, and start live streams at playlist PART-HOLD-BACK rather than HOLD-BACK.
* @type {boolean}
*/
,
set: function set(mode) {
this.config.lowLatencyMode = mode;
}
/**
* position (in seconds) of live sync point (ie edge of live position minus safety delay defined by ```hls.config.liveSyncDuration```)
* @type {number}
*/
}, {
key: "liveSyncPosition",
get: function get() {
return this.latencyController.liveSyncPosition;
}
/**
* estimated position (in seconds) of live edge (ie edge of live playlist plus time sync playlist advanced)
* returns 0 before first playlist is loaded
* @type {number}
*/
}, {
key: "latency",
get: function get() {
return this.latencyController.latency;
}
/**
* maximum distance from the edge before the player seeks forward to ```hls.liveSyncPosition```
* configured using ```liveMaxLatencyDurationCount``` (multiple of target duration) or ```liveMaxLatencyDuration```
* returns 0 before first playlist is loaded
* @type {number}
*/
}, {
key: "maxLatency",
get: function get() {
return this.latencyController.maxLatency;
}
/**
* target distance from the edge as calculated by the latency controller
* @type {number}
*/
}, {
key: "targetLatency",
get: function get() {
return this.latencyController.targetLatency;
}
/**
* set to true when startLoad is called before MANIFEST_PARSED event
* @type {boolean}
*/
}, {
key: "forceStartLoad",
get: function get() {
return this.streamController.forceStartLoad;
}
}], [{
key: "version",
get: function get() {
return "1.0.0-rc.5.0.canary.7022";
}
}, {
key: "Events",
get: function get() {
return _events__WEBPACK_IMPORTED_MODULE_10__["Events"];
}
}, {
key: "ErrorTypes",
get: function get() {
return _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"];
}
}, {
key: "ErrorDetails",
get: function get() {
return _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"];
}
}, {
key: "DefaultConfig",
get: function get() {
if (!Hls.defaultConfig) {
return _config__WEBPACK_IMPORTED_MODULE_9__["hlsDefaultConfig"];
}
return Hls.defaultConfig;
}
/**
* @type {HlsConfig}
*/
,
set: function set(defaultConfig) {
Hls.defaultConfig = defaultConfig;
}
}]);
return Hls;
}();
Hls.defaultConfig = void 0;
/***/ }),
/***/ "./src/is-supported.ts":
/*!*****************************!*\
!*** ./src/is-supported.ts ***!
\*****************************/
/*! exports provided: isSupported, changeTypeSupported */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isSupported", function() { return isSupported; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "changeTypeSupported", function() { return changeTypeSupported; });
/* harmony import */ var _utils_mediasource_helper__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utils/mediasource-helper */ "./src/utils/mediasource-helper.ts");
function getSourceBuffer() {
return self.SourceBuffer || self.WebKitSourceBuffer;
}
function isSupported() {
var mediaSource = Object(_utils_mediasource_helper__WEBPACK_IMPORTED_MODULE_0__["getMediaSource"])();
if (!mediaSource) {
return false;
}
var sourceBuffer = getSourceBuffer();
var isTypeSupported = mediaSource && typeof mediaSource.isTypeSupported === 'function' && mediaSource.isTypeSupported('video/mp4; codecs="avc1.42E01E,mp4a.40.2"'); // if SourceBuffer is exposed ensure its API is valid
// safari and old version of Chrome doe not expose SourceBuffer globally so checking SourceBuffer.prototype is impossible
var sourceBufferValidAPI = !sourceBuffer || sourceBuffer.prototype && typeof sourceBuffer.prototype.appendBuffer === 'function' && typeof sourceBuffer.prototype.remove === 'function';
return !!isTypeSupported && !!sourceBufferValidAPI;
}
function changeTypeSupported() {
var _sourceBuffer$prototy;
var sourceBuffer = getSourceBuffer();
return typeof (sourceBuffer === null || sourceBuffer === void 0 ? void 0 : (_sourceBuffer$prototy = sourceBuffer.prototype) === null || _sourceBuffer$prototy === void 0 ? void 0 : _sourceBuffer$prototy.changeType) === 'function';
}
/***/ }),
/***/ "./src/loader/fragment-loader.ts":
/*!***************************************!*\
!*** ./src/loader/fragment-loader.ts ***!
\***************************************/
/*! exports provided: default, LoadError */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return FragmentLoader; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LoadError", function() { return LoadError; });
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); }
function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
var MIN_CHUNK_SIZE = Math.pow(2, 17); // 128kb
var FragmentLoader = /*#__PURE__*/function () {
function FragmentLoader(config) {
this.config = void 0;
this.loader = null;
this.partLoadTimeout = -1;
this.config = config;
}
var _proto = FragmentLoader.prototype;
_proto.destroy = function destroy() {
if (this.loader) {
this.loader.destroy();
this.loader = null;
}
};
_proto.abort = function abort() {
if (this.loader) {
// Abort the loader for current fragment. Only one may load at any given time
this.loader.abort();
}
};
_proto.load = function load(frag, _onProgress) {
var _this = this;
var url = frag.url;
if (!url) {
return Promise.reject(new LoadError({
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].NETWORK_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].FRAG_LOAD_ERROR,
fatal: false,
frag: frag,
networkDetails: null
}, "Fragment does not have a " + (url ? 'part list' : 'url')));
}
this.abort();
var config = this.config;
var FragmentILoader = config.fLoader;
var DefaultILoader = config.loader;
return new Promise(function (resolve, reject) {
if (_this.loader) {
_this.loader.destroy();
}
var loader = _this.loader = frag.loader = FragmentILoader ? new FragmentILoader(config) : new DefaultILoader(config);
var loaderContext = createLoaderContext(frag);
var loaderConfig = {
timeout: config.fragLoadingTimeOut,
maxRetry: 0,
retryDelay: 0,
maxRetryDelay: config.fragLoadingMaxRetryTimeout,
highWaterMark: MIN_CHUNK_SIZE
}; // Assign frag stats to the loader's stats reference
frag.stats = loader.stats;
loader.load(loaderContext, loaderConfig, {
onSuccess: function onSuccess(response, stats, context, networkDetails) {
_this.resetLoader(frag, loader);
resolve({
frag: frag,
part: null,
payload: response.data,
networkDetails: networkDetails
});
},
onError: function onError(response, context, networkDetails) {
_this.resetLoader(frag, loader);
reject(new LoadError({
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].NETWORK_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].FRAG_LOAD_ERROR,
fatal: false,
frag: frag,
response: response,
networkDetails: networkDetails
}));
},
onAbort: function onAbort(stats, context, networkDetails) {
_this.resetLoader(frag, loader);
reject(new LoadError({
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].NETWORK_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].INTERNAL_ABORTED,
fatal: false,
frag: frag,
networkDetails: networkDetails
}));
},
onTimeout: function onTimeout(response, context, networkDetails) {
_this.resetLoader(frag, loader);
reject(new LoadError({
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].NETWORK_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].FRAG_LOAD_TIMEOUT,
fatal: false,
frag: frag,
networkDetails: networkDetails
}));
},
onProgress: function onProgress(stats, context, data, networkDetails) {
if (_onProgress) {
_onProgress({
frag: frag,
part: null,
payload: data,
networkDetails: networkDetails
});
}
}
});
});
};
_proto.loadPart = function loadPart(frag, part, onProgress) {
var _this2 = this;
this.abort();
var config = this.config;
var FragmentILoader = config.fLoader;
var DefaultILoader = config.loader;
return new Promise(function (resolve, reject) {
if (_this2.loader) {
_this2.loader.destroy();
}
var loader = _this2.loader = frag.loader = FragmentILoader ? new FragmentILoader(config) : new DefaultILoader(config);
var loaderContext = createLoaderContext(frag, part);
var loaderConfig = {
timeout: config.fragLoadingTimeOut,
maxRetry: 0,
retryDelay: 0,
maxRetryDelay: config.fragLoadingMaxRetryTimeout,
highWaterMark: MIN_CHUNK_SIZE
}; // Assign part stats to the loader's stats reference
part.stats = loader.stats;
loader.load(loaderContext, loaderConfig, {
onSuccess: function onSuccess(response, stats, context, networkDetails) {
_this2.resetLoader(frag, loader);
_this2.updateStatsFromPart(frag, part);
var partLoadedData = {
frag: frag,
part: part,
payload: response.data,
networkDetails: networkDetails
};
onProgress(partLoadedData);
resolve(partLoadedData);
},
onError: function onError(response, context, networkDetails) {
_this2.resetLoader(frag, loader);
reject(new LoadError({
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].NETWORK_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].FRAG_LOAD_ERROR,
fatal: false,
frag: frag,
part: part,
response: response,
networkDetails: networkDetails
}));
},
onAbort: function onAbort(stats, context, networkDetails) {
frag.stats.aborted = part.stats.aborted;
_this2.resetLoader(frag, loader);
reject(new LoadError({
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].NETWORK_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].INTERNAL_ABORTED,
fatal: false,
frag: frag,
part: part,
networkDetails: networkDetails
}));
},
onTimeout: function onTimeout(response, context, networkDetails) {
_this2.resetLoader(frag, loader);
reject(new LoadError({
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].NETWORK_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].FRAG_LOAD_TIMEOUT,
fatal: false,
frag: frag,
part: part,
networkDetails: networkDetails
}));
}
});
});
};
_proto.updateStatsFromPart = function updateStatsFromPart(frag, part) {
var fragStats = frag.stats;
var partStats = part.stats;
var partTotal = partStats.total;
fragStats.loaded += partStats.loaded;
if (partTotal) {
var estTotalParts = Math.round(frag.duration / part.duration);
var estLoadedParts = Math.min(Math.round(fragStats.loaded / partTotal), estTotalParts);
var estRemainingParts = estTotalParts - estLoadedParts;
var estRemainingBytes = estRemainingParts * Math.round(fragStats.loaded / estLoadedParts);
fragStats.total = fragStats.loaded + estRemainingBytes;
} else {
fragStats.total = Math.max(fragStats.loaded, fragStats.total);
}
var fragLoading = fragStats.loading;
var partLoading = partStats.loading;
if (fragLoading.start) {
// add to fragment loader latency
fragLoading.first += partLoading.first - partLoading.start;
} else {
fragLoading.start = partLoading.start;
fragLoading.first = partLoading.first;
}
fragLoading.end = partLoading.end;
};
_proto.resetLoader = function resetLoader(frag, loader) {
frag.loader = null;
if (this.loader === loader) {
self.clearTimeout(this.partLoadTimeout);
this.loader = null;
}
loader.destroy();
};
return FragmentLoader;
}();
function createLoaderContext(frag, part) {
if (part === void 0) {
part = null;
}
var segment = part || frag;
var loaderContext = {
frag: frag,
part: part,
responseType: 'arraybuffer',
url: segment.url,
rangeStart: 0,
rangeEnd: 0
};
var start = segment.byteRangeStartOffset;
var end = segment.byteRangeEndOffset;
if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(start) && Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(end)) {
loaderContext.rangeStart = start;
loaderContext.rangeEnd = end;
}
return loaderContext;
}
var LoadError = /*#__PURE__*/function (_Error) {
_inheritsLoose(LoadError, _Error);
function LoadError(data) {
var _this3;
for (var _len = arguments.length, params = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
params[_key - 1] = arguments[_key];
}
_this3 = _Error.call.apply(_Error, [this].concat(params)) || this;
_this3.data = void 0;
_this3.data = data;
return _this3;
}
return LoadError;
}( /*#__PURE__*/_wrapNativeSuper(Error));
/***/ }),
/***/ "./src/loader/fragment.ts":
/*!********************************!*\
!*** ./src/loader/fragment.ts ***!
\********************************/
/*! exports provided: ElementaryStreamTypes, BaseSegment, Fragment, Part */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ElementaryStreamTypes", function() { return ElementaryStreamTypes; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BaseSegment", function() { return BaseSegment; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Fragment", function() { return Fragment; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Part", function() { return Part; });
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! url-toolkit */ "./node_modules/url-toolkit/src/url-toolkit.js");
/* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(url_toolkit__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/* harmony import */ var _level_key__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./level-key */ "./src/loader/level-key.ts");
/* harmony import */ var _load_stats__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./load-stats */ "./src/loader/load-stats.ts");
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
var ElementaryStreamTypes;
(function (ElementaryStreamTypes) {
ElementaryStreamTypes["AUDIO"] = "audio";
ElementaryStreamTypes["VIDEO"] = "video";
ElementaryStreamTypes["AUDIOVIDEO"] = "audiovideo";
})(ElementaryStreamTypes || (ElementaryStreamTypes = {}));
var BaseSegment = /*#__PURE__*/function () {
// baseurl is the URL to the playlist
// relurl is the portion of the URL that comes from inside the playlist.
// Holds the types of data this fragment supports
function BaseSegment(baseurl) {
var _this$elementaryStrea;
this._byteRange = null;
this._url = null;
this.baseurl = void 0;
this.relurl = void 0;
this.elementaryStreams = (_this$elementaryStrea = {}, _this$elementaryStrea[ElementaryStreamTypes.AUDIO] = null, _this$elementaryStrea[ElementaryStreamTypes.VIDEO] = null, _this$elementaryStrea[ElementaryStreamTypes.AUDIOVIDEO] = null, _this$elementaryStrea);
this.baseurl = baseurl;
} // setByteRange converts a EXT-X-BYTERANGE attribute into a two element array
var _proto = BaseSegment.prototype;
_proto.setByteRange = function setByteRange(value, previous) {
var params = value.split('@', 2);
var byteRange = [];
if (params.length === 1) {
byteRange[0] = previous ? previous.byteRangeEndOffset : 0;
} else {
byteRange[0] = parseInt(params[1]);
}
byteRange[1] = parseInt(params[0]) + byteRange[0];
this._byteRange = byteRange;
};
_createClass(BaseSegment, [{
key: "byteRange",
get: function get() {
if (!this._byteRange) {
return [];
}
return this._byteRange;
}
}, {
key: "byteRangeStartOffset",
get: function get() {
return this.byteRange[0];
}
}, {
key: "byteRangeEndOffset",
get: function get() {
return this.byteRange[1];
}
}, {
key: "url",
get: function get() {
if (!this._url && this.baseurl && this.relurl) {
this._url = Object(url_toolkit__WEBPACK_IMPORTED_MODULE_1__["buildAbsoluteURL"])(this.baseurl, this.relurl, {
alwaysNormalize: true
});
}
return this._url || '';
},
set: function set(value) {
this._url = value;
}
}]);
return BaseSegment;
}();
var Fragment = /*#__PURE__*/function (_BaseSegment) {
_inheritsLoose(Fragment, _BaseSegment);
// EXTINF has to be present for a m38 to be considered valid
// sn notates the sequence number for a segment, and if set to a string can be 'initSegment'
// levelkey is the EXT-X-KEY that applies to this segment for decryption
// core difference from the private field _decryptdata is the lack of the initialized IV
// _decryptdata will set the IV for this segment based on the segment number in the fragment
// A string representing the fragment type
// A reference to the loader. Set while the fragment is loading, and removed afterwards. Used to abort fragment loading
// The level/track index to which the fragment belongs
// The continuity counter of the fragment
// The starting Presentation Time Stamp (PTS) of the fragment. Set after transmux complete.
// The ending Presentation Time Stamp (PTS) of the fragment. Set after transmux complete.
// The latest Presentation Time Stamp (PTS) appended to the buffer.
// The starting Decode Time Stamp (DTS) of the fragment. Set after transmux complete.
// The ending Decode Time Stamp (DTS) of the fragment. Set after transmux complete.
// The start time of the fragment, as listed in the manifest. Updated after transmux complete.
// Set by `updateFragPTSDTS` in level-helper
// The maximum starting Presentation Time Stamp (audio/video PTS) of the fragment. Set after transmux complete.
// The minimum ending Presentation Time Stamp (audio/video PTS) of the fragment. Set after transmux complete.
// Load/parse timing information
// A flag indicating whether the segment was downloaded in order to test bitrate, and was not buffered
// #EXTINF segment title
function Fragment(type, baseurl) {
var _this;
_this = _BaseSegment.call(this, baseurl) || this;
_this._decryptdata = null;
_this.rawProgramDateTime = null;
_this.programDateTime = null;
_this.tagList = [];
_this.duration = 0;
_this.sn = 0;
_this.levelkey = void 0;
_this.type = void 0;
_this.loader = null;
_this.level = -1;
_this.cc = 0;
_this.startPTS = void 0;
_this.endPTS = void 0;
_this.appendedPTS = void 0;
_this.startDTS = void 0;
_this.endDTS = void 0;
_this.start = 0;
_this.deltaPTS = void 0;
_this.maxStartPTS = void 0;
_this.minEndPTS = void 0;
_this.stats = new _load_stats__WEBPACK_IMPORTED_MODULE_4__["LoadStats"]();
_this.urlId = 0;
_this.data = void 0;
_this.bitrateTest = false;
_this.title = null;
_this.type = type;
return _this;
}
var _proto2 = Fragment.prototype;
/**
* Utility method for parseLevelPlaylist to create an initialization vector for a given segment
* @param {number} segmentNumber - segment number to generate IV with
* @returns {Uint8Array}
*/
_proto2.createInitializationVector = function createInitializationVector(segmentNumber) {
var uint8View = new Uint8Array(16);
for (var i = 12; i < 16; i++) {
uint8View[i] = segmentNumber >> 8 * (15 - i) & 0xff;
}
return uint8View;
}
/**
* Utility method for parseLevelPlaylist to get a fragment's decryption data from the currently parsed encryption key data
* @param levelkey - a playlist's encryption info
* @param segmentNumber - the fragment's segment number
* @returns {LevelKey} - an object to be applied as a fragment's decryptdata
*/
;
_proto2.setDecryptDataFromLevelKey = function setDecryptDataFromLevelKey(levelkey, segmentNumber) {
var decryptdata = levelkey;
if ((levelkey === null || levelkey === void 0 ? void 0 : levelkey.method) === 'AES-128' && levelkey.uri && !levelkey.iv) {
decryptdata = _level_key__WEBPACK_IMPORTED_MODULE_3__["LevelKey"].fromURI(levelkey.uri);
decryptdata.method = levelkey.method;
decryptdata.iv = this.createInitializationVector(segmentNumber);
decryptdata.keyFormat = 'identity';
}
return decryptdata;
};
_proto2.setElementaryStreamInfo = function setElementaryStreamInfo(type, startPTS, endPTS, startDTS, endDTS, partial) {
if (partial === void 0) {
partial = false;
}
var elementaryStreams = this.elementaryStreams;
var info = elementaryStreams[type];
if (!info) {
elementaryStreams[type] = {
startPTS: startPTS,
endPTS: endPTS,
startDTS: startDTS,
endDTS: endDTS,
partial: partial
};
return;
}
info.startPTS = Math.min(info.startPTS, startPTS);
info.endPTS = Math.max(info.endPTS, endPTS);
info.startDTS = Math.min(info.startDTS, startDTS);
info.endDTS = Math.max(info.endDTS, endDTS);
};
_proto2.clearElementaryStreamInfo = function clearElementaryStreamInfo() {
var elementaryStreams = this.elementaryStreams;
elementaryStreams[ElementaryStreamTypes.AUDIO] = null;
elementaryStreams[ElementaryStreamTypes.VIDEO] = null;
elementaryStreams[ElementaryStreamTypes.AUDIOVIDEO] = null;
};
_createClass(Fragment, [{
key: "decryptdata",
get: function get() {
if (!this.levelkey && !this._decryptdata) {
return null;
}
if (!this._decryptdata && this.levelkey) {
var sn = this.sn;
if (typeof sn !== 'number') {
// We are fetching decryption data for a initialization segment
// If the segment was encrypted with AES-128
// It must have an IV defined. We cannot substitute the Segment Number in.
if (this.levelkey && this.levelkey.method === 'AES-128' && !this.levelkey.iv) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn("missing IV for initialization segment with method=\"" + this.levelkey.method + "\" - compliance issue");
}
/*
Be converted to a Number.
'initSegment' will become NaN.
NaN, which when converted through ToInt32() -> +0.
---
Explicitly set sn to resulting value from implicit conversions 'initSegment' values for IV generation.
*/
sn = 0;
}
this._decryptdata = this.setDecryptDataFromLevelKey(this.levelkey, sn);
}
return this._decryptdata;
}
}, {
key: "end",
get: function get() {
return this.start + this.duration;
}
}, {
key: "endProgramDateTime",
get: function get() {
if (this.programDateTime === null) {
return null;
}
if (!Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(this.programDateTime)) {
return null;
}
var duration = !Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(this.duration) ? 0 : this.duration;
return this.programDateTime + duration * 1000;
}
}, {
key: "encrypted",
get: function get() {
var _this$decryptdata;
// At the m3u8-parser level we need to add support for manifest signalled keyformats
// when we want the fragment to start reporting that it is encrypted.
// Currently, keyFormat will only be set for identity keys
if ((_this$decryptdata = this.decryptdata) !== null && _this$decryptdata !== void 0 && _this$decryptdata.keyFormat && this.decryptdata.uri) {
return true;
}
return false;
}
}]);
return Fragment;
}(BaseSegment);
var Part = /*#__PURE__*/function (_BaseSegment2) {
_inheritsLoose(Part, _BaseSegment2);
function Part(partAttrs, frag, baseurl, index, previous) {
var _this2;
_this2 = _BaseSegment2.call(this, baseurl) || this;
_this2.fragOffset = 0;
_this2.duration = 0;
_this2.gap = false;
_this2.independent = false;
_this2.relurl = void 0;
_this2.fragment = void 0;
_this2.index = void 0;
_this2.stats = new _load_stats__WEBPACK_IMPORTED_MODULE_4__["LoadStats"]();
_this2.duration = partAttrs.decimalFloatingPoint('DURATION');
_this2.gap = partAttrs.bool('GAP');
_this2.independent = partAttrs.bool('INDEPENDENT');
_this2.relurl = partAttrs.enumeratedString('URI');
_this2.fragment = frag;
_this2.index = index;
var byteRange = partAttrs.enumeratedString('BYTERANGE');
if (byteRange) {
_this2.setByteRange(byteRange, previous);
}
if (previous) {
_this2.fragOffset = previous.fragOffset + previous.duration;
}
return _this2;
}
_createClass(Part, [{
key: "start",
get: function get() {
return this.fragment.start + this.fragOffset;
}
}, {
key: "end",
get: function get() {
return this.start + this.duration;
}
}, {
key: "loaded",
get: function get() {
var elementaryStreams = this.elementaryStreams;
return !!(elementaryStreams.audio || elementaryStreams.video || elementaryStreams.audiovideo);
}
}]);
return Part;
}(BaseSegment);
/***/ }),
/***/ "./src/loader/key-loader.ts":
/*!**********************************!*\
!*** ./src/loader/key-loader.ts ***!
\**********************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return KeyLoader; });
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/*
* Decrypt key Loader
*/
var KeyLoader = /*#__PURE__*/function () {
function KeyLoader(hls) {
this.hls = void 0;
this.loaders = {};
this.decryptkey = null;
this.decrypturl = null;
this.hls = hls;
this._registerListeners();
}
var _proto = KeyLoader.prototype;
_proto._registerListeners = function _registerListeners() {
this.hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].KEY_LOADING, this.onKeyLoading, this);
};
_proto._unregisterListeners = function _unregisterListeners() {
this.hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].KEY_LOADING, this.onKeyLoading);
};
_proto.destroy = function destroy() {
this._unregisterListeners();
for (var loaderName in this.loaders) {
var loader = this.loaders[loaderName];
if (loader) {
loader.destroy();
}
}
this.loaders = {};
};
_proto.onKeyLoading = function onKeyLoading(event, data) {
var frag = data.frag;
var type = frag.type;
var loader = this.loaders[type];
if (!frag.decryptdata) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn('Missing decryption data on fragment in onKeyLoading');
return;
} // Load the key if the uri is different from previous one, or if the decrypt key has not yet been retrieved
var uri = frag.decryptdata.uri;
if (uri !== this.decrypturl || this.decryptkey === null) {
var config = this.hls.config;
if (loader) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn("abort previous key loader for type:" + type);
loader.abort();
}
if (!uri) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn('key uri is falsy');
return;
}
var Loader = config.loader;
var fragLoader = frag.loader = this.loaders[type] = new Loader(config);
this.decrypturl = uri;
this.decryptkey = null;
var loaderContext = {
url: uri,
frag: frag,
responseType: 'arraybuffer'
}; // maxRetry is 0 so that instead of retrying the same key on the same variant multiple times,
// key-loader will trigger an error and rely on stream-controller to handle retry logic.
// this will also align retry logic with fragment-loader
var loaderConfig = {
timeout: config.fragLoadingTimeOut,
maxRetry: 0,
retryDelay: config.fragLoadingRetryDelay,
maxRetryDelay: config.fragLoadingMaxRetryTimeout,
highWaterMark: 0
};
var loaderCallbacks = {
onSuccess: this.loadsuccess.bind(this),
onError: this.loaderror.bind(this),
onTimeout: this.loadtimeout.bind(this)
};
fragLoader.load(loaderContext, loaderConfig, loaderCallbacks);
} else if (this.decryptkey) {
// Return the key if it's already been loaded
frag.decryptdata.key = this.decryptkey;
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].KEY_LOADED, {
frag: frag
});
}
};
_proto.loadsuccess = function loadsuccess(response, stats, context) {
var frag = context.frag;
if (!frag.decryptdata) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error('after key load, decryptdata unset');
return;
}
this.decryptkey = frag.decryptdata.key = new Uint8Array(response.data); // detach fragment loader on load success
frag.loader = null;
delete this.loaders[frag.type];
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].KEY_LOADED, {
frag: frag
});
};
_proto.loaderror = function loaderror(response, context) {
var frag = context.frag;
var loader = frag.loader;
if (loader) {
loader.abort();
}
delete this.loaders[frag.type];
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].NETWORK_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].KEY_LOAD_ERROR,
fatal: false,
frag: frag,
response: response
});
};
_proto.loadtimeout = function loadtimeout(stats, context) {
var frag = context.frag;
var loader = frag.loader;
if (loader) {
loader.abort();
}
delete this.loaders[frag.type];
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].NETWORK_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].KEY_LOAD_TIMEOUT,
fatal: false,
frag: frag
});
};
return KeyLoader;
}();
/***/ }),
/***/ "./src/loader/level-details.ts":
/*!*************************************!*\
!*** ./src/loader/level-details.ts ***!
\*************************************/
/*! exports provided: LevelDetails */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LevelDetails", function() { return LevelDetails; });
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
var DEFAULT_TARGET_DURATION = 10;
var LevelDetails = /*#__PURE__*/function () {
// Manifest reload synchronization
function LevelDetails(baseUrl) {
this.PTSKnown = false;
this.alignedSliding = false;
this.averagetargetduration = void 0;
this.endCC = 0;
this.endSN = 0;
this.fragments = void 0;
this.fragmentHint = void 0;
this.partList = null;
this.initSegment = null;
this.live = true;
this.ageHeader = 0;
this.advancedDateTime = void 0;
this.updated = true;
this.advanced = true;
this.availabilityDelay = void 0;
this.misses = 0;
this.needSidxRanges = false;
this.startCC = 0;
this.startSN = 0;
this.startTimeOffset = null;
this.targetduration = 0;
this.totalduration = 0;
this.type = null;
this.url = void 0;
this.m3u8 = '';
this.version = null;
this.canBlockReload = false;
this.canSkipUntil = 0;
this.canSkipDateRanges = false;
this.skippedSegments = 0;
this.recentlyRemovedDateranges = void 0;
this.partHoldBack = 0;
this.holdBack = 0;
this.partTarget = 0;
this.preloadHint = void 0;
this.renditionReports = void 0;
this.tuneInGoal = 0;
this.deltaUpdateFailed = void 0;
this.fragments = [];
this.url = baseUrl;
}
var _proto = LevelDetails.prototype;
_proto.reloaded = function reloaded(previous) {
if (!previous) {
this.advanced = true;
this.updated = true;
return;
}
var partSnDiff = this.lastPartSn - previous.lastPartSn;
var partIndexDiff = this.lastPartIndex - previous.lastPartIndex;
this.updated = this.endSN !== previous.endSN || !!partIndexDiff || !!partSnDiff;
this.advanced = this.endSN > previous.endSN || partSnDiff > 0 || partSnDiff === 0 && partIndexDiff > 0;
if (this.updated || this.advanced) {
this.misses = Math.floor(previous.misses * 0.6);
} else {
this.misses = previous.misses + 1;
}
this.availabilityDelay = previous.availabilityDelay;
};
_createClass(LevelDetails, [{
key: "hasProgramDateTime",
get: function get() {
if (this.fragments.length) {
return Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(this.fragments[this.fragments.length - 1].programDateTime);
}
return false;
}
}, {
key: "levelTargetDuration",
get: function get() {
return this.averagetargetduration || this.targetduration || DEFAULT_TARGET_DURATION;
}
}, {
key: "edge",
get: function get() {
return this.partEnd || this.fragmentEnd;
}
}, {
key: "partEnd",
get: function get() {
var _this$partList;
if ((_this$partList = this.partList) !== null && _this$partList !== void 0 && _this$partList.length) {
return this.partList[this.partList.length - 1].end;
}
return this.fragmentEnd;
}
}, {
key: "fragmentEnd",
get: function get() {
var _this$fragments;
if ((_this$fragments = this.fragments) !== null && _this$fragments !== void 0 && _this$fragments.length) {
return this.fragments[this.fragments.length - 1].end;
}
return 0;
}
}, {
key: "age",
get: function get() {
if (this.advancedDateTime) {
return Math.max(Date.now() - this.advancedDateTime, 0) / 1000;
}
return 0;
}
}, {
key: "lastPartIndex",
get: function get() {
var _this$partList2;
if ((_this$partList2 = this.partList) !== null && _this$partList2 !== void 0 && _this$partList2.length) {
return this.partList[this.partList.length - 1].index;
}
return -1;
}
}, {
key: "lastPartSn",
get: function get() {
var _this$partList3;
if ((_this$partList3 = this.partList) !== null && _this$partList3 !== void 0 && _this$partList3.length) {
return this.partList[this.partList.length - 1].fragment.sn;
}
return this.endSN;
}
}]);
return LevelDetails;
}();
/***/ }),
/***/ "./src/loader/level-key.ts":
/*!*********************************!*\
!*** ./src/loader/level-key.ts ***!
\*********************************/
/*! exports provided: LevelKey */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LevelKey", function() { return LevelKey; });
/* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! url-toolkit */ "./node_modules/url-toolkit/src/url-toolkit.js");
/* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(url_toolkit__WEBPACK_IMPORTED_MODULE_0__);
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
var LevelKey = /*#__PURE__*/function () {
LevelKey.fromURL = function fromURL(baseUrl, relativeUrl) {
return new LevelKey(baseUrl, relativeUrl);
};
LevelKey.fromURI = function fromURI(uri) {
return new LevelKey(uri);
};
function LevelKey(absoluteOrBaseURI, relativeURL) {
this._uri = null;
this.method = null;
this.keyFormat = null;
this.keyFormatVersions = null;
this.keyID = null;
this.key = null;
this.iv = null;
if (relativeURL) {
this._uri = Object(url_toolkit__WEBPACK_IMPORTED_MODULE_0__["buildAbsoluteURL"])(absoluteOrBaseURI, relativeURL, {
alwaysNormalize: true
});
} else {
this._uri = absoluteOrBaseURI;
}
}
_createClass(LevelKey, [{
key: "uri",
get: function get() {
return this._uri;
}
}]);
return LevelKey;
}();
/***/ }),
/***/ "./src/loader/load-stats.ts":
/*!**********************************!*\
!*** ./src/loader/load-stats.ts ***!
\**********************************/
/*! exports provided: LoadStats */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LoadStats", function() { return LoadStats; });
var LoadStats = function LoadStats() {
this.aborted = false;
this.loaded = 0;
this.retry = 0;
this.total = 0;
this.chunkCount = 0;
this.bwEstimate = 0;
this.loading = {
start: 0,
first: 0,
end: 0
};
this.parsing = {
start: 0,
end: 0
};
this.buffering = {
start: 0,
first: 0,
end: 0
};
};
/***/ }),
/***/ "./src/loader/m3u8-parser.ts":
/*!***********************************!*\
!*** ./src/loader/m3u8-parser.ts ***!
\***********************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return M3U8Parser; });
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! url-toolkit */ "./node_modules/url-toolkit/src/url-toolkit.js");
/* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(url_toolkit__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _fragment__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./fragment */ "./src/loader/fragment.ts");
/* harmony import */ var _level_details__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./level-details */ "./src/loader/level-details.ts");
/* harmony import */ var _level_key__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./level-key */ "./src/loader/level-key.ts");
/* harmony import */ var _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/attr-list */ "./src/utils/attr-list.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/* harmony import */ var _utils_codecs__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../utils/codecs */ "./src/utils/codecs.ts");
// https://regex101.com is your friend
var MASTER_PLAYLIST_REGEX = /#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-SESSION-DATA:([^\r\n]*)[\r\n]+/g;
var MASTER_PLAYLIST_MEDIA_REGEX = /#EXT-X-MEDIA:(.*)/g;
var LEVEL_PLAYLIST_REGEX_FAST = new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source, // duration (#EXTINF:<duration>,<title>), group 1 => duration, group 2 => title
/(?!#) *(\S[\S ]*)/.source, // segment URI, group 3 => the URI (note newline is not eaten)
/#EXT-X-BYTERANGE:*(.+)/.source, // next segment's byterange, group 4 => range spec (x@y)
/#EXT-X-PROGRAM-DATE-TIME:(.+)/.source, // next segment's program date/time group 5 => the datetime spec
/#.*/.source // All other non-segment oriented tags will match with all groups empty
].join('|'), 'g');
var LEVEL_PLAYLIST_REGEX_SLOW = new RegExp([/#(EXTM3U)/.source, /#EXT-X-(PLAYLIST-TYPE):(.+)/.source, /#EXT-X-(MEDIA-SEQUENCE): *(\d+)/.source, /#EXT-X-(SKIP):(.+)/.source, /#EXT-X-(TARGETDURATION): *(\d+)/.source, /#EXT-X-(KEY):(.+)/.source, /#EXT-X-(START):(.+)/.source, /#EXT-X-(ENDLIST)/.source, /#EXT-X-(DISCONTINUITY-SEQ)UENCE: *(\d+)/.source, /#EXT-X-(DIS)CONTINUITY/.source, /#EXT-X-(VERSION):(\d+)/.source, /#EXT-X-(MAP):(.+)/.source, /#EXT-X-(SERVER-CONTROL):(.+)/.source, /#EXT-X-(PART-INF):(.+)/.source, /#EXT-X-(GAP)/.source, /#EXT-X-(BITRATE):\s*(\d+)/.source, /#EXT-X-(PART):(.+)/.source, /#EXT-X-(PRELOAD-HINT):(.+)/.source, /#EXT-X-(RENDITION-REPORT):(.+)/.source, /(#)([^:]*):(.*)/.source, /(#)(.*)(?:.*)\r?\n?/.source].join('|'));
var MP4_REGEX_SUFFIX = /\.(mp4|m4s|m4v|m4a)$/i;
var M3U8Parser = /*#__PURE__*/function () {
function M3U8Parser() {}
M3U8Parser.findGroup = function findGroup(groups, mediaGroupId) {
for (var i = 0; i < groups.length; i++) {
var group = groups[i];
if (group.id === mediaGroupId) {
return group;
}
}
};
M3U8Parser.convertAVC1ToAVCOTI = function convertAVC1ToAVCOTI(codec) {
// Convert avc1 codec string from RFC-4281 to RFC-6381 for MediaSource.isTypeSupported
var avcdata = codec.split('.');
if (avcdata.length > 2) {
var result = avcdata.shift() + '.';
result += parseInt(avcdata.shift()).toString(16);
result += ('000' + parseInt(avcdata.shift()).toString(16)).substr(-4);
return result;
}
return codec;
};
M3U8Parser.resolve = function resolve(url, baseUrl) {
return url_toolkit__WEBPACK_IMPORTED_MODULE_1__["buildAbsoluteURL"](baseUrl, url, {
alwaysNormalize: true
});
};
M3U8Parser.parseMasterPlaylist = function parseMasterPlaylist(string, baseurl) {
var levels = [];
var sessionData = {};
var hasSessionData = false;
MASTER_PLAYLIST_REGEX.lastIndex = 0;
var result;
while ((result = MASTER_PLAYLIST_REGEX.exec(string)) != null) {
if (result[1]) {
// '#EXT-X-STREAM-INF' is found, parse level tag in group 1
var attrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](result[1]);
var level = {
attrs: attrs,
bitrate: attrs.decimalInteger('AVERAGE-BANDWIDTH') || attrs.decimalInteger('BANDWIDTH'),
name: attrs.NAME,
url: M3U8Parser.resolve(result[2], baseurl)
};
var resolution = attrs.decimalResolution('RESOLUTION');
if (resolution) {
level.width = resolution.width;
level.height = resolution.height;
}
setCodecs((attrs.CODECS || '').split(/[ ,]+/).filter(function (c) {
return c;
}), level);
if (level.videoCodec && level.videoCodec.indexOf('avc1') !== -1) {
level.videoCodec = M3U8Parser.convertAVC1ToAVCOTI(level.videoCodec);
}
levels.push(level);
} else if (result[3]) {
// '#EXT-X-SESSION-DATA' is found, parse session data in group 3
var sessionAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](result[3]);
if (sessionAttrs['DATA-ID']) {
hasSessionData = true;
sessionData[sessionAttrs['DATA-ID']] = sessionAttrs;
}
}
}
return {
levels: levels,
sessionData: hasSessionData ? sessionData : null
};
};
M3U8Parser.parseMasterPlaylistMedia = function parseMasterPlaylistMedia(string, baseurl, type, groups) {
if (groups === void 0) {
groups = [];
}
var result;
var medias = [];
var id = 0;
MASTER_PLAYLIST_MEDIA_REGEX.lastIndex = 0;
while ((result = MASTER_PLAYLIST_MEDIA_REGEX.exec(string)) !== null) {
var attrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](result[1]);
if (attrs.TYPE === type) {
var media = {
attrs: attrs,
bitrate: 0,
id: id++,
groupId: attrs['GROUP-ID'],
instreamId: attrs['INSTREAM-ID'],
name: attrs.NAME || attrs.LANGUAGE || '',
type: type,
default: attrs.bool('DEFAULT'),
autoselect: attrs.bool('AUTOSELECT'),
forced: attrs.bool('FORCED'),
lang: attrs.LANGUAGE,
url: attrs.URI ? M3U8Parser.resolve(attrs.URI, baseurl) : ''
};
if (groups.length) {
// If there are audio or text groups signalled in the manifest, let's look for a matching codec string for this track
// If we don't find the track signalled, lets use the first audio groups codec we have
// Acting as a best guess
var groupCodec = M3U8Parser.findGroup(groups, media.groupId) || groups[0];
assignCodec(media, groupCodec, 'audioCodec');
assignCodec(media, groupCodec, 'textCodec');
}
medias.push(media);
}
}
return medias;
};
M3U8Parser.parseLevelPlaylist = function parseLevelPlaylist(string, baseurl, id, type, levelUrlId) {
var level = new _level_details__WEBPACK_IMPORTED_MODULE_3__["LevelDetails"](baseurl);
var fragments = level.fragments;
var currentSN = 0;
var currentPart = 0;
var totalduration = 0;
var discontinuityCounter = 0;
var prevFrag = null;
var frag = new _fragment__WEBPACK_IMPORTED_MODULE_2__["Fragment"](type, baseurl);
var result;
var i;
var levelkey;
var firstPdtIndex = -1;
LEVEL_PLAYLIST_REGEX_FAST.lastIndex = 0;
level.m3u8 = string;
while ((result = LEVEL_PLAYLIST_REGEX_FAST.exec(string)) !== null) {
var duration = result[1];
if (duration) {
// INF
frag.duration = parseFloat(duration); // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
var title = (' ' + result[2]).slice(1);
frag.title = title || null;
frag.tagList.push(title ? ['INF', duration, title] : ['INF', duration]);
} else if (result[3]) {
// url
if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(frag.duration)) {
frag.start = totalduration;
if (levelkey) {
frag.levelkey = levelkey;
}
frag.sn = currentSN;
frag.level = id;
frag.cc = discontinuityCounter;
frag.urlId = levelUrlId;
fragments.push(frag); // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
frag.relurl = (' ' + result[3]).slice(1);
assignProgramDateTime(frag, prevFrag);
prevFrag = frag;
totalduration += frag.duration;
currentSN++;
currentPart = 0;
frag = new _fragment__WEBPACK_IMPORTED_MODULE_2__["Fragment"](type, baseurl); // setup the next fragment for part loading
frag.start = totalduration;
frag.sn = currentSN;
frag.cc = discontinuityCounter;
frag.level = id;
}
} else if (result[4]) {
// X-BYTERANGE
var data = (' ' + result[4]).slice(1);
if (prevFrag) {
frag.setByteRange(data, prevFrag);
} else {
frag.setByteRange(data);
}
} else if (result[5]) {
// PROGRAM-DATE-TIME
// avoid sliced strings https://github.com/video-dev/hls.js/issues/939
frag.rawProgramDateTime = (' ' + result[5]).slice(1);
frag.tagList.push(['PROGRAM-DATE-TIME', frag.rawProgramDateTime]);
if (firstPdtIndex === -1) {
firstPdtIndex = fragments.length;
}
} else {
result = result[0].match(LEVEL_PLAYLIST_REGEX_SLOW);
if (!result) {
_utils_logger__WEBPACK_IMPORTED_MODULE_6__["logger"].warn('No matches on slow regex match for level playlist!');
continue;
}
for (i = 1; i < result.length; i++) {
if (typeof result[i] !== 'undefined') {
break;
}
} // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
var tag = (' ' + result[i]).slice(1);
var value1 = (' ' + result[i + 1]).slice(1);
var value2 = result[i + 2] ? (' ' + result[i + 2]).slice(1) : '';
switch (tag) {
case 'PLAYLIST-TYPE':
level.type = value1.toUpperCase();
break;
case 'MEDIA-SEQUENCE':
currentSN = level.startSN = parseInt(value1);
break;
case 'SKIP':
{
var skipAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](value1);
var skippedSegments = skipAttrs.decimalInteger('SKIPPED-SEGMENTS');
if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(skippedSegments)) {
level.skippedSegments = skippedSegments; // This will result in fragments[] containing undefined values, which we will fill in with `mergeDetails`
for (var _i = skippedSegments; _i--;) {
fragments.unshift(null);
}
currentSN += skippedSegments;
}
var recentlyRemovedDateranges = skipAttrs.enumeratedString('RECENTLY-REMOVED-DATERANGES');
if (recentlyRemovedDateranges) {
level.recentlyRemovedDateranges = recentlyRemovedDateranges.split('\t');
}
break;
}
case 'TARGETDURATION':
level.targetduration = parseFloat(value1);
break;
case 'VERSION':
level.version = parseInt(value1);
break;
case 'EXTM3U':
break;
case 'ENDLIST':
level.live = false;
break;
case '#':
if (value1 || value2) {
frag.tagList.push(value2 ? [value1, value2] : [value1]);
}
break;
case 'DIS':
discontinuityCounter++;
/* falls through */
case 'GAP':
frag.tagList.push([tag]);
break;
case 'BITRATE':
frag.tagList.push([tag, value1]);
break;
case 'DISCONTINUITY-SEQ':
discontinuityCounter = parseInt(value1);
break;
case 'KEY':
{
var _keyAttrs$enumeratedS;
// https://tools.ietf.org/html/rfc8216#section-4.3.2.4
var keyAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](value1);
var decryptmethod = keyAttrs.enumeratedString('METHOD');
var decrypturi = keyAttrs.URI;
var decryptiv = keyAttrs.hexadecimalInteger('IV');
var decryptkeyformatversions = keyAttrs.enumeratedString('KEYFORMATVERSIONS');
var decryptkeyid = keyAttrs.enumeratedString('KEYID'); // From RFC: This attribute is OPTIONAL; its absence indicates an implicit value of "identity".
var decryptkeyformat = (_keyAttrs$enumeratedS = keyAttrs.enumeratedString('KEYFORMAT')) != null ? _keyAttrs$enumeratedS : 'identity';
var unsupportedKnownKeyformatsInManifest = ['com.apple.streamingkeydelivery', 'com.microsoft.playready', 'urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed', // widevine (v2)
'com.widevine' // earlier widevine (v1)
];
if (unsupportedKnownKeyformatsInManifest.indexOf(decryptkeyformat) > -1) {
_utils_logger__WEBPACK_IMPORTED_MODULE_6__["logger"].warn("Keyformat " + decryptkeyformat + " is not supported from the manifest");
continue;
} else if (decryptkeyformat !== 'identity') {
// We are supposed to skip keys we don't understand.
// As we currently only officially support identity keys
// from the manifest we shouldn't save any other key.
continue;
} // TODO: multiple keys can be defined on a fragment, and we need to support this
// for clients that support both playready and widevine
if (decryptmethod) {
// TODO: need to determine if the level key is actually a relative URL
// if it isn't, then we should instead construct the LevelKey using fromURI.
levelkey = _level_key__WEBPACK_IMPORTED_MODULE_4__["LevelKey"].fromURL(baseurl, decrypturi);
if (decrypturi && ['AES-128', 'SAMPLE-AES', 'SAMPLE-AES-CENC'].indexOf(decryptmethod) >= 0) {
levelkey.method = decryptmethod;
levelkey.keyFormat = decryptkeyformat;
if (decryptkeyid) {
levelkey.keyID = decryptkeyid;
}
if (decryptkeyformatversions) {
levelkey.keyFormatVersions = decryptkeyformatversions;
} // Initialization Vector (IV)
levelkey.iv = decryptiv;
}
}
break;
}
case 'START':
{
var startAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](value1);
var startTimeOffset = startAttrs.decimalFloatingPoint('TIME-OFFSET'); // TIME-OFFSET can be 0
if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(startTimeOffset)) {
level.startTimeOffset = startTimeOffset;
}
break;
}
case 'MAP':
{
var mapAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](value1);
frag.relurl = mapAttrs.URI;
if (mapAttrs.BYTERANGE) {
frag.setByteRange(mapAttrs.BYTERANGE);
}
frag.level = id;
frag.sn = 'initSegment';
if (levelkey) {
frag.levelkey = levelkey;
}
level.initSegment = frag;
frag = new _fragment__WEBPACK_IMPORTED_MODULE_2__["Fragment"](type, baseurl);
frag.rawProgramDateTime = level.initSegment.rawProgramDateTime;
break;
}
case 'SERVER-CONTROL':
{
var serverControlAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](value1);
level.canBlockReload = serverControlAttrs.bool('CAN-BLOCK-RELOAD');
level.canSkipUntil = serverControlAttrs.optionalFloat('CAN-SKIP-UNTIL', 0);
level.canSkipDateRanges = level.canSkipUntil > 0 && serverControlAttrs.bool('CAN-SKIP-DATERANGES');
level.partHoldBack = serverControlAttrs.optionalFloat('PART-HOLD-BACK', 0);
level.holdBack = serverControlAttrs.optionalFloat('HOLD-BACK', 0);
break;
}
case 'PART-INF':
{
var partInfAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](value1);
level.partTarget = partInfAttrs.decimalFloatingPoint('PART-TARGET');
break;
}
case 'PART':
{
var partList = level.partList;
if (!partList) {
partList = level.partList = [];
}
var previousFragmentPart = currentPart > 0 ? partList[partList.length - 1] : undefined;
var index = currentPart++;
var part = new _fragment__WEBPACK_IMPORTED_MODULE_2__["Part"](new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](value1), frag, baseurl, index, previousFragmentPart);
partList.push(part);
frag.duration += part.duration;
break;
}
case 'PRELOAD-HINT':
{
var preloadHintAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](value1);
level.preloadHint = preloadHintAttrs;
break;
}
case 'RENDITION-REPORT':
{
var renditionReportAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](value1);
level.renditionReports = level.renditionReports || [];
level.renditionReports.push(renditionReportAttrs);
break;
}
default:
_utils_logger__WEBPACK_IMPORTED_MODULE_6__["logger"].warn("line parsed but not handled: " + result);
break;
}
}
}
if (prevFrag && !prevFrag.relurl) {
fragments.pop();
totalduration -= prevFrag.duration;
if (level.partList) {
level.fragmentHint = prevFrag;
}
} else if (level.partList) {
assignProgramDateTime(frag, prevFrag);
frag.cc = discontinuityCounter;
level.fragmentHint = frag;
}
var fragmentLength = fragments.length;
var firstFragment = fragments[0];
var lastFragment = fragments[fragmentLength - 1];
totalduration += level.skippedSegments * level.targetduration;
if (totalduration > 0 && fragmentLength && lastFragment) {
level.averagetargetduration = totalduration / fragmentLength;
var lastSn = lastFragment.sn;
level.endSN = lastSn !== 'initSegment' ? lastSn : 0;
if (firstFragment) {
level.startCC = firstFragment.cc;
if (!level.initSegment) {
// this is a bit lurky but HLS really has no other way to tell us
// if the fragments are TS or MP4, except if we download them :/
// but this is to be able to handle SIDX.
if (level.fragments.every(function (frag) {
return MP4_REGEX_SUFFIX.test(frag.relurl);
})) {
_utils_logger__WEBPACK_IMPORTED_MODULE_6__["logger"].warn('MP4 fragments found but no init segment (probably no MAP, incomplete M3U8), trying to fetch SIDX');
frag = new _fragment__WEBPACK_IMPORTED_MODULE_2__["Fragment"](type, baseurl);
frag.relurl = lastFragment.relurl;
frag.level = id;
frag.sn = 'initSegment';
level.initSegment = frag;
level.needSidxRanges = true;
}
}
}
} else {
level.endSN = 0;
level.startCC = 0;
}
if (level.fragmentHint) {
totalduration += level.fragmentHint.duration;
}
level.totalduration = totalduration;
level.endCC = discontinuityCounter;
/**
* Backfill any missing PDT values
* "If the first EXT-X-PROGRAM-DATE-TIME tag in a Playlist appears after
* one or more Media Segment URIs, the client SHOULD extrapolate
* backward from that tag (using EXTINF durations and/or media
* timestamps) to associate dates with those segments."
* We have already extrapolated forward, but all fragments up to the first instance of PDT do not have their PDTs
* computed.
*/
if (firstPdtIndex > 0) {
backfillProgramDateTimes(fragments, firstPdtIndex);
}
return level;
};
return M3U8Parser;
}();
function setCodecs(codecs, level) {
['video', 'audio', 'text'].forEach(function (type) {
var filtered = codecs.filter(function (codec) {
return Object(_utils_codecs__WEBPACK_IMPORTED_MODULE_7__["isCodecType"])(codec, type);
});
if (filtered.length) {
var preferred = filtered.filter(function (codec) {
return codec.lastIndexOf('avc1', 0) === 0 || codec.lastIndexOf('mp4a', 0) === 0;
});
level[type + "Codec"] = preferred.length > 0 ? preferred[0] : filtered[0]; // remove from list
codecs = codecs.filter(function (codec) {
return filtered.indexOf(codec) === -1;
});
}
});
level.unknownCodecs = codecs;
}
function assignCodec(media, groupItem, codecProperty) {
var codecValue = groupItem[codecProperty];
if (codecValue) {
media[codecProperty] = codecValue;
}
}
function backfillProgramDateTimes(fragments, firstPdtIndex) {
var fragPrev = fragments[firstPdtIndex];
for (var i = firstPdtIndex; i--;) {
var frag = fragments[i]; // Exit on delta-playlist skipped segments
if (!frag) {
return;
}
frag.programDateTime = fragPrev.programDateTime - frag.duration * 1000;
fragPrev = frag;
}
}
function assignProgramDateTime(frag, prevFrag) {
if (frag.rawProgramDateTime) {
frag.programDateTime = Date.parse(frag.rawProgramDateTime);
} else if (prevFrag !== null && prevFrag !== void 0 && prevFrag.programDateTime) {
frag.programDateTime = prevFrag.endProgramDateTime;
}
if (!Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(frag.programDateTime)) {
frag.programDateTime = null;
frag.rawProgramDateTime = null;
}
}
/***/ }),
/***/ "./src/loader/playlist-loader.ts":
/*!***************************************!*\
!*** ./src/loader/playlist-loader.ts ***!
\***************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/mp4-tools */ "./src/utils/mp4-tools.ts");
/* harmony import */ var _m3u8_parser__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./m3u8-parser */ "./src/loader/m3u8-parser.ts");
/* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts");
/* harmony import */ var _utils_attr_list__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../utils/attr-list */ "./src/utils/attr-list.ts");
/**
* PlaylistLoader - delegate for media manifest/playlist loading tasks. Takes care of parsing media to internal data-models.
*
* Once loaded, dispatches events with parsed data-models of manifest/levels/audio/subtitle tracks.
*
* Uses loader(s) set in config to do actual internal loading of resource tasks.
*
* @module
*
*/
function mapContextToLevelType(context) {
var type = context.type;
switch (type) {
case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].AUDIO_TRACK:
return _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].AUDIO;
case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].SUBTITLE_TRACK:
return _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].SUBTITLE;
default:
return _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN;
}
}
function getResponseUrl(response, context) {
var url = response.url; // responseURL not supported on some browsers (it is used to detect URL redirection)
// data-uri mode also not supported (but no need to detect redirection)
if (url === undefined || url.indexOf('data:') === 0) {
// fallback to initial URL
url = context.url;
}
return url;
}
var PlaylistLoader = /*#__PURE__*/function () {
function PlaylistLoader(hls) {
this.hls = void 0;
this.loaders = Object.create(null);
this.checkAgeHeader = true;
this.hls = hls;
this.registerListeners();
}
var _proto = PlaylistLoader.prototype;
_proto.registerListeners = function registerListeners() {
var hls = this.hls;
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADING, this.onManifestLoading, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_LOADING, this.onLevelLoading, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].AUDIO_TRACK_LOADING, this.onAudioTrackLoading, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_TRACK_LOADING, this.onSubtitleTrackLoading, this);
};
_proto.unregisterListeners = function unregisterListeners() {
var hls = this.hls;
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADING, this.onManifestLoading, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_LOADING, this.onLevelLoading, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].AUDIO_TRACK_LOADING, this.onAudioTrackLoading, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_TRACK_LOADING, this.onSubtitleTrackLoading, this);
}
/**
* Returns defaults or configured loader-type overloads (pLoader and loader config params)
*/
;
_proto.createInternalLoader = function createInternalLoader(context) {
var config = this.hls.config;
var PLoader = config.pLoader;
var Loader = config.loader;
var InternalLoader = PLoader || Loader;
var loader = new InternalLoader(config);
context.loader = loader;
this.loaders[context.type] = loader;
return loader;
};
_proto.getInternalLoader = function getInternalLoader(context) {
return this.loaders[context.type];
};
_proto.resetInternalLoader = function resetInternalLoader(contextType) {
if (this.loaders[contextType]) {
delete this.loaders[contextType];
}
}
/**
* Call `destroy` on all internal loader instances mapped (one per context type)
*/
;
_proto.destroyInternalLoaders = function destroyInternalLoaders() {
for (var contextType in this.loaders) {
var loader = this.loaders[contextType];
if (loader) {
loader.destroy();
}
this.resetInternalLoader(contextType);
}
};
_proto.destroy = function destroy() {
this.unregisterListeners();
this.destroyInternalLoaders();
};
_proto.onManifestLoading = function onManifestLoading(event, data) {
var url = data.url;
this.checkAgeHeader = true;
this.load({
id: null,
groupId: null,
level: 0,
responseType: 'text',
type: _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].MANIFEST,
url: url,
deliveryDirectives: null
});
};
_proto.onLevelLoading = function onLevelLoading(event, data) {
var id = data.id,
level = data.level,
url = data.url,
deliveryDirectives = data.deliveryDirectives;
this.load({
id: id,
groupId: null,
level: level,
responseType: 'text',
type: _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].LEVEL,
url: url,
deliveryDirectives: deliveryDirectives
});
};
_proto.onAudioTrackLoading = function onAudioTrackLoading(event, data) {
var id = data.id,
groupId = data.groupId,
url = data.url,
deliveryDirectives = data.deliveryDirectives;
this.load({
id: id,
groupId: groupId,
level: null,
responseType: 'text',
type: _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].AUDIO_TRACK,
url: url,
deliveryDirectives: deliveryDirectives
});
};
_proto.onSubtitleTrackLoading = function onSubtitleTrackLoading(event, data) {
var id = data.id,
groupId = data.groupId,
url = data.url,
deliveryDirectives = data.deliveryDirectives;
this.load({
id: id,
groupId: groupId,
level: null,
responseType: 'text',
type: _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].SUBTITLE_TRACK,
url: url,
deliveryDirectives: deliveryDirectives
});
};
_proto.load = function load(context) {
var _context$deliveryDire;
var config = this.hls.config; // logger.debug(`[playlist-loader]: Loading playlist of type ${context.type}, level: ${context.level}, id: ${context.id}`);
// Check if a loader for this context already exists
var loader = this.getInternalLoader(context);
if (loader) {
var loaderContext = loader.context;
if (loaderContext && loaderContext.url === context.url) {
// same URL can't overlap
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].trace('[playlist-loader]: playlist request ongoing');
return;
}
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].log("[playlist-loader]: aborting previous loader for type: " + context.type);
loader.abort();
}
var maxRetry;
var timeout;
var retryDelay;
var maxRetryDelay; // apply different configs for retries depending on
// context (manifest, level, audio/subs playlist)
switch (context.type) {
case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].MANIFEST:
maxRetry = config.manifestLoadingMaxRetry;
timeout = config.manifestLoadingTimeOut;
retryDelay = config.manifestLoadingRetryDelay;
maxRetryDelay = config.manifestLoadingMaxRetryTimeout;
break;
case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].LEVEL:
case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].AUDIO_TRACK:
case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].SUBTITLE_TRACK:
// Manage retries in Level/Track Controller
maxRetry = 0;
timeout = config.levelLoadingTimeOut;
break;
default:
maxRetry = config.levelLoadingMaxRetry;
timeout = config.levelLoadingTimeOut;
retryDelay = config.levelLoadingRetryDelay;
maxRetryDelay = config.levelLoadingMaxRetryTimeout;
break;
}
loader = this.createInternalLoader(context); // Override level/track timeout for LL-HLS requests
// (the default of 10000ms is counter productive to blocking playlist reload requests)
if ((_context$deliveryDire = context.deliveryDirectives) !== null && _context$deliveryDire !== void 0 && _context$deliveryDire.part) {
var levelDetails;
if (context.type === _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].LEVEL && context.level !== null) {
levelDetails = this.hls.levels[context.level].details;
} else if (context.type === _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].AUDIO_TRACK && context.id !== null) {
levelDetails = this.hls.audioTracks[context.id].details;
} else if (context.type === _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].SUBTITLE_TRACK && context.id !== null) {
levelDetails = this.hls.subtitleTracks[context.id].details;
}
if (levelDetails) {
var partTarget = levelDetails.partTarget;
var targetDuration = levelDetails.targetduration;
if (partTarget && targetDuration) {
timeout = Math.min(Math.max(partTarget * 3, targetDuration * 0.8) * 1000, timeout);
}
}
}
var loaderConfig = {
timeout: timeout,
maxRetry: maxRetry,
retryDelay: retryDelay,
maxRetryDelay: maxRetryDelay,
highWaterMark: 0
};
var loaderCallbacks = {
onSuccess: this.loadsuccess.bind(this),
onError: this.loaderror.bind(this),
onTimeout: this.loadtimeout.bind(this)
}; // logger.debug(`[playlist-loader]: Calling internal loader delegate for URL: ${context.url}`);
loader.load(context, loaderConfig, loaderCallbacks);
};
_proto.loadsuccess = function loadsuccess(response, stats, context, networkDetails) {
if (networkDetails === void 0) {
networkDetails = null;
}
if (context.isSidxRequest) {
this.handleSidxRequest(response, context);
this.handlePlaylistLoaded(response, stats, context, networkDetails);
return;
}
this.resetInternalLoader(context.type);
var string = response.data; // Validate if it is an M3U8 at all
if (string.indexOf('#EXTM3U') !== 0) {
this.handleManifestParsingError(response, context, 'no EXTM3U delimiter', networkDetails);
return;
}
stats.parsing.start = performance.now(); // Check if chunk-list or master. handle empty chunk list case (first EXTINF not signaled, but TARGETDURATION present)
if (string.indexOf('#EXTINF:') > 0 || string.indexOf('#EXT-X-TARGETDURATION:') > 0) {
this.handleTrackOrLevelPlaylist(response, stats, context, networkDetails);
} else {
this.handleMasterPlaylist(response, stats, context, networkDetails);
}
};
_proto.loaderror = function loaderror(response, context, networkDetails) {
if (networkDetails === void 0) {
networkDetails = null;
}
this.handleNetworkError(context, networkDetails, false, response);
};
_proto.loadtimeout = function loadtimeout(stats, context, networkDetails) {
if (networkDetails === void 0) {
networkDetails = null;
}
this.handleNetworkError(context, networkDetails, true);
};
_proto.handleMasterPlaylist = function handleMasterPlaylist(response, stats, context, networkDetails) {
var hls = this.hls;
var string = response.data;
var url = getResponseUrl(response, context);
var _M3U8Parser$parseMast = _m3u8_parser__WEBPACK_IMPORTED_MODULE_5__["default"].parseMasterPlaylist(string, url),
levels = _M3U8Parser$parseMast.levels,
sessionData = _M3U8Parser$parseMast.sessionData;
if (!levels.length) {
this.handleManifestParsingError(response, context, 'no level found in manifest', networkDetails);
return;
} // multi level playlist, parse level info
var audioGroups = levels.map(function (level) {
return {
id: level.attrs.AUDIO,
audioCodec: level.audioCodec
};
});
var subtitleGroups = levels.map(function (level) {
return {
id: level.attrs.SUBTITLES,
textCodec: level.textCodec
};
});
var audioTracks = _m3u8_parser__WEBPACK_IMPORTED_MODULE_5__["default"].parseMasterPlaylistMedia(string, url, 'AUDIO', audioGroups);
var subtitles = _m3u8_parser__WEBPACK_IMPORTED_MODULE_5__["default"].parseMasterPlaylistMedia(string, url, 'SUBTITLES', subtitleGroups);
var captions = _m3u8_parser__WEBPACK_IMPORTED_MODULE_5__["default"].parseMasterPlaylistMedia(string, url, 'CLOSED-CAPTIONS');
if (audioTracks.length) {
// check if we have found an audio track embedded in main playlist (audio track without URI attribute)
var embeddedAudioFound = audioTracks.some(function (audioTrack) {
return !audioTrack.url;
}); // if no embedded audio track defined, but audio codec signaled in quality level,
// we need to signal this main audio track this could happen with playlists with
// alt audio rendition in which quality levels (main)
// contains both audio+video. but with mixed audio track not signaled
if (!embeddedAudioFound && levels[0].audioCodec && !levels[0].attrs.AUDIO) {
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].log('[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one');
audioTracks.unshift({
type: 'main',
name: 'main',
default: false,
autoselect: false,
forced: false,
id: -1,
attrs: new _utils_attr_list__WEBPACK_IMPORTED_MODULE_7__["AttrList"]({}),
bitrate: 0,
url: ''
});
}
}
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADED, {
levels: levels,
audioTracks: audioTracks,
subtitles: subtitles,
captions: captions,
url: url,
stats: stats,
networkDetails: networkDetails,
sessionData: sessionData
});
};
_proto.handleTrackOrLevelPlaylist = function handleTrackOrLevelPlaylist(response, stats, context, networkDetails) {
var hls = this.hls;
var id = context.id,
level = context.level,
type = context.type;
var url = getResponseUrl(response, context);
var levelUrlId = Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(id) ? id : 0;
var levelId = Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(level) ? level : levelUrlId;
var levelType = mapContextToLevelType(context);
var levelDetails = _m3u8_parser__WEBPACK_IMPORTED_MODULE_5__["default"].parseLevelPlaylist(response.data, url, levelId, levelType, levelUrlId);
if (!levelDetails.fragments.length) {
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorTypes"].NETWORK_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].LEVEL_EMPTY_ERROR,
fatal: false,
url: url,
reason: 'no fragments found in level',
level: typeof context.level === 'number' ? context.level : undefined
});
return;
} // We have done our first request (Manifest-type) and receive
// not a master playlist but a chunk-list (track/level)
// We fire the manifest-loaded event anyway with the parsed level-details
// by creating a single-level structure for it.
if (type === _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].MANIFEST) {
var singleLevel = {
attrs: new _utils_attr_list__WEBPACK_IMPORTED_MODULE_7__["AttrList"]({}),
bitrate: 0,
details: levelDetails,
name: '',
url: url
};
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADED, {
levels: [singleLevel],
audioTracks: [],
url: url,
stats: stats,
networkDetails: networkDetails,
sessionData: null
});
} // save parsing time
stats.parsing.end = performance.now(); // in case we need SIDX ranges
// return early after calling load for
// the SIDX box.
if (levelDetails.needSidxRanges) {
var sidxUrl = levelDetails.initSegment.url;
this.load({
url: sidxUrl,
isSidxRequest: true,
type: type,
level: level,
levelDetails: levelDetails,
id: id,
groupId: null,
rangeStart: 0,
rangeEnd: 2048,
responseType: 'arraybuffer',
deliveryDirectives: null
});
return;
} // extend the context with the new levelDetails property
context.levelDetails = levelDetails;
this.handlePlaylistLoaded(response, stats, context, networkDetails);
};
_proto.handleSidxRequest = function handleSidxRequest(response, context) {
var sidxInfo = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_4__["parseSegmentIndex"])(new Uint8Array(response.data)); // if provided fragment does not contain sidx, early return
if (!sidxInfo) {
return;
}
var sidxReferences = sidxInfo.references;
var levelDetails = context.levelDetails;
sidxReferences.forEach(function (segmentRef, index) {
var segRefInfo = segmentRef.info;
var frag = levelDetails.fragments[index];
if (frag.byteRange.length === 0) {
frag.setByteRange(String(1 + segRefInfo.end - segRefInfo.start) + '@' + String(segRefInfo.start));
}
});
levelDetails.initSegment.setByteRange(String(sidxInfo.moovEndOffset) + '@0');
};
_proto.handleManifestParsingError = function handleManifestParsingError(response, context, reason, networkDetails) {
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorTypes"].NETWORK_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].MANIFEST_PARSING_ERROR,
fatal: context.type === _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].MANIFEST,
url: response.url,
reason: reason,
response: response,
context: context,
networkDetails: networkDetails
});
};
_proto.handleNetworkError = function handleNetworkError(context, networkDetails, timeout, response) {
if (timeout === void 0) {
timeout = false;
}
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn("[playlist-loader]: A network " + (timeout ? 'timeout' : 'error') + " occurred while loading " + context.type + " level: " + context.level + " id: " + context.id + " group-id: \"" + context.groupId + "\"");
var details = _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].UNKNOWN;
var fatal = false;
var loader = this.getInternalLoader(context);
switch (context.type) {
case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].MANIFEST:
details = timeout ? _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].MANIFEST_LOAD_TIMEOUT : _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].MANIFEST_LOAD_ERROR;
fatal = true;
break;
case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].LEVEL:
details = timeout ? _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].LEVEL_LOAD_TIMEOUT : _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].LEVEL_LOAD_ERROR;
fatal = false;
break;
case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].AUDIO_TRACK:
details = timeout ? _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].AUDIO_TRACK_LOAD_TIMEOUT : _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].AUDIO_TRACK_LOAD_ERROR;
fatal = false;
break;
case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].SUBTITLE_TRACK:
details = timeout ? _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].SUBTITLE_TRACK_LOAD_TIMEOUT : _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].SUBTITLE_LOAD_ERROR;
fatal = false;
break;
}
if (loader) {
this.resetInternalLoader(context.type);
}
var errorData = {
type: _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorTypes"].NETWORK_ERROR,
details: details,
fatal: fatal,
url: context.url,
loader: loader,
context: context,
networkDetails: networkDetails
};
if (response) {
errorData.response = response;
}
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, errorData);
};
_proto.handlePlaylistLoaded = function handlePlaylistLoaded(response, stats, context, networkDetails) {
var type = context.type,
level = context.level,
id = context.id,
groupId = context.groupId,
loader = context.loader,
levelDetails = context.levelDetails,
deliveryDirectives = context.deliveryDirectives;
if (!(levelDetails !== null && levelDetails !== void 0 && levelDetails.targetduration)) {
this.handleManifestParsingError(response, context, 'invalid target duration', networkDetails);
return;
}
if (!loader) {
return;
} // Avoid repeated browser error log `Refused to get unsafe header "age"` when unnecessary or past attempts failed
var checkAgeHeader = this.checkAgeHeader && levelDetails.live;
var ageHeader = checkAgeHeader ? loader.getResponseHeader('age') : null;
levelDetails.ageHeader = ageHeader ? parseFloat(ageHeader) : 0;
this.checkAgeHeader = !!ageHeader;
switch (type) {
case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].MANIFEST:
case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].LEVEL:
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_LOADED, {
details: levelDetails,
level: level || 0,
id: id || 0,
stats: stats,
networkDetails: networkDetails,
deliveryDirectives: deliveryDirectives
});
break;
case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].AUDIO_TRACK:
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].AUDIO_TRACK_LOADED, {
details: levelDetails,
id: id || 0,
groupId: groupId || '',
stats: stats,
networkDetails: networkDetails,
deliveryDirectives: deliveryDirectives
});
break;
case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].SUBTITLE_TRACK:
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_TRACK_LOADED, {
details: levelDetails,
id: id || 0,
groupId: groupId || '',
stats: stats,
networkDetails: networkDetails,
deliveryDirectives: deliveryDirectives
});
break;
}
};
return PlaylistLoader;
}();
/* harmony default export */ __webpack_exports__["default"] = (PlaylistLoader);
/***/ }),
/***/ "./src/polyfills/number.ts":
/*!*********************************!*\
!*** ./src/polyfills/number.ts ***!
\*********************************/
/*! exports provided: isFiniteNumber, MAX_SAFE_INTEGER */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isFiniteNumber", function() { return isFiniteNumber; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MAX_SAFE_INTEGER", function() { return MAX_SAFE_INTEGER; });
var isFiniteNumber = Number.isFinite || function (value) {
return typeof value === 'number' && isFinite(value);
};
var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991;
/***/ }),
/***/ "./src/remux/aac-helper.ts":
/*!*********************************!*\
!*** ./src/remux/aac-helper.ts ***!
\*********************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/**
* AAC helper
*/
var AAC = /*#__PURE__*/function () {
function AAC() {}
AAC.getSilentFrame = function getSilentFrame(codec, channelCount) {
switch (codec) {
case 'mp4a.40.2':
if (channelCount === 1) {
return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x23, 0x80]);
} else if (channelCount === 2) {
return new Uint8Array([0x21, 0x00, 0x49, 0x90, 0x02, 0x19, 0x00, 0x23, 0x80]);
} else if (channelCount === 3) {
return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x8e]);
} else if (channelCount === 4) {
return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x80, 0x2c, 0x80, 0x08, 0x02, 0x38]);
} else if (channelCount === 5) {
return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x38]);
} else if (channelCount === 6) {
return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x00, 0xb2, 0x00, 0x20, 0x08, 0xe0]);
}
break;
// handle HE-AAC below (mp4a.40.5 / mp4a.40.29)
default:
if (channelCount === 1) {
// ffmpeg -y -f lavfi -i "aevalsrc=0:d=0.05" -c:a libfdk_aac -profile:a aac_he -b:a 4k output.aac && hexdump -v -e '16/1 "0x%x," "\n"' -v output.aac
return new Uint8Array([0x1, 0x40, 0x22, 0x80, 0xa3, 0x4e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0, 0x0, 0x1c, 0x6, 0xf1, 0xc1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5e]);
} else if (channelCount === 2) {
// ffmpeg -y -f lavfi -i "aevalsrc=0|0:d=0.05" -c:a libfdk_aac -profile:a aac_he_v2 -b:a 4k output.aac && hexdump -v -e '16/1 "0x%x," "\n"' -v output.aac
return new Uint8Array([0x1, 0x40, 0x22, 0x80, 0xa3, 0x5e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0, 0x0, 0x0, 0x95, 0x0, 0x6, 0xf1, 0xa1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5e]);
} else if (channelCount === 3) {
// ffmpeg -y -f lavfi -i "aevalsrc=0|0|0:d=0.05" -c:a libfdk_aac -profile:a aac_he_v2 -b:a 4k output.aac && hexdump -v -e '16/1 "0x%x," "\n"' -v output.aac
return new Uint8Array([0x1, 0x40, 0x22, 0x80, 0xa3, 0x5e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0, 0x0, 0x0, 0x95, 0x0, 0x6, 0xf1, 0xa1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5e]);
}
break;
}
return undefined;
};
return AAC;
}();
/* harmony default export */ __webpack_exports__["default"] = (AAC);
/***/ }),
/***/ "./src/remux/mp4-generator.ts":
/*!************************************!*\
!*** ./src/remux/mp4-generator.ts ***!
\************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/**
* Generate MP4 Box
*/
var UINT32_MAX = Math.pow(2, 32) - 1;
var MP4 = /*#__PURE__*/function () {
function MP4() {}
MP4.init = function init() {
MP4.types = {
avc1: [],
// codingname
avcC: [],
btrt: [],
dinf: [],
dref: [],
esds: [],
ftyp: [],
hdlr: [],
mdat: [],
mdhd: [],
mdia: [],
mfhd: [],
minf: [],
moof: [],
moov: [],
mp4a: [],
'.mp3': [],
mvex: [],
mvhd: [],
pasp: [],
sdtp: [],
stbl: [],
stco: [],
stsc: [],
stsd: [],
stsz: [],
stts: [],
tfdt: [],
tfhd: [],
traf: [],
trak: [],
trun: [],
trex: [],
tkhd: [],
vmhd: [],
smhd: []
};
var i;
for (i in MP4.types) {
if (MP4.types.hasOwnProperty(i)) {
MP4.types[i] = [i.charCodeAt(0), i.charCodeAt(1), i.charCodeAt(2), i.charCodeAt(3)];
}
}
var videoHdlr = new Uint8Array([0x00, // version 0
0x00, 0x00, 0x00, // flags
0x00, 0x00, 0x00, 0x00, // pre_defined
0x76, 0x69, 0x64, 0x65, // handler_type: 'vide'
0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x00, 0x00, 0x00, // reserved
0x56, 0x69, 0x64, 0x65, 0x6f, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'VideoHandler'
]);
var audioHdlr = new Uint8Array([0x00, // version 0
0x00, 0x00, 0x00, // flags
0x00, 0x00, 0x00, 0x00, // pre_defined
0x73, 0x6f, 0x75, 0x6e, // handler_type: 'soun'
0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x00, 0x00, 0x00, // reserved
0x53, 0x6f, 0x75, 0x6e, 0x64, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'SoundHandler'
]);
MP4.HDLR_TYPES = {
video: videoHdlr,
audio: audioHdlr
};
var dref = new Uint8Array([0x00, // version 0
0x00, 0x00, 0x00, // flags
0x00, 0x00, 0x00, 0x01, // entry_count
0x00, 0x00, 0x00, 0x0c, // entry_size
0x75, 0x72, 0x6c, 0x20, // 'url' type
0x00, // version 0
0x00, 0x00, 0x01 // entry_flags
]);
var stco = new Uint8Array([0x00, // version
0x00, 0x00, 0x00, // flags
0x00, 0x00, 0x00, 0x00 // entry_count
]);
MP4.STTS = MP4.STSC = MP4.STCO = stco;
MP4.STSZ = new Uint8Array([0x00, // version
0x00, 0x00, 0x00, // flags
0x00, 0x00, 0x00, 0x00, // sample_size
0x00, 0x00, 0x00, 0x00 // sample_count
]);
MP4.VMHD = new Uint8Array([0x00, // version
0x00, 0x00, 0x01, // flags
0x00, 0x00, // graphicsmode
0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // opcolor
]);
MP4.SMHD = new Uint8Array([0x00, // version
0x00, 0x00, 0x00, // flags
0x00, 0x00, // balance
0x00, 0x00 // reserved
]);
MP4.STSD = new Uint8Array([0x00, // version 0
0x00, 0x00, 0x00, // flags
0x00, 0x00, 0x00, 0x01]); // entry_count
var majorBrand = new Uint8Array([105, 115, 111, 109]); // isom
var avc1Brand = new Uint8Array([97, 118, 99, 49]); // avc1
var minorVersion = new Uint8Array([0, 0, 0, 1]);
MP4.FTYP = MP4.box(MP4.types.ftyp, majorBrand, minorVersion, majorBrand, avc1Brand);
MP4.DINF = MP4.box(MP4.types.dinf, MP4.box(MP4.types.dref, dref));
};
MP4.box = function box(type) {
var size = 8;
for (var _len = arguments.length, payload = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
payload[_key - 1] = arguments[_key];
}
var i = payload.length;
var len = i; // calculate the total size we need to allocate
while (i--) {
size += payload[i].byteLength;
}
var result = new Uint8Array(size);
result[0] = size >> 24 & 0xff;
result[1] = size >> 16 & 0xff;
result[2] = size >> 8 & 0xff;
result[3] = size & 0xff;
result.set(type, 4); // copy the payload into the result
for (i = 0, size = 8; i < len; i++) {
// copy payload[i] array @ offset size
result.set(payload[i], size);
size += payload[i].byteLength;
}
return result;
};
MP4.hdlr = function hdlr(type) {
return MP4.box(MP4.types.hdlr, MP4.HDLR_TYPES[type]);
};
MP4.mdat = function mdat(data) {
return MP4.box(MP4.types.mdat, data);
};
MP4.mdhd = function mdhd(timescale, duration) {
duration *= timescale;
var upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
var lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
return MP4.box(MP4.types.mdhd, new Uint8Array([0x01, // version 1
0x00, 0x00, 0x00, // flags
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, // creation_time
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, // modification_time
timescale >> 24 & 0xff, timescale >> 16 & 0xff, timescale >> 8 & 0xff, timescale & 0xff, // timescale
upperWordDuration >> 24, upperWordDuration >> 16 & 0xff, upperWordDuration >> 8 & 0xff, upperWordDuration & 0xff, lowerWordDuration >> 24, lowerWordDuration >> 16 & 0xff, lowerWordDuration >> 8 & 0xff, lowerWordDuration & 0xff, 0x55, 0xc4, // 'und' language (undetermined)
0x00, 0x00]));
};
MP4.mdia = function mdia(track) {
return MP4.box(MP4.types.mdia, MP4.mdhd(track.timescale, track.duration), MP4.hdlr(track.type), MP4.minf(track));
};
MP4.mfhd = function mfhd(sequenceNumber) {
return MP4.box(MP4.types.mfhd, new Uint8Array([0x00, 0x00, 0x00, 0x00, // flags
sequenceNumber >> 24, sequenceNumber >> 16 & 0xff, sequenceNumber >> 8 & 0xff, sequenceNumber & 0xff // sequence_number
]));
};
MP4.minf = function minf(track) {
if (track.type === 'audio') {
return MP4.box(MP4.types.minf, MP4.box(MP4.types.smhd, MP4.SMHD), MP4.DINF, MP4.stbl(track));
} else {
return MP4.box(MP4.types.minf, MP4.box(MP4.types.vmhd, MP4.VMHD), MP4.DINF, MP4.stbl(track));
}
};
MP4.moof = function moof(sn, baseMediaDecodeTime, track) {
return MP4.box(MP4.types.moof, MP4.mfhd(sn), MP4.traf(track, baseMediaDecodeTime));
}
/**
* @param tracks... (optional) {array} the tracks associated with this movie
*/
;
MP4.moov = function moov(tracks) {
var i = tracks.length;
var boxes = [];
while (i--) {
boxes[i] = MP4.trak(tracks[i]);
}
return MP4.box.apply(null, [MP4.types.moov, MP4.mvhd(tracks[0].timescale, tracks[0].duration)].concat(boxes).concat(MP4.mvex(tracks)));
};
MP4.mvex = function mvex(tracks) {
var i = tracks.length;
var boxes = [];
while (i--) {
boxes[i] = MP4.trex(tracks[i]);
}
return MP4.box.apply(null, [MP4.types.mvex].concat(boxes));
};
MP4.mvhd = function mvhd(timescale, duration) {
duration *= timescale;
var upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
var lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
var bytes = new Uint8Array([0x01, // version 1
0x00, 0x00, 0x00, // flags
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, // creation_time
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, // modification_time
timescale >> 24 & 0xff, timescale >> 16 & 0xff, timescale >> 8 & 0xff, timescale & 0xff, // timescale
upperWordDuration >> 24, upperWordDuration >> 16 & 0xff, upperWordDuration >> 8 & 0xff, upperWordDuration & 0xff, lowerWordDuration >> 24, lowerWordDuration >> 16 & 0xff, lowerWordDuration >> 8 & 0xff, lowerWordDuration & 0xff, 0x00, 0x01, 0x00, 0x00, // 1.0 rate
0x01, 0x00, // 1.0 volume
0x00, 0x00, // reserved
0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, // transformation: unity matrix
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pre_defined
0xff, 0xff, 0xff, 0xff // next_track_ID
]);
return MP4.box(MP4.types.mvhd, bytes);
};
MP4.sdtp = function sdtp(track) {
var samples = track.samples || [];
var bytes = new Uint8Array(4 + samples.length);
var i;
var flags; // leave the full box header (4 bytes) all zero
// write the sample table
for (i = 0; i < samples.length; i++) {
flags = samples[i].flags;
bytes[i + 4] = flags.dependsOn << 4 | flags.isDependedOn << 2 | flags.hasRedundancy;
}
return MP4.box(MP4.types.sdtp, bytes);
};
MP4.stbl = function stbl(track) {
return MP4.box(MP4.types.stbl, MP4.stsd(track), MP4.box(MP4.types.stts, MP4.STTS), MP4.box(MP4.types.stsc, MP4.STSC), MP4.box(MP4.types.stsz, MP4.STSZ), MP4.box(MP4.types.stco, MP4.STCO));
};
MP4.avc1 = function avc1(track) {
var sps = [];
var pps = [];
var i;
var data;
var len; // assemble the SPSs
for (i = 0; i < track.sps.length; i++) {
data = track.sps[i];
len = data.byteLength;
sps.push(len >>> 8 & 0xff);
sps.push(len & 0xff); // SPS
sps = sps.concat(Array.prototype.slice.call(data));
} // assemble the PPSs
for (i = 0; i < track.pps.length; i++) {
data = track.pps[i];
len = data.byteLength;
pps.push(len >>> 8 & 0xff);
pps.push(len & 0xff);
pps = pps.concat(Array.prototype.slice.call(data));
}
var avcc = MP4.box(MP4.types.avcC, new Uint8Array([0x01, // version
sps[3], // profile
sps[4], // profile compat
sps[5], // level
0xfc | 3, // lengthSizeMinusOne, hard-coded to 4 bytes
0xe0 | track.sps.length // 3bit reserved (111) + numOfSequenceParameterSets
].concat(sps).concat([track.pps.length // numOfPictureParameterSets
]).concat(pps))); // "PPS"
var width = track.width;
var height = track.height;
var hSpacing = track.pixelRatio[0];
var vSpacing = track.pixelRatio[1];
return MP4.box(MP4.types.avc1, new Uint8Array([0x00, 0x00, 0x00, // reserved
0x00, 0x00, 0x00, // reserved
0x00, 0x01, // data_reference_index
0x00, 0x00, // pre_defined
0x00, 0x00, // reserved
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pre_defined
width >> 8 & 0xff, width & 0xff, // width
height >> 8 & 0xff, height & 0xff, // height
0x00, 0x48, 0x00, 0x00, // horizresolution
0x00, 0x48, 0x00, 0x00, // vertresolution
0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x01, // frame_count
0x12, 0x64, 0x61, 0x69, 0x6c, // dailymotion/hls.js
0x79, 0x6d, 0x6f, 0x74, 0x69, 0x6f, 0x6e, 0x2f, 0x68, 0x6c, 0x73, 0x2e, 0x6a, 0x73, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // compressorname
0x00, 0x18, // depth = 24
0x11, 0x11]), // pre_defined = -1
avcc, MP4.box(MP4.types.btrt, new Uint8Array([0x00, 0x1c, 0x9c, 0x80, // bufferSizeDB
0x00, 0x2d, 0xc6, 0xc0, // maxBitrate
0x00, 0x2d, 0xc6, 0xc0])), // avgBitrate
MP4.box(MP4.types.pasp, new Uint8Array([hSpacing >> 24, // hSpacing
hSpacing >> 16 & 0xff, hSpacing >> 8 & 0xff, hSpacing & 0xff, vSpacing >> 24, // vSpacing
vSpacing >> 16 & 0xff, vSpacing >> 8 & 0xff, vSpacing & 0xff])));
};
MP4.esds = function esds(track) {
var configlen = track.config.length;
return new Uint8Array([0x00, // version 0
0x00, 0x00, 0x00, // flags
0x03, // descriptor_type
0x17 + configlen, // length
0x00, 0x01, // es_id
0x00, // stream_priority
0x04, // descriptor_type
0x0f + configlen, // length
0x40, // codec : mpeg4_audio
0x15, // stream_type
0x00, 0x00, 0x00, // buffer_size
0x00, 0x00, 0x00, 0x00, // maxBitrate
0x00, 0x00, 0x00, 0x00, // avgBitrate
0x05 // descriptor_type
].concat([configlen]).concat(track.config).concat([0x06, 0x01, 0x02])); // GASpecificConfig)); // length + audio config descriptor
};
MP4.mp4a = function mp4a(track) {
var samplerate = track.samplerate;
return MP4.box(MP4.types.mp4a, new Uint8Array([0x00, 0x00, 0x00, // reserved
0x00, 0x00, 0x00, // reserved
0x00, 0x01, // data_reference_index
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
0x00, track.channelCount, // channelcount
0x00, 0x10, // sampleSize:16bits
0x00, 0x00, 0x00, 0x00, // reserved2
samplerate >> 8 & 0xff, samplerate & 0xff, //
0x00, 0x00]), MP4.box(MP4.types.esds, MP4.esds(track)));
};
MP4.mp3 = function mp3(track) {
var samplerate = track.samplerate;
return MP4.box(MP4.types['.mp3'], new Uint8Array([0x00, 0x00, 0x00, // reserved
0x00, 0x00, 0x00, // reserved
0x00, 0x01, // data_reference_index
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
0x00, track.channelCount, // channelcount
0x00, 0x10, // sampleSize:16bits
0x00, 0x00, 0x00, 0x00, // reserved2
samplerate >> 8 & 0xff, samplerate & 0xff, //
0x00, 0x00]));
};
MP4.stsd = function stsd(track) {
if (track.type === 'audio') {
if (!track.isAAC && track.codec === 'mp3') {
return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp3(track));
}
return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp4a(track));
} else {
return MP4.box(MP4.types.stsd, MP4.STSD, MP4.avc1(track));
}
};
MP4.tkhd = function tkhd(track) {
var id = track.id;
var duration = track.duration * track.timescale;
var width = track.width;
var height = track.height;
var upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
var lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
return MP4.box(MP4.types.tkhd, new Uint8Array([0x01, // version 1
0x00, 0x00, 0x07, // flags
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, // creation_time
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, // modification_time
id >> 24 & 0xff, id >> 16 & 0xff, id >> 8 & 0xff, id & 0xff, // track_ID
0x00, 0x00, 0x00, 0x00, // reserved
upperWordDuration >> 24, upperWordDuration >> 16 & 0xff, upperWordDuration >> 8 & 0xff, upperWordDuration & 0xff, lowerWordDuration >> 24, lowerWordDuration >> 16 & 0xff, lowerWordDuration >> 8 & 0xff, lowerWordDuration & 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x00, // layer
0x00, 0x00, // alternate_group
0x00, 0x00, // non-audio track volume
0x00, 0x00, // reserved
0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, // transformation: unity matrix
width >> 8 & 0xff, width & 0xff, 0x00, 0x00, // width
height >> 8 & 0xff, height & 0xff, 0x00, 0x00 // height
]));
};
MP4.traf = function traf(track, baseMediaDecodeTime) {
var sampleDependencyTable = MP4.sdtp(track);
var id = track.id;
var upperWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1));
var lowerWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1));
return MP4.box(MP4.types.traf, MP4.box(MP4.types.tfhd, new Uint8Array([0x00, // version 0
0x00, 0x00, 0x00, // flags
id >> 24, id >> 16 & 0xff, id >> 8 & 0xff, id & 0xff // track_ID
])), MP4.box(MP4.types.tfdt, new Uint8Array([0x01, // version 1
0x00, 0x00, 0x00, // flags
upperWordBaseMediaDecodeTime >> 24, upperWordBaseMediaDecodeTime >> 16 & 0xff, upperWordBaseMediaDecodeTime >> 8 & 0xff, upperWordBaseMediaDecodeTime & 0xff, lowerWordBaseMediaDecodeTime >> 24, lowerWordBaseMediaDecodeTime >> 16 & 0xff, lowerWordBaseMediaDecodeTime >> 8 & 0xff, lowerWordBaseMediaDecodeTime & 0xff])), MP4.trun(track, sampleDependencyTable.length + 16 + // tfhd
20 + // tfdt
8 + // traf header
16 + // mfhd
8 + // moof header
8), // mdat header
sampleDependencyTable);
}
/**
* Generate a track box.
* @param track {object} a track definition
* @return {Uint8Array} the track box
*/
;
MP4.trak = function trak(track) {
track.duration = track.duration || 0xffffffff;
return MP4.box(MP4.types.trak, MP4.tkhd(track), MP4.mdia(track));
};
MP4.trex = function trex(track) {
var id = track.id;
return MP4.box(MP4.types.trex, new Uint8Array([0x00, // version 0
0x00, 0x00, 0x00, // flags
id >> 24, id >> 16 & 0xff, id >> 8 & 0xff, id & 0xff, // track_ID
0x00, 0x00, 0x00, 0x01, // default_sample_description_index
0x00, 0x00, 0x00, 0x00, // default_sample_duration
0x00, 0x00, 0x00, 0x00, // default_sample_size
0x00, 0x01, 0x00, 0x01 // default_sample_flags
]));
};
MP4.trun = function trun(track, offset) {
var samples = track.samples || [];
var len = samples.length;
var arraylen = 12 + 16 * len;
var array = new Uint8Array(arraylen);
var i;
var sample;
var duration;
var size;
var flags;
var cts;
offset += 8 + arraylen;
array.set([0x00, // version 0
0x00, 0x0f, 0x01, // flags
len >>> 24 & 0xff, len >>> 16 & 0xff, len >>> 8 & 0xff, len & 0xff, // sample_count
offset >>> 24 & 0xff, offset >>> 16 & 0xff, offset >>> 8 & 0xff, offset & 0xff // data_offset
], 0);
for (i = 0; i < len; i++) {
sample = samples[i];
duration = sample.duration;
size = sample.size;
flags = sample.flags;
cts = sample.cts;
array.set([duration >>> 24 & 0xff, duration >>> 16 & 0xff, duration >>> 8 & 0xff, duration & 0xff, // sample_duration
size >>> 24 & 0xff, size >>> 16 & 0xff, size >>> 8 & 0xff, size & 0xff, // sample_size
flags.isLeading << 2 | flags.dependsOn, flags.isDependedOn << 6 | flags.hasRedundancy << 4 | flags.paddingValue << 1 | flags.isNonSync, flags.degradPrio & 0xf0 << 8, flags.degradPrio & 0x0f, // sample_flags
cts >>> 24 & 0xff, cts >>> 16 & 0xff, cts >>> 8 & 0xff, cts & 0xff // sample_composition_time_offset
], 12 + 16 * i);
}
return MP4.box(MP4.types.trun, array);
};
MP4.initSegment = function initSegment(tracks) {
if (!MP4.types) {
MP4.init();
}
var movie = MP4.moov(tracks);
var result = new Uint8Array(MP4.FTYP.byteLength + movie.byteLength);
result.set(MP4.FTYP);
result.set(movie, MP4.FTYP.byteLength);
return result;
};
return MP4;
}();
MP4.types = void 0;
MP4.HDLR_TYPES = void 0;
MP4.STTS = void 0;
MP4.STSC = void 0;
MP4.STCO = void 0;
MP4.STSZ = void 0;
MP4.VMHD = void 0;
MP4.SMHD = void 0;
MP4.STSD = void 0;
MP4.FTYP = void 0;
MP4.DINF = void 0;
/* harmony default export */ __webpack_exports__["default"] = (MP4);
/***/ }),
/***/ "./src/remux/mp4-remuxer.ts":
/*!**********************************!*\
!*** ./src/remux/mp4-remuxer.ts ***!
\**********************************/
/*! exports provided: default, normalizePts */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return MP4Remuxer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "normalizePts", function() { return normalizePts; });
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var _aac_helper__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./aac-helper */ "./src/remux/aac-helper.ts");
/* harmony import */ var _mp4_generator__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./mp4-generator */ "./src/remux/mp4-generator.ts");
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/* harmony import */ var _utils_timescale_conversion__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../utils/timescale-conversion */ "./src/utils/timescale-conversion.ts");
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
var MAX_SILENT_FRAME_DURATION = 10 * 1000; // 10 seconds
var AAC_SAMPLES_PER_FRAME = 1024;
var MPEG_AUDIO_SAMPLE_PER_FRAME = 1152;
var chromeVersion = null;
var safariWebkitVersion = null;
var requiresPositiveDts = false;
var MP4Remuxer = /*#__PURE__*/function () {
function MP4Remuxer(observer, config, typeSupported, vendor) {
if (vendor === void 0) {
vendor = '';
}
this.observer = void 0;
this.config = void 0;
this.typeSupported = void 0;
this.ISGenerated = false;
this._initPTS = void 0;
this._initDTS = void 0;
this.nextAvcDts = null;
this.nextAudioPts = null;
this.isAudioContiguous = false;
this.isVideoContiguous = false;
this.observer = observer;
this.config = config;
this.typeSupported = typeSupported;
this.ISGenerated = false;
if (chromeVersion === null) {
var userAgent = navigator.userAgent || '';
var result = userAgent.match(/Chrome\/(\d+)/i);
chromeVersion = result ? parseInt(result[1]) : 0;
}
if (safariWebkitVersion === null) {
var _result = navigator.userAgent.match(/Safari\/(\d+)/i);
safariWebkitVersion = _result ? parseInt(_result[1]) : 0;
}
requiresPositiveDts = !!chromeVersion && chromeVersion < 75 || !!safariWebkitVersion && safariWebkitVersion < 600;
}
var _proto = MP4Remuxer.prototype;
_proto.destroy = function destroy() {};
_proto.resetTimeStamp = function resetTimeStamp(defaultTimeStamp) {
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].log('[mp4-remuxer]: initPTS & initDTS reset');
this._initPTS = this._initDTS = defaultTimeStamp;
};
_proto.resetNextTimestamp = function resetNextTimestamp() {
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].log('[mp4-remuxer]: reset next timestamp');
this.isVideoContiguous = false;
this.isAudioContiguous = false;
};
_proto.resetInitSegment = function resetInitSegment() {
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].log('[mp4-remuxer]: ISGenerated flag reset');
this.ISGenerated = false;
};
_proto.getVideoStartPts = function getVideoStartPts(videoSamples) {
var rolloverDetected = false;
var startPTS = videoSamples.reduce(function (minPTS, sample) {
var delta = sample.pts - minPTS;
if (delta < -4294967296) {
// 2^32, see PTSNormalize for reasoning, but we're hitting a rollover here, and we don't want that to impact the timeOffset calculation
rolloverDetected = true;
return normalizePts(minPTS, sample.pts);
} else if (delta > 0) {
return minPTS;
} else {
return sample.pts;
}
}, videoSamples[0].pts);
if (rolloverDetected) {
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].debug('PTS rollover detected');
}
return startPTS;
};
_proto.remux = function remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, flush) {
var video;
var audio;
var initSegment;
var text;
var id3;
var independent;
var audioTimeOffset = timeOffset;
var videoTimeOffset = timeOffset; // If we're remuxing audio and video progressively, wait until we've received enough samples for each track before proceeding.
// This is done to synchronize the audio and video streams. We know if the current segment will have samples if the "pid"
// parameter is greater than -1. The pid is set when the PMT is parsed, which contains the tracks list.
// However, if the initSegment has already been generated, or we've reached the end of a segment (flush),
// then we can remux one track without waiting for the other.
var hasAudio = audioTrack.pid > -1;
var hasVideo = videoTrack.pid > -1;
var enoughAudioSamples = audioTrack.samples.length > 0;
var enoughVideoSamples = videoTrack.samples.length > 1;
var canRemuxAvc = (!hasAudio || enoughAudioSamples) && (!hasVideo || enoughVideoSamples) || this.ISGenerated || flush;
if (canRemuxAvc) {
if (!this.ISGenerated) {
initSegment = this.generateIS(audioTrack, videoTrack, timeOffset);
}
var isVideoContiguous = this.isVideoContiguous;
if (enoughVideoSamples && !isVideoContiguous && this.config.forceKeyFrameOnDiscontinuity) {
var length = videoTrack.samples.length;
var firstKeyFrameIndex = findKeyframeIndex(videoTrack.samples);
independent = true;
if (firstKeyFrameIndex > 0) {
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn("[mp4-remuxer]: Dropped " + firstKeyFrameIndex + " out of " + length + " video samples due to a missing keyframe");
var startPTS = this.getVideoStartPts(videoTrack.samples);
videoTrack.samples = videoTrack.samples.slice(firstKeyFrameIndex);
videoTrack.dropped += firstKeyFrameIndex;
videoTimeOffset += (videoTrack.samples[0].pts - startPTS) / (videoTrack.timescale || 90000);
} else if (firstKeyFrameIndex === -1) {
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn("[mp4-remuxer]: No keyframe found out of " + length + " video samples");
independent = false;
}
}
if (this.ISGenerated) {
if (enoughAudioSamples && enoughVideoSamples) {
// timeOffset is expected to be the offset of the first timestamp of this fragment (first DTS)
// if first audio DTS is not aligned with first video DTS then we need to take that into account
// when providing timeOffset to remuxAudio / remuxVideo. if we don't do that, there might be a permanent / small
// drift between audio and video streams
var _startPTS = this.getVideoStartPts(videoTrack.samples);
var tsDelta = normalizePts(audioTrack.samples[0].pts, _startPTS) - _startPTS;
var audiovideoTimestampDelta = tsDelta / videoTrack.inputTimeScale;
audioTimeOffset += Math.max(0, audiovideoTimestampDelta);
videoTimeOffset += Math.max(0, -audiovideoTimestampDelta);
} // Purposefully remuxing audio before video, so that remuxVideo can use nextAudioPts, which is calculated in remuxAudio.
if (enoughAudioSamples) {
// if initSegment was generated without audio samples, regenerate it again
if (!audioTrack.samplerate) {
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn('[mp4-remuxer]: regenerate InitSegment as audio detected');
initSegment = this.generateIS(audioTrack, videoTrack, timeOffset);
delete initSegment.video;
}
audio = this.remuxAudio(audioTrack, audioTimeOffset, this.isAudioContiguous, accurateTimeOffset, enoughVideoSamples ? videoTimeOffset : undefined);
if (enoughVideoSamples) {
var audioTrackLength = audio ? audio.endPTS - audio.startPTS : 0; // if initSegment was generated without video samples, regenerate it again
if (!videoTrack.inputTimeScale) {
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn('[mp4-remuxer]: regenerate InitSegment as video detected');
initSegment = this.generateIS(audioTrack, videoTrack, timeOffset);
}
video = this.remuxVideo(videoTrack, videoTimeOffset, isVideoContiguous, audioTrackLength);
}
} else if (enoughVideoSamples) {
video = this.remuxVideo(videoTrack, videoTimeOffset, isVideoContiguous, 0);
}
if (video && independent !== undefined) {
video.independent = independent;
}
}
} // Allow ID3 and text to remux, even if more audio/video samples are required
if (this.ISGenerated) {
if (id3Track.samples.length) {
id3 = this.remuxID3(id3Track, timeOffset);
}
if (textTrack.samples.length) {
text = this.remuxText(textTrack, timeOffset);
}
}
return {
audio: audio,
video: video,
initSegment: initSegment,
independent: independent,
text: text,
id3: id3
};
};
_proto.generateIS = function generateIS(audioTrack, videoTrack, timeOffset) {
var audioSamples = audioTrack.samples;
var videoSamples = videoTrack.samples;
var typeSupported = this.typeSupported;
var tracks = {};
var computePTSDTS = !Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(this._initPTS);
var container = 'audio/mp4';
var initPTS;
var initDTS;
var timescale;
if (computePTSDTS) {
initPTS = initDTS = Infinity;
}
if (audioTrack.config && audioSamples.length) {
// let's use audio sampling rate as MP4 time scale.
// rationale is that there is a integer nb of audio frames per audio sample (1024 for AAC)
// using audio sampling rate here helps having an integer MP4 frame duration
// this avoids potential rounding issue and AV sync issue
audioTrack.timescale = audioTrack.samplerate;
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].log("[mp4-remuxer]: audio sampling rate : " + audioTrack.samplerate);
if (!audioTrack.isAAC) {
if (typeSupported.mpeg) {
// Chrome and Safari
container = 'audio/mpeg';
audioTrack.codec = '';
} else if (typeSupported.mp3) {
// Firefox
audioTrack.codec = 'mp3';
}
}
tracks.audio = {
id: 'audio',
container: container,
codec: audioTrack.codec,
initSegment: !audioTrack.isAAC && typeSupported.mpeg ? new Uint8Array(0) : _mp4_generator__WEBPACK_IMPORTED_MODULE_2__["default"].initSegment([audioTrack]),
metadata: {
channelCount: audioTrack.channelCount
}
};
if (computePTSDTS) {
timescale = audioTrack.inputTimeScale; // remember first PTS of this demuxing context. for audio, PTS = DTS
initPTS = initDTS = audioSamples[0].pts - Math.round(timescale * timeOffset);
}
}
if (videoTrack.sps && videoTrack.pps && videoSamples.length) {
// let's use input time scale as MP4 video timescale
// we use input time scale straight away to avoid rounding issues on frame duration / cts computation
videoTrack.timescale = videoTrack.inputTimeScale;
tracks.video = {
id: 'main',
container: 'video/mp4',
codec: videoTrack.codec,
initSegment: _mp4_generator__WEBPACK_IMPORTED_MODULE_2__["default"].initSegment([videoTrack]),
metadata: {
width: videoTrack.width,
height: videoTrack.height
}
};
if (computePTSDTS) {
timescale = videoTrack.inputTimeScale;
var startPTS = this.getVideoStartPts(videoSamples);
var startOffset = Math.round(timescale * timeOffset);
initDTS = Math.min(initDTS, normalizePts(videoSamples[0].dts, startPTS) - startOffset);
initPTS = Math.min(initPTS, startPTS - startOffset);
}
}
if (Object.keys(tracks).length) {
this.ISGenerated = true;
if (computePTSDTS) {
this._initPTS = initPTS;
this._initDTS = initDTS;
}
return {
tracks: tracks,
initPTS: initPTS,
timescale: timescale
};
}
};
_proto.remuxVideo = function remuxVideo(track, timeOffset, contiguous, audioTrackLength) {
var timeScale = track.inputTimeScale;
var inputSamples = track.samples;
var outputSamples = [];
var nbSamples = inputSamples.length;
var initPTS = this._initPTS;
var nextAvcDts = this.nextAvcDts;
var offset = 8;
var mp4SampleDuration;
var firstDTS;
var lastDTS;
var minPTS = Number.POSITIVE_INFINITY;
var maxPTS = Number.NEGATIVE_INFINITY;
var ptsDtsShift = 0;
var sortSamples = false; // if parsed fragment is contiguous with last one, let's use last DTS value as reference
if (!contiguous || nextAvcDts === null) {
var pts = timeOffset * timeScale;
var cts = inputSamples[0].pts - normalizePts(inputSamples[0].dts, inputSamples[0].pts); // if not contiguous, let's use target timeOffset
nextAvcDts = pts - cts;
} // PTS is coded on 33bits, and can loop from -2^32 to 2^32
// PTSNormalize will make PTS/DTS value monotonic, we use last known DTS value as reference value
for (var i = 0; i < nbSamples; i++) {
var sample = inputSamples[i];
sample.pts = normalizePts(sample.pts - initPTS, nextAvcDts);
sample.dts = normalizePts(sample.dts - initPTS, nextAvcDts);
if (sample.dts > sample.pts) {
var PTS_DTS_SHIFT_TOLERANCE_90KHZ = 90000 * 0.2;
ptsDtsShift = Math.max(Math.min(ptsDtsShift, sample.pts - sample.dts), -1 * PTS_DTS_SHIFT_TOLERANCE_90KHZ);
}
if (sample.dts < inputSamples[i > 0 ? i - 1 : i].dts) {
sortSamples = true;
}
} // sort video samples by DTS then PTS then demux id order
if (sortSamples) {
inputSamples.sort(function (a, b) {
var deltadts = a.dts - b.dts;
var deltapts = a.pts - b.pts;
return deltadts || deltapts;
});
} // Get first/last DTS
firstDTS = inputSamples[0].dts;
lastDTS = inputSamples[inputSamples.length - 1].dts; // on Safari let's signal the same sample duration for all samples
// sample duration (as expected by trun MP4 boxes), should be the delta between sample DTS
// set this constant duration as being the avg delta between consecutive DTS.
var averageSampleDuration = Math.round((lastDTS - firstDTS) / (nbSamples - 1)); // handle broken streams with PTS < DTS, tolerance up 0.2 seconds
if (ptsDtsShift < 0) {
if (ptsDtsShift < averageSampleDuration * -2) {
// Fix for "CNN special report, with CC" in test-streams (including Safari browser)
// With large PTS < DTS errors such as this, we want to correct CTS while maintaining increasing DTS values
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn("PTS < DTS detected in video samples, offsetting DTS from PTS by " + Object(_utils_timescale_conversion__WEBPACK_IMPORTED_MODULE_6__["toMsFromMpegTsClock"])(-averageSampleDuration, true) + " ms");
var lastDts = ptsDtsShift;
for (var _i = 0; _i < nbSamples; _i++) {
inputSamples[_i].dts = lastDts = Math.max(lastDts, inputSamples[_i].pts - averageSampleDuration);
inputSamples[_i].pts = Math.max(lastDts, inputSamples[_i].pts);
}
} else {
// Fix for "Custom IV with bad PTS DTS" in test-streams
// With smaller PTS < DTS errors we can simply move all DTS back. This increases CTS without causing buffer gaps or decode errors in Safari
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn("PTS < DTS detected in video samples, shifting DTS by " + Object(_utils_timescale_conversion__WEBPACK_IMPORTED_MODULE_6__["toMsFromMpegTsClock"])(ptsDtsShift, true) + " ms to overcome this issue");
for (var _i2 = 0; _i2 < nbSamples; _i2++) {
inputSamples[_i2].dts = inputSamples[_i2].dts + ptsDtsShift;
}
}
firstDTS = inputSamples[0].dts;
} // if fragment are contiguous, detect hole/overlapping between fragments
if (contiguous) {
// check timestamp continuity across consecutive fragments (this is to remove inter-fragment gap/hole)
var delta = firstDTS - nextAvcDts;
var foundHole = delta > averageSampleDuration;
var foundOverlap = delta < -1;
if (foundHole || foundOverlap) {
if (foundHole) {
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn("AVC: " + Object(_utils_timescale_conversion__WEBPACK_IMPORTED_MODULE_6__["toMsFromMpegTsClock"])(delta, true) + " ms (" + delta + "dts) hole between fragments detected, filling it");
} else {
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn("AVC: " + Object(_utils_timescale_conversion__WEBPACK_IMPORTED_MODULE_6__["toMsFromMpegTsClock"])(-delta, true) + " ms (" + delta + "dts) overlapping between fragments detected");
}
firstDTS = nextAvcDts;
var firstPTS = inputSamples[0].pts - delta;
inputSamples[0].dts = firstDTS;
inputSamples[0].pts = firstPTS;
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].log("Video: First PTS/DTS adjusted: " + Object(_utils_timescale_conversion__WEBPACK_IMPORTED_MODULE_6__["toMsFromMpegTsClock"])(firstPTS, true) + "/" + Object(_utils_timescale_conversion__WEBPACK_IMPORTED_MODULE_6__["toMsFromMpegTsClock"])(firstDTS, true) + ", delta: " + Object(_utils_timescale_conversion__WEBPACK_IMPORTED_MODULE_6__["toMsFromMpegTsClock"])(delta, true) + " ms");
}
}
if (requiresPositiveDts) {
firstDTS = Math.max(0, firstDTS);
}
var nbNalu = 0;
var naluLen = 0;
for (var _i3 = 0; _i3 < nbSamples; _i3++) {
// compute total/avc sample length and nb of NAL units
var _sample = inputSamples[_i3];
var units = _sample.units;
var nbUnits = units.length;
var sampleLen = 0;
for (var j = 0; j < nbUnits; j++) {
sampleLen += units[j].data.length;
}
naluLen += sampleLen;
nbNalu += nbUnits;
_sample.length = sampleLen; // normalize PTS/DTS
// ensure sample monotonic DTS
_sample.dts = Math.max(_sample.dts, firstDTS); // ensure that computed value is greater or equal than sample DTS
_sample.pts = Math.max(_sample.pts, _sample.dts, 0);
minPTS = Math.min(_sample.pts, minPTS);
maxPTS = Math.max(_sample.pts, maxPTS);
}
lastDTS = inputSamples[nbSamples - 1].dts;
/* concatenate the video data and construct the mdat in place
(need 8 more bytes to fill length and mpdat type) */
var mdatSize = naluLen + 4 * nbNalu + 8;
var mdat;
try {
mdat = new Uint8Array(mdatSize);
} catch (err) {
this.observer.emit(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].ERROR, _events__WEBPACK_IMPORTED_MODULE_3__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_4__["ErrorTypes"].MUX_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_4__["ErrorDetails"].REMUX_ALLOC_ERROR,
fatal: false,
bytes: mdatSize,
reason: "fail allocating video mdat " + mdatSize
});
return;
}
var view = new DataView(mdat.buffer);
view.setUint32(0, mdatSize);
mdat.set(_mp4_generator__WEBPACK_IMPORTED_MODULE_2__["default"].types.mdat, 4);
for (var _i4 = 0; _i4 < nbSamples; _i4++) {
var avcSample = inputSamples[_i4];
var avcSampleUnits = avcSample.units;
var mp4SampleLength = 0; // convert NALU bitstream to MP4 format (prepend NALU with size field)
for (var _j = 0, _nbUnits = avcSampleUnits.length; _j < _nbUnits; _j++) {
var unit = avcSampleUnits[_j];
var unitData = unit.data;
var unitDataLen = unit.data.byteLength;
view.setUint32(offset, unitDataLen);
offset += 4;
mdat.set(unitData, offset);
offset += unitDataLen;
mp4SampleLength += 4 + unitDataLen;
} // expected sample duration is the Decoding Timestamp diff of consecutive samples
if (_i4 < nbSamples - 1) {
mp4SampleDuration = inputSamples[_i4 + 1].dts - avcSample.dts;
} else {
var config = this.config;
var lastFrameDuration = avcSample.dts - inputSamples[_i4 > 0 ? _i4 - 1 : _i4].dts;
if (config.stretchShortVideoTrack && this.nextAudioPts !== null) {
// In some cases, a segment's audio track duration may exceed the video track duration.
// Since we've already remuxed audio, and we know how long the audio track is, we look to
// see if the delta to the next segment is longer than maxBufferHole.
// If so, playback would potentially get stuck, so we artificially inflate
// the duration of the last frame to minimize any potential gap between segments.
var gapTolerance = Math.floor(config.maxBufferHole * timeScale);
var deltaToFrameEnd = (audioTrackLength ? minPTS + audioTrackLength * timeScale : this.nextAudioPts) - avcSample.pts;
if (deltaToFrameEnd > gapTolerance) {
// We subtract lastFrameDuration from deltaToFrameEnd to try to prevent any video
// frame overlap. maxBufferHole should be >> lastFrameDuration anyway.
mp4SampleDuration = deltaToFrameEnd - lastFrameDuration;
if (mp4SampleDuration < 0) {
mp4SampleDuration = lastFrameDuration;
}
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].log("[mp4-remuxer]: It is approximately " + deltaToFrameEnd / 90 + " ms to the next segment; using duration " + mp4SampleDuration / 90 + " ms for the last video frame.");
} else {
mp4SampleDuration = lastFrameDuration;
}
} else {
mp4SampleDuration = lastFrameDuration;
}
}
var compositionTimeOffset = Math.round(avcSample.pts - avcSample.dts);
outputSamples.push(new Mp4Sample(avcSample.key, mp4SampleDuration, mp4SampleLength, compositionTimeOffset));
}
if (outputSamples.length && chromeVersion && chromeVersion < 70) {
// Chrome workaround, mark first sample as being a Random Access Point (keyframe) to avoid sourcebuffer append issue
// https://code.google.com/p/chromium/issues/detail?id=229412
var flags = outputSamples[0].flags;
flags.dependsOn = 2;
flags.isNonSync = 0;
}
console.assert(mp4SampleDuration !== undefined, 'mp4SampleDuration must be computed'); // next AVC sample DTS should be equal to last sample DTS + last sample duration (in PES timescale)
this.nextAvcDts = nextAvcDts = lastDTS + mp4SampleDuration;
this.isVideoContiguous = true;
var moof = _mp4_generator__WEBPACK_IMPORTED_MODULE_2__["default"].moof(track.sequenceNumber++, firstDTS, _extends({}, track, {
samples: outputSamples
}));
var type = 'video';
var data = {
data1: moof,
data2: mdat,
startPTS: minPTS / timeScale,
endPTS: (maxPTS + mp4SampleDuration) / timeScale,
startDTS: firstDTS / timeScale,
endDTS: nextAvcDts / timeScale,
type: type,
hasAudio: false,
hasVideo: true,
nb: outputSamples.length,
dropped: track.dropped
};
track.samples = [];
track.dropped = 0;
console.assert(mdat.length, 'MDAT length must not be zero');
return data;
};
_proto.remuxAudio = function remuxAudio(track, timeOffset, contiguous, accurateTimeOffset, videoTimeOffset) {
var inputTimeScale = track.inputTimeScale;
var mp4timeScale = track.samplerate ? track.samplerate : inputTimeScale;
var scaleFactor = inputTimeScale / mp4timeScale;
var mp4SampleDuration = track.isAAC ? AAC_SAMPLES_PER_FRAME : MPEG_AUDIO_SAMPLE_PER_FRAME;
var inputSampleDuration = mp4SampleDuration * scaleFactor;
var initPTS = this._initPTS;
var rawMPEG = !track.isAAC && this.typeSupported.mpeg;
var outputSamples = [];
var inputSamples = track.samples;
var offset = rawMPEG ? 0 : 8;
var fillFrame;
var nextAudioPts = this.nextAudioPts || -1; // window.audioSamples ? window.audioSamples.push(inputSamples.map(s => s.pts)) : (window.audioSamples = [inputSamples.map(s => s.pts)]);
// for audio samples, also consider consecutive fragments as being contiguous (even if a level switch occurs),
// for sake of clarity:
// consecutive fragments are frags with
// - less than 100ms gaps between new time offset (if accurate) and next expected PTS OR
// - less than 20 audio frames distance
// contiguous fragments are consecutive fragments from same quality level (same level, new SN = old SN + 1)
// this helps ensuring audio continuity
// and this also avoids audio glitches/cut when switching quality, or reporting wrong duration on first audio frame
var timeOffsetMpegTS = timeOffset * inputTimeScale;
this.isAudioContiguous = contiguous = contiguous || inputSamples.length && nextAudioPts > 0 && (accurateTimeOffset && Math.abs(timeOffsetMpegTS - nextAudioPts) < 9000 || Math.abs(normalizePts(inputSamples[0].pts - initPTS, timeOffsetMpegTS) - nextAudioPts) < 20 * inputSampleDuration); // compute normalized PTS
inputSamples.forEach(function (sample) {
sample.pts = sample.dts = normalizePts(sample.pts - initPTS, timeOffsetMpegTS);
});
if (!contiguous || nextAudioPts < 0) {
// filter out sample with negative PTS that are not playable anyway
// if we don't remove these negative samples, they will shift all audio samples forward.
// leading to audio overlap between current / next fragment
inputSamples = inputSamples.filter(function (sample) {
return sample.pts >= 0;
}); // in case all samples have negative PTS, and have been filtered out, return now
if (!inputSamples.length) {
return;
}
if (videoTimeOffset === 0) {
// Set the start to 0 to match video so that start gaps larger than inputSampleDuration are filled with silence
nextAudioPts = 0;
} else if (accurateTimeOffset) {
// When not seeking, not live, and LevelDetails.PTSKnown, use fragment start as predicted next audio PTS
nextAudioPts = Math.max(0, timeOffsetMpegTS);
} else {
// if frags are not contiguous and if we cant trust time offset, let's use first sample PTS as next audio PTS
nextAudioPts = inputSamples[0].pts;
}
} // If the audio track is missing samples, the frames seem to get "left-shifted" within the
// resulting mp4 segment, causing sync issues and leaving gaps at the end of the audio segment.
// In an effort to prevent this from happening, we inject frames here where there are gaps.
// When possible, we inject a silent frame; when that's not possible, we duplicate the last
// frame.
if (track.isAAC) {
var maxAudioFramesDrift = this.config.maxAudioFramesDrift;
for (var i = 0, nextPts = nextAudioPts; i < inputSamples.length;) {
// First, let's see how far off this frame is from where we expect it to be
var sample = inputSamples[i];
var pts = sample.pts;
var delta = pts - nextPts;
var duration = Math.abs(1000 * delta / inputTimeScale); // When remuxing with video, if we're overlapping by more than a duration, drop this sample to stay in sync
if (delta <= -maxAudioFramesDrift * inputSampleDuration && videoTimeOffset !== undefined) {
if (contiguous || i > 0) {
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn("[mp4-remuxer]: Dropping 1 audio frame @ " + (nextPts / inputTimeScale).toFixed(3) + "s due to " + Math.round(duration) + " ms overlap.");
inputSamples.splice(i, 1); // Don't touch nextPtsNorm or i
} else {
// When changing qualities we can't trust that audio has been appended up to nextAudioPts
// Warn about the overlap but do not drop samples as that can introduce buffer gaps
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn("Audio frame @ " + (pts / inputTimeScale).toFixed(3) + "s overlaps nextAudioPts by " + Math.round(1000 * delta / inputTimeScale) + " ms.");
nextPts = pts + inputSampleDuration;
i++;
}
} // eslint-disable-line brace-style
// Insert missing frames if:
// 1: We're more than maxAudioFramesDrift frame away
// 2: Not more than MAX_SILENT_FRAME_DURATION away
// 3: currentTime (aka nextPtsNorm) is not 0
// 4: remuxing with video (videoTimeOffset !== undefined)
else if (delta >= maxAudioFramesDrift * inputSampleDuration && duration < MAX_SILENT_FRAME_DURATION && videoTimeOffset !== undefined) {
var missing = Math.floor(delta / inputSampleDuration); // Adjust nextPts so that silent samples are aligned with media pts. This will prevent media samples from
// later being shifted if nextPts is based on timeOffset and delta is not a multiple of inputSampleDuration.
nextPts = pts - missing * inputSampleDuration;
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn("[mp4-remuxer]: Injecting " + missing + " audio frame @ " + (nextPts / inputTimeScale).toFixed(3) + "s due to " + Math.round(1000 * delta / inputTimeScale) + " ms gap.");
for (var j = 0; j < missing; j++) {
var newStamp = Math.max(nextPts, 0);
fillFrame = _aac_helper__WEBPACK_IMPORTED_MODULE_1__["default"].getSilentFrame(track.manifestCodec || track.codec, track.channelCount);
if (!fillFrame) {
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].log('[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead.');
fillFrame = sample.unit.subarray();
}
inputSamples.splice(i, 0, {
unit: fillFrame,
pts: newStamp,
dts: newStamp
});
nextPts += inputSampleDuration;
i++;
} // Adjust sample to next expected pts
sample.pts = sample.dts = nextPts;
nextPts += inputSampleDuration;
i++;
} else {
// Otherwise, just adjust pts
sample.pts = sample.dts = nextPts;
nextPts += inputSampleDuration;
i++;
}
}
}
var firstPTS = null;
var lastPTS = null;
var mdat;
var mdatSize = 0;
var sampleLength = inputSamples.length;
while (sampleLength--) {
mdatSize += inputSamples[sampleLength].unit.byteLength;
}
for (var _j2 = 0, _nbSamples = inputSamples.length; _j2 < _nbSamples; _j2++) {
var audioSample = inputSamples[_j2];
var unit = audioSample.unit;
var _pts = audioSample.pts;
if (lastPTS !== null) {
// If we have more than one sample, set the duration of the sample to the "real" duration; the PTS diff with
// the previous sample
var prevSample = outputSamples[_j2 - 1];
prevSample.duration = Math.round((_pts - lastPTS) / scaleFactor);
} else {
var _delta = Math.round(1000 * (_pts - nextAudioPts) / inputTimeScale);
var numMissingFrames = 0; // if fragment are contiguous, detect hole/overlapping between fragments
// contiguous fragments are consecutive fragments from same quality level (same level, new SN = old SN + 1)
if (contiguous && track.isAAC) {
if (_delta > 0 && _delta < MAX_SILENT_FRAME_DURATION) {
numMissingFrames = Math.round((_pts - nextAudioPts) / inputSampleDuration);
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].log("[mp4-remuxer]: " + _delta + " ms hole between AAC samples detected,filling it");
if (numMissingFrames > 0) {
fillFrame = _aac_helper__WEBPACK_IMPORTED_MODULE_1__["default"].getSilentFrame(track.manifestCodec || track.codec, track.channelCount);
if (!fillFrame) {
fillFrame = unit.subarray();
}
mdatSize += 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
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].log("[mp4-remuxer]: drop overlapping AAC sample, expected/parsed/delta:" + (nextAudioPts / inputTimeScale).toFixed(3) + "s/" + (_pts / inputTimeScale).toFixed(3) + "s/" + -_delta + "ms");
mdatSize -= unit.byteLength;
continue;
} // set PTS/DTS to expected PTS/DTS
_pts = nextAudioPts;
} // remember first PTS of our audioSamples
firstPTS = _pts;
if (mdatSize > 0) {
/* concatenate the audio data and construct the mdat in place
(need 8 more bytes to fill length and mdat type) */
mdatSize += offset;
try {
mdat = new Uint8Array(mdatSize);
} catch (err) {
this.observer.emit(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].ERROR, _events__WEBPACK_IMPORTED_MODULE_3__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_4__["ErrorTypes"].MUX_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_4__["ErrorDetails"].REMUX_ALLOC_ERROR,
fatal: false,
bytes: mdatSize,
reason: "fail allocating audio mdat " + mdatSize
});
return;
}
if (!rawMPEG) {
var view = new DataView(mdat.buffer);
view.setUint32(0, mdatSize);
mdat.set(_mp4_generator__WEBPACK_IMPORTED_MODULE_2__["default"].types.mdat, 4);
}
} else {
// no audio samples
return;
}
for (var _i5 = 0; _i5 < numMissingFrames; _i5++) {
fillFrame = _aac_helper__WEBPACK_IMPORTED_MODULE_1__["default"].getSilentFrame(track.manifestCodec || track.codec, track.channelCount);
if (!fillFrame) {
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].log('[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating the current frame instead');
fillFrame = unit.subarray();
}
mdat.set(fillFrame, offset);
offset += fillFrame.byteLength;
outputSamples.push(new Mp4Sample(true, AAC_SAMPLES_PER_FRAME, fillFrame.byteLength, 0));
}
}
mdat.set(unit, offset);
var unitLen = unit.byteLength;
offset += unitLen; // Default the sample's duration to the computed mp4SampleDuration, which will either be 1024 for AAC or 1152 for MPEG
// In the case that we have 1 sample, this will be the duration. If we have more than one sample, the duration
// becomes the PTS diff with the previous sample
outputSamples.push(new Mp4Sample(true, mp4SampleDuration, unitLen, 0));
lastPTS = _pts;
} // We could end up with no audio samples if all input samples were overlapping with the previously remuxed ones
var nbSamples = outputSamples.length;
if (!nbSamples) {
return;
} // The next audio sample PTS should be equal to last sample PTS + duration
var lastSample = outputSamples[outputSamples.length - 1];
this.nextAudioPts = nextAudioPts = lastPTS + scaleFactor * lastSample.duration; // Set the track samples from inputSamples to outputSamples before remuxing
var moof = rawMPEG ? new Uint8Array(0) : _mp4_generator__WEBPACK_IMPORTED_MODULE_2__["default"].moof(track.sequenceNumber++, firstPTS / scaleFactor, _extends({}, track, {
samples: outputSamples
})); // Clear the track samples. This also clears the samples array in the demuxer, since the reference is shared
track.samples = [];
var start = firstPTS / inputTimeScale;
var end = nextAudioPts / inputTimeScale;
var type = 'audio';
var audioData = {
data1: moof,
data2: mdat,
startPTS: start,
endPTS: end,
startDTS: start,
endDTS: end,
type: type,
hasAudio: true,
hasVideo: false,
nb: nbSamples
};
this.isAudioContiguous = true;
console.assert(mdat.length, 'MDAT length must not be zero');
return audioData;
};
_proto.remuxEmptyAudio = function remuxEmptyAudio(track, timeOffset, contiguous, videoData) {
var inputTimeScale = track.inputTimeScale;
var mp4timeScale = track.samplerate ? track.samplerate : inputTimeScale;
var scaleFactor = inputTimeScale / mp4timeScale;
var nextAudioPts = this.nextAudioPts; // sync with video's timestamp
var startDTS = (nextAudioPts !== null ? nextAudioPts : videoData.startDTS * inputTimeScale) + this._initDTS;
var endDTS = videoData.endDTS * inputTimeScale + this._initDTS; // one sample's duration value
var frameDuration = scaleFactor * AAC_SAMPLES_PER_FRAME; // samples count of this segment's duration
var nbSamples = Math.ceil((endDTS - startDTS) / frameDuration); // silent frame
var silentFrame = _aac_helper__WEBPACK_IMPORTED_MODULE_1__["default"].getSilentFrame(track.manifestCodec || track.codec, track.channelCount);
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn('[mp4-remuxer]: remux empty Audio'); // Can't remux if we can't generate a silent frame...
if (!silentFrame) {
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].trace('[mp4-remuxer]: Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec');
return;
}
var samples = [];
for (var i = 0; i < nbSamples; i++) {
var stamp = startDTS + i * frameDuration;
samples.push({
unit: silentFrame,
pts: stamp,
dts: stamp
});
}
track.samples = samples;
return this.remuxAudio(track, timeOffset, contiguous, false);
};
_proto.remuxID3 = function remuxID3(track, timeOffset) {
var length = track.samples.length;
if (!length) {
return;
}
var inputTimeScale = track.inputTimeScale;
var initPTS = this._initPTS;
var initDTS = this._initDTS;
for (var index = 0; index < length; index++) {
var sample = track.samples[index]; // setting id3 pts, dts to relative time
// using this._initPTS and this._initDTS to calculate relative time
sample.pts = normalizePts(sample.pts - initPTS, timeOffset * inputTimeScale) / inputTimeScale;
sample.dts = normalizePts(sample.dts - initDTS, timeOffset * inputTimeScale) / inputTimeScale;
}
var samples = track.samples;
track.samples = [];
return {
samples: samples
};
};
_proto.remuxText = function remuxText(track, timeOffset) {
var length = track.samples.length;
if (!length) {
return;
}
var inputTimeScale = track.inputTimeScale;
var initPTS = this._initPTS;
for (var index = 0; index < length; index++) {
var sample = track.samples[index]; // setting text pts, dts to relative time
// using this._initPTS and this._initDTS to calculate relative time
sample.pts = normalizePts(sample.pts - initPTS, timeOffset * inputTimeScale) / inputTimeScale;
}
track.samples.sort(function (a, b) {
return a.pts - b.pts;
});
var samples = track.samples;
track.samples = [];
return {
samples: samples
};
};
return MP4Remuxer;
}();
function normalizePts(value, reference) {
var offset;
if (reference === null) {
return value;
}
if (reference < value) {
// - 2^33
offset = -8589934592;
} else {
// + 2^33
offset = 8589934592;
}
/* PTS is 33bit (from 0 to 2^33 -1)
if diff between value and reference is bigger than half of the amplitude (2^32) then it means that
PTS looping occured. fill the gap */
while (Math.abs(value - reference) > 4294967296) {
value += offset;
}
return value;
}
function findKeyframeIndex(samples) {
for (var i = 0; i < samples.length; i++) {
if (samples[i].key) {
return i;
}
}
return -1;
}
var Mp4Sample = function Mp4Sample(isKeyframe, duration, size, cts) {
this.size = void 0;
this.duration = void 0;
this.cts = void 0;
this.flags = void 0;
this.duration = duration;
this.size = size;
this.cts = cts;
this.flags = new Mp4SampleFlags(isKeyframe);
};
var Mp4SampleFlags = function Mp4SampleFlags(isKeyframe) {
this.isLeading = 0;
this.isDependedOn = 0;
this.hasRedundancy = 0;
this.degradPrio = 0;
this.dependsOn = 1;
this.isNonSync = 1;
this.dependsOn = isKeyframe ? 2 : 1;
this.isNonSync = isKeyframe ? 0 : 1;
};
/***/ }),
/***/ "./src/remux/passthrough-remuxer.ts":
/*!******************************************!*\
!*** ./src/remux/passthrough-remuxer.ts ***!
\******************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/mp4-tools */ "./src/utils/mp4-tools.ts");
/* harmony import */ var _loader_fragment__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../loader/fragment */ "./src/loader/fragment.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
var PassThroughRemuxer = /*#__PURE__*/function () {
function PassThroughRemuxer() {
this.emitInitSegment = false;
this.audioCodec = void 0;
this.videoCodec = void 0;
this.initData = void 0;
this.initPTS = void 0;
this.initTracks = void 0;
this.lastEndDTS = null;
}
var _proto = PassThroughRemuxer.prototype;
_proto.destroy = function destroy() {};
_proto.resetTimeStamp = function resetTimeStamp(defaultInitPTS) {
this.initPTS = defaultInitPTS;
this.lastEndDTS = null;
};
_proto.resetNextTimestamp = function resetNextTimestamp() {
this.lastEndDTS = null;
};
_proto.resetInitSegment = function resetInitSegment(initSegment, audioCodec, videoCodec) {
this.audioCodec = audioCodec;
this.videoCodec = videoCodec;
this.generateInitSegment(initSegment);
this.emitInitSegment = true;
};
_proto.generateInitSegment = function generateInitSegment(initSegment) {
var audioCodec = this.audioCodec,
videoCodec = this.videoCodec;
if (!initSegment || !initSegment.byteLength) {
this.initTracks = undefined;
this.initData = undefined;
return;
}
var initData = this.initData = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_1__["parseInitSegment"])(initSegment); // Get codec from initSegment or fallback to default
if (!audioCodec) {
audioCodec = getParsedTrackCodec(initData.audio, _loader_fragment__WEBPACK_IMPORTED_MODULE_2__["ElementaryStreamTypes"].AUDIO);
}
if (!videoCodec) {
videoCodec = getParsedTrackCodec(initData.video, _loader_fragment__WEBPACK_IMPORTED_MODULE_2__["ElementaryStreamTypes"].VIDEO);
}
var tracks = {};
if (initData.audio && initData.video) {
tracks.audiovideo = {
container: 'video/mp4',
codec: audioCodec + ',' + videoCodec,
initSegment: initSegment,
id: 'main'
};
} else if (initData.audio) {
tracks.audio = {
container: 'audio/mp4',
codec: audioCodec,
initSegment: initSegment,
id: 'audio'
};
} else if (initData.video) {
tracks.video = {
container: 'video/mp4',
codec: videoCodec,
initSegment: initSegment,
id: 'main'
};
} else {
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn('[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes.');
}
this.initTracks = tracks;
};
_proto.remux = function remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset) {
var initPTS = this.initPTS,
lastEndDTS = this.lastEndDTS;
var result = {
audio: undefined,
video: undefined,
text: textTrack,
id3: id3Track,
initSegment: undefined
}; // If we haven't yet set a lastEndDTS, or it was reset, set it to the provided timeOffset. We want to use the
// lastEndDTS over timeOffset whenever possible; during progressive playback, the media source will not update
// the media duration (which is what timeOffset is provided as) before we need to process the next chunk.
if (!Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(lastEndDTS)) {
lastEndDTS = this.lastEndDTS = timeOffset || 0;
} // The binary segment data is added to the videoTrack in the mp4demuxer. We don't check to see if the data is only
// audio or video (or both); adding it to video was an arbitrary choice.
var data = videoTrack.samples;
if (!data || !data.length) {
return result;
}
var initSegment = {
initPTS: undefined,
timescale: 1
};
var initData = this.initData;
if (!initData || !initData.length) {
this.generateInitSegment(data);
initData = this.initData;
}
if (!initData || !initData.length) {
// We can't remux if the initSegment could not be generated
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn('[passthrough-remuxer.ts]: Failed to generate initSegment.');
return result;
}
if (this.emitInitSegment) {
initSegment.tracks = this.initTracks;
this.emitInitSegment = false;
}
if (!Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(initPTS)) {
this.initPTS = initSegment.initPTS = initPTS = computeInitPTS(initData, data, lastEndDTS);
}
var duration = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_1__["getDuration"])(data, initData);
var startDTS = lastEndDTS;
var endDTS = duration + startDTS;
Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_1__["offsetStartDTS"])(initData, data, initPTS);
if (duration > 0) {
this.lastEndDTS = endDTS;
} else {
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn('Duration parsed from mp4 should be greater than zero');
this.resetNextTimestamp();
}
var hasAudio = !!initData.audio;
var hasVideo = !!initData.video;
var type = '';
if (hasAudio) {
type += 'audio';
}
if (hasVideo) {
type += 'video';
}
var track = {
data1: data,
startPTS: startDTS,
startDTS: startDTS,
endPTS: endDTS,
endDTS: endDTS,
type: type,
hasAudio: hasAudio,
hasVideo: hasVideo,
nb: 1,
dropped: 0
};
result.audio = track.type === 'audio' ? track : undefined;
result.video = track.type !== 'audio' ? track : undefined;
result.text = textTrack;
result.id3 = id3Track;
result.initSegment = initSegment;
return result;
};
return PassThroughRemuxer;
}();
var computeInitPTS = function computeInitPTS(initData, data, timeOffset) {
return Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_1__["getStartDTS"])(initData, data) - timeOffset;
};
function getParsedTrackCodec(track, type) {
var parsedCodec = track === null || track === void 0 ? void 0 : track.codec;
if (parsedCodec && parsedCodec.length > 4) {
return parsedCodec;
} // Since mp4-tools cannot parse full codec string (see 'TODO: Parse codec details'... in mp4-tools)
// Provide defaults based on codec type
// This allows for some playback of some fmp4 playlists without CODECS defined in manifest
if (parsedCodec === 'hvc1') {
return 'hvc1.1.c.L120.90';
}
if (parsedCodec === 'av01') {
return 'av01.0.04M.08';
}
if (parsedCodec === 'avc1' || type === _loader_fragment__WEBPACK_IMPORTED_MODULE_2__["ElementaryStreamTypes"].VIDEO) {
return 'avc1.42e01e';
}
return 'mp4a.40.5';
}
/* harmony default export */ __webpack_exports__["default"] = (PassThroughRemuxer);
/***/ }),
/***/ "./src/task-loop.ts":
/*!**************************!*\
!*** ./src/task-loop.ts ***!
\**************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return TaskLoop; });
/**
* Sub-class specialization of EventHandler base class.
*
* TaskLoop allows to schedule a task function being called (optionnaly repeatedly) on the main loop,
* scheduled asynchroneously, avoiding recursive calls in the same tick.
*
* The task itself is implemented in `doTick`. It can be requested and called for single execution
* using the `tick` method.
*
* It will be assured that the task execution method (`tick`) only gets called once per main loop "tick",
* no matter how often it gets requested for execution. Execution in further ticks will be scheduled accordingly.
*
* If further execution requests have already been scheduled on the next tick, it can be checked with `hasNextTick`,
* and cancelled with `clearNextTick`.
*
* The task can be scheduled as an interval repeatedly with a period as parameter (see `setInterval`, `clearInterval`).
*
* Sub-classes need to implement the `doTick` method which will effectively have the task execution routine.
*
* Further explanations:
*
* The baseclass has a `tick` method that will schedule the doTick call. It may be called synchroneously
* only for a stack-depth of one. On re-entrant calls, sub-sequent calls are scheduled for next main loop ticks.
*
* When the task execution (`tick` method) is called in re-entrant way this is detected and
* we are limiting the task execution per call stack to exactly one, but scheduling/post-poning further
* task processing on the next main loop iteration (also known as "next tick" in the Node/JS runtime lingo).
*/
var TaskLoop = /*#__PURE__*/function () {
function TaskLoop() {
this._boundTick = void 0;
this._tickTimer = null;
this._tickInterval = null;
this._tickCallCount = 0;
this._boundTick = this.tick.bind(this);
}
var _proto = TaskLoop.prototype;
_proto.destroy = function destroy() {
this.onHandlerDestroying();
this.onHandlerDestroyed();
};
_proto.onHandlerDestroying = function onHandlerDestroying() {
// clear all timers before unregistering from event bus
this.clearNextTick();
this.clearInterval();
};
_proto.onHandlerDestroyed = function onHandlerDestroyed() {}
/**
* @returns {boolean}
*/
;
_proto.hasInterval = function hasInterval() {
return !!this._tickInterval;
}
/**
* @returns {boolean}
*/
;
_proto.hasNextTick = function hasNextTick() {
return !!this._tickTimer;
}
/**
* @param {number} millis Interval time (ms)
* @returns {boolean} True when interval has been scheduled, false when already scheduled (no effect)
*/
;
_proto.setInterval = function setInterval(millis) {
if (!this._tickInterval) {
this._tickInterval = self.setInterval(this._boundTick, millis);
return true;
}
return false;
}
/**
* @returns {boolean} True when interval was cleared, false when none was set (no effect)
*/
;
_proto.clearInterval = function clearInterval() {
if (this._tickInterval) {
self.clearInterval(this._tickInterval);
this._tickInterval = null;
return true;
}
return false;
}
/**
* @returns {boolean} True when timeout was cleared, false when none was set (no effect)
*/
;
_proto.clearNextTick = function clearNextTick() {
if (this._tickTimer) {
self.clearTimeout(this._tickTimer);
this._tickTimer = null;
return true;
}
return false;
}
/**
* Will call the subclass doTick implementation in this main loop tick
* or in the next one (via setTimeout(,0)) in case it has already been called
* in this tick (in case this is a re-entrant call).
*/
;
_proto.tick = function tick() {
this._tickCallCount++;
if (this._tickCallCount === 1) {
this.doTick(); // re-entrant call to tick from previous doTick call stack
// -> schedule a call on the next main loop iteration to process this task processing request
if (this._tickCallCount > 1) {
// make sure only one timer exists at any time at max
this.clearNextTick();
this._tickTimer = self.setTimeout(this._boundTick, 0);
}
this._tickCallCount = 0;
}
}
/**
* For subclass to implement task logic
* @abstract
*/
;
_proto.doTick = function doTick() {};
return TaskLoop;
}();
/***/ }),
/***/ "./src/types/level.ts":
/*!****************************!*\
!*** ./src/types/level.ts ***!
\****************************/
/*! exports provided: HlsSkip, getSkipValue, HlsUrlParameters, Level */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HlsSkip", function() { return HlsSkip; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getSkipValue", function() { return getSkipValue; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HlsUrlParameters", function() { return HlsUrlParameters; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Level", function() { return Level; });
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
var HlsSkip;
(function (HlsSkip) {
HlsSkip["No"] = "";
HlsSkip["Yes"] = "YES";
HlsSkip["v2"] = "v2";
})(HlsSkip || (HlsSkip = {}));
function getSkipValue(details, msn) {
var canSkipUntil = details.canSkipUntil,
canSkipDateRanges = details.canSkipDateRanges,
endSN = details.endSN;
var snChangeGoal = msn - endSN;
if (canSkipUntil && snChangeGoal < canSkipUntil) {
if (canSkipDateRanges) {
return HlsSkip.v2;
}
return HlsSkip.Yes;
}
return HlsSkip.No;
}
var HlsUrlParameters = /*#__PURE__*/function () {
function HlsUrlParameters(msn, part, skip) {
this.msn = void 0;
this.part = void 0;
this.skip = void 0;
this.msn = msn;
this.part = part;
this.skip = skip;
}
var _proto = HlsUrlParameters.prototype;
_proto.addDirectives = function addDirectives(uri) {
var url = new self.URL(uri);
var searchParams = url.searchParams;
searchParams.set('_HLS_msn', this.msn.toString());
if (this.part !== undefined) {
searchParams.set('_HLS_part', this.part.toString());
}
if (this.skip) {
searchParams.set('_HLS_skip', this.skip);
}
searchParams.sort();
url.search = searchParams.toString();
return url.toString();
};
return HlsUrlParameters;
}();
var Level = /*#__PURE__*/function () {
function Level(data) {
this.attrs = void 0;
this.audioCodec = void 0;
this.bitrate = void 0;
this.codecSet = void 0;
this.height = void 0;
this.id = void 0;
this.name = void 0;
this.videoCodec = void 0;
this.width = void 0;
this.unknownCodecs = void 0;
this.audioGroupIds = void 0;
this.details = void 0;
this.fragmentError = 0;
this.loadError = 0;
this.loaded = void 0;
this.realBitrate = 0;
this.textGroupIds = void 0;
this.url = void 0;
this._urlId = 0;
this.url = [data.url];
this.attrs = data.attrs;
this.bitrate = data.bitrate;
if (data.details) {
this.details = data.details;
}
this.id = data.id || 0;
this.name = data.name;
this.width = data.width || 0;
this.height = data.height || 0;
this.audioCodec = data.audioCodec;
this.videoCodec = data.videoCodec;
this.unknownCodecs = data.unknownCodecs;
this.codecSet = [data.videoCodec, data.audioCodec].filter(function (c) {
return c;
}).join(',').replace(/\.[^.,]+/g, '');
}
_createClass(Level, [{
key: "maxBitrate",
get: function get() {
return Math.max(this.realBitrate, this.bitrate);
}
}, {
key: "uri",
get: function get() {
return this.url[this._urlId] || '';
}
}, {
key: "urlId",
get: function get() {
return this._urlId;
},
set: function set(value) {
var newValue = value % this.url.length;
if (this._urlId !== newValue) {
this.details = undefined;
this._urlId = newValue;
}
}
}]);
return Level;
}();
/***/ }),
/***/ "./src/types/loader.ts":
/*!*****************************!*\
!*** ./src/types/loader.ts ***!
\*****************************/
/*! exports provided: PlaylistContextType, PlaylistLevelType */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PlaylistContextType", function() { return PlaylistContextType; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PlaylistLevelType", function() { return PlaylistLevelType; });
var PlaylistContextType;
(function (PlaylistContextType) {
PlaylistContextType["MANIFEST"] = "manifest";
PlaylistContextType["LEVEL"] = "level";
PlaylistContextType["AUDIO_TRACK"] = "audioTrack";
PlaylistContextType["SUBTITLE_TRACK"] = "subtitleTrack";
})(PlaylistContextType || (PlaylistContextType = {}));
var PlaylistLevelType;
(function (PlaylistLevelType) {
PlaylistLevelType["MAIN"] = "main";
PlaylistLevelType["AUDIO"] = "audio";
PlaylistLevelType["SUBTITLE"] = "subtitle";
})(PlaylistLevelType || (PlaylistLevelType = {}));
/***/ }),
/***/ "./src/types/transmuxer.ts":
/*!*********************************!*\
!*** ./src/types/transmuxer.ts ***!
\*********************************/
/*! exports provided: ChunkMetadata */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ChunkMetadata", function() { return ChunkMetadata; });
var ChunkMetadata = function ChunkMetadata(level, sn, id, size, part, partial) {
if (size === void 0) {
size = 0;
}
if (part === void 0) {
part = -1;
}
if (partial === void 0) {
partial = false;
}
this.level = void 0;
this.sn = void 0;
this.part = void 0;
this.id = void 0;
this.size = void 0;
this.partial = void 0;
this.transmuxing = getNewPerformanceTiming();
this.buffering = {
audio: getNewPerformanceTiming(),
video: getNewPerformanceTiming(),
audiovideo: getNewPerformanceTiming()
};
this.level = level;
this.sn = sn;
this.id = id;
this.size = size;
this.part = part;
this.partial = partial;
};
function getNewPerformanceTiming() {
return {
start: 0,
executeStart: 0,
executeEnd: 0,
end: 0
};
}
/***/ }),
/***/ "./src/utils/attr-list.ts":
/*!********************************!*\
!*** ./src/utils/attr-list.ts ***!
\********************************/
/*! exports provided: AttrList */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AttrList", function() { return AttrList; });
var DECIMAL_RESOLUTION_REGEX = /^(\d+)x(\d+)$/; // eslint-disable-line no-useless-escape
var ATTR_LIST_REGEX = /\s*(.+?)\s*=((?:\".*?\")|.*?)(?:,|$)/g; // eslint-disable-line no-useless-escape
// adapted from https://github.com/kanongil/node-m3u8parse/blob/master/attrlist.js
var AttrList = /*#__PURE__*/function () {
function AttrList(attrs) {
if (typeof attrs === 'string') {
attrs = AttrList.parseAttrList(attrs);
}
for (var attr in attrs) {
if (attrs.hasOwnProperty(attr)) {
this[attr] = attrs[attr];
}
}
}
var _proto = AttrList.prototype;
_proto.decimalInteger = function decimalInteger(attrName) {
var intValue = parseInt(this[attrName], 10);
if (intValue > Number.MAX_SAFE_INTEGER) {
return Infinity;
}
return intValue;
};
_proto.hexadecimalInteger = function hexadecimalInteger(attrName) {
if (this[attrName]) {
var stringValue = (this[attrName] || '0x').slice(2);
stringValue = (stringValue.length & 1 ? '0' : '') + stringValue;
var value = new Uint8Array(stringValue.length / 2);
for (var i = 0; i < stringValue.length / 2; i++) {
value[i] = parseInt(stringValue.slice(i * 2, i * 2 + 2), 16);
}
return value;
} else {
return null;
}
};
_proto.hexadecimalIntegerAsNumber = function hexadecimalIntegerAsNumber(attrName) {
var intValue = parseInt(this[attrName], 16);
if (intValue > Number.MAX_SAFE_INTEGER) {
return Infinity;
}
return intValue;
};
_proto.decimalFloatingPoint = function decimalFloatingPoint(attrName) {
return parseFloat(this[attrName]);
};
_proto.optionalFloat = function optionalFloat(attrName, defaultValue) {
var value = this[attrName];
return value ? parseFloat(value) : defaultValue;
};
_proto.enumeratedString = function enumeratedString(attrName) {
return this[attrName];
};
_proto.bool = function bool(attrName) {
return this[attrName] === 'YES';
};
_proto.decimalResolution = function decimalResolution(attrName) {
var res = DECIMAL_RESOLUTION_REGEX.exec(this[attrName]);
if (res === null) {
return undefined;
}
return {
width: parseInt(res[1], 10),
height: parseInt(res[2], 10)
};
};
AttrList.parseAttrList = function parseAttrList(input) {
var match;
var attrs = {};
var quote = '"';
ATTR_LIST_REGEX.lastIndex = 0;
while ((match = ATTR_LIST_REGEX.exec(input)) !== null) {
var value = match[2];
if (value.indexOf(quote) === 0 && value.lastIndexOf(quote) === value.length - 1) {
value = value.slice(1, -1);
}
attrs[match[1]] = value;
}
return attrs;
};
return AttrList;
}();
/***/ }),
/***/ "./src/utils/binary-search.ts":
/*!************************************!*\
!*** ./src/utils/binary-search.ts ***!
\************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
var BinarySearch = {
/**
* Searches for an item in an array which matches a certain condition.
* This requires the condition to only match one item in the array,
* and for the array to be ordered.
*
* @param {Array<T>} list The array to search.
* @param {BinarySearchComparison<T>} comparisonFn
* Called and provided a candidate item as the first argument.
* Should return:
* > -1 if the item should be located at a lower index than the provided item.
* > 1 if the item should be located at a higher index than the provided item.
* > 0 if the item is the item you're looking for.
*
* @return {T | null} The object if it is found or null otherwise.
*/
search: function search(list, comparisonFn) {
var minIndex = 0;
var maxIndex = list.length - 1;
var currentIndex = null;
var currentElement = null;
while (minIndex <= maxIndex) {
currentIndex = (minIndex + maxIndex) / 2 | 0;
currentElement = list[currentIndex];
var comparisonResult = comparisonFn(currentElement);
if (comparisonResult > 0) {
minIndex = currentIndex + 1;
} else if (comparisonResult < 0) {
maxIndex = currentIndex - 1;
} else {
return currentElement;
}
}
return null;
}
};
/* harmony default export */ __webpack_exports__["default"] = (BinarySearch);
/***/ }),
/***/ "./src/utils/buffer-helper.ts":
/*!************************************!*\
!*** ./src/utils/buffer-helper.ts ***!
\************************************/
/*! exports provided: BufferHelper */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BufferHelper", function() { return BufferHelper; });
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/**
* @module BufferHelper
*
* Providing methods dealing with buffer length retrieval for example.
*
* In general, a helper around HTML5 MediaElement TimeRanges gathered from `buffered` property.
*
* Also @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/buffered
*/
var noopBuffered = {
length: 0,
start: function start() {
return 0;
},
end: function end() {
return 0;
}
};
var BufferHelper = /*#__PURE__*/function () {
function BufferHelper() {}
/**
* Return true if `media`'s buffered include `position`
* @param {Bufferable} media
* @param {number} position
* @returns {boolean}
*/
BufferHelper.isBuffered = function isBuffered(media, position) {
try {
if (media) {
var buffered = BufferHelper.getBuffered(media);
for (var i = 0; i < buffered.length; i++) {
if (position >= buffered.start(i) && position <= buffered.end(i)) {
return true;
}
}
}
} catch (error) {// this is to catch
// InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer':
// This SourceBuffer has been removed from the parent media source
}
return false;
};
BufferHelper.bufferInfo = function bufferInfo(media, pos, maxHoleDuration) {
try {
if (media) {
var vbuffered = BufferHelper.getBuffered(media);
var buffered = [];
var i;
for (i = 0; i < vbuffered.length; i++) {
buffered.push({
start: vbuffered.start(i),
end: vbuffered.end(i)
});
}
return this.bufferedInfo(buffered, pos, maxHoleDuration);
}
} catch (error) {// this is to catch
// InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer':
// This SourceBuffer has been removed from the parent media source
}
return {
len: 0,
start: pos,
end: pos,
nextStart: undefined
};
};
BufferHelper.bufferedInfo = function bufferedInfo(buffered, pos, maxHoleDuration) {
// sort on buffer.start/smaller end (IE does not always return sorted buffered range)
buffered.sort(function (a, b) {
var diff = a.start - b.start;
if (diff) {
return diff;
} else {
return b.end - a.end;
}
});
var buffered2 = [];
if (maxHoleDuration) {
// there might be some small holes between buffer time range
// consider that holes smaller than maxHoleDuration are irrelevant and build another
// buffer time range representations that discards those holes
for (var i = 0; i < buffered.length; i++) {
var buf2len = buffered2.length;
if (buf2len) {
var buf2end = buffered2[buf2len - 1].end; // if small hole (value between 0 or maxHoleDuration ) or overlapping (negative)
if (buffered[i].start - buf2end < maxHoleDuration) {
// merge overlapping time ranges
// update lastRange.end only if smaller than item.end
// e.g. [ 1, 15] with [ 2,8] => [ 1,15] (no need to modify lastRange.end)
// whereas [ 1, 8] with [ 2,15] => [ 1,15] ( lastRange should switch from [1,8] to [1,15])
if (buffered[i].end > buf2end) {
buffered2[buf2len - 1].end = buffered[i].end;
}
} else {
// big hole
buffered2.push(buffered[i]);
}
} else {
// first value
buffered2.push(buffered[i]);
}
}
} else {
buffered2 = buffered;
}
var bufferLen = 0; // bufferStartNext can possibly be undefined based on the conditional logic below
var bufferStartNext; // bufferStart and bufferEnd are buffer boundaries around current video position
var bufferStart = pos;
var bufferEnd = pos;
for (var _i = 0; _i < buffered2.length; _i++) {
var start = buffered2[_i].start;
var end = buffered2[_i].end; // logger.log('buf start/end:' + buffered.start(i) + '/' + buffered.end(i));
if (pos + maxHoleDuration >= start && pos < end) {
// play position is inside this buffer TimeRange, retrieve end of buffer position and buffer length
bufferStart = start;
bufferEnd = end;
bufferLen = bufferEnd - pos;
} else if (pos + maxHoleDuration < start) {
bufferStartNext = start;
break;
}
}
return {
len: bufferLen,
start: bufferStart || 0,
end: bufferEnd || 0,
nextStart: bufferStartNext
};
}
/**
* Safe method to get buffered property.
* SourceBuffer.buffered may throw if SourceBuffer is removed from it's MediaSource
*/
;
BufferHelper.getBuffered = function getBuffered(media) {
try {
return media.buffered;
} catch (e) {
_utils_logger__WEBPACK_IMPORTED_MODULE_0__["logger"].log('failed to get media.buffered', e);
return noopBuffered;
}
};
return BufferHelper;
}();
/***/ }),
/***/ "./src/utils/cea-608-parser.ts":
/*!*************************************!*\
!*** ./src/utils/cea-608-parser.ts ***!
\*************************************/
/*! exports provided: Row, CaptionScreen, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Row", function() { return Row; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CaptionScreen", function() { return CaptionScreen; });
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/**
*
* 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;
var NR_COLS = 100; // 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'];
var VerboseLevel;
(function (VerboseLevel) {
VerboseLevel[VerboseLevel["ERROR"] = 0] = "ERROR";
VerboseLevel[VerboseLevel["TEXT"] = 1] = "TEXT";
VerboseLevel[VerboseLevel["WARNING"] = 2] = "WARNING";
VerboseLevel[VerboseLevel["INFO"] = 2] = "INFO";
VerboseLevel[VerboseLevel["DEBUG"] = 3] = "DEBUG";
VerboseLevel[VerboseLevel["DATA"] = 3] = "DATA";
})(VerboseLevel || (VerboseLevel = {}));
var CaptionsLogger = /*#__PURE__*/function () {
function CaptionsLogger() {
this.time = null;
this.verboseLevel = VerboseLevel.ERROR;
}
var _proto = CaptionsLogger.prototype;
_proto.log = function log(severity, msg) {
if (this.verboseLevel >= severity) {
_utils_logger__WEBPACK_IMPORTED_MODULE_0__["logger"].log(this.time + " [" + severity + "] " + msg);
}
};
return CaptionsLogger;
}();
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 = /*#__PURE__*/function () {
function PenState(foreground, underline, italics, background, flash) {
this.foreground = void 0;
this.underline = void 0;
this.italics = void 0;
this.background = void 0;
this.flash = void 0;
this.foreground = foreground || 'white';
this.underline = underline || false;
this.italics = italics || false;
this.background = background || 'black';
this.flash = flash || false;
}
var _proto2 = PenState.prototype;
_proto2.reset = function reset() {
this.foreground = 'white';
this.underline = false;
this.italics = false;
this.background = 'black';
this.flash = false;
};
_proto2.setStyles = 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];
}
}
};
_proto2.isDefault = function isDefault() {
return this.foreground === 'white' && !this.underline && !this.italics && this.background === 'black' && !this.flash;
};
_proto2.equals = function equals(other) {
return this.foreground === other.foreground && this.underline === other.underline && this.italics === other.italics && this.background === other.background && this.flash === other.flash;
};
_proto2.copy = function copy(newPenState) {
this.foreground = newPenState.foreground;
this.underline = newPenState.underline;
this.italics = newPenState.italics;
this.background = newPenState.background;
this.flash = newPenState.flash;
};
_proto2.toString = 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 = /*#__PURE__*/function () {
function StyledUnicodeChar(uchar, foreground, underline, italics, background, flash) {
this.uchar = void 0;
this.penState = void 0;
this.uchar = uchar || ' '; // unicode character
this.penState = new PenState(foreground, underline, italics, background, flash);
}
var _proto3 = StyledUnicodeChar.prototype;
_proto3.reset = function reset() {
this.uchar = ' ';
this.penState.reset();
};
_proto3.setChar = function setChar(uchar, newPenState) {
this.uchar = uchar;
this.penState.copy(newPenState);
};
_proto3.setPenState = function setPenState(newPenState) {
this.penState.copy(newPenState);
};
_proto3.equals = function equals(other) {
return this.uchar === other.uchar && this.penState.equals(other.penState);
};
_proto3.copy = function copy(newChar) {
this.uchar = newChar.uchar;
this.penState.copy(newChar.penState);
};
_proto3.isEmpty = function isEmpty() {
return this.uchar === ' ' && this.penState.isDefault();
};
return StyledUnicodeChar;
}();
/**
* CEA-608 row consisting of NR_COLS instances of StyledUnicodeChar.
* @constructor
*/
var Row = /*#__PURE__*/function () {
function Row(logger) {
this.chars = void 0;
this.pos = void 0;
this.currPenState = void 0;
this.cueStartTime = void 0;
this.logger = void 0;
this.chars = [];
for (var i = 0; i < NR_COLS; i++) {
this.chars.push(new StyledUnicodeChar());
}
this.logger = logger;
this.pos = 0;
this.currPenState = new PenState();
}
var _proto4 = Row.prototype;
_proto4.equals = 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;
};
_proto4.copy = function copy(other) {
for (var i = 0; i < NR_COLS; i++) {
this.chars[i].copy(other.chars[i]);
}
};
_proto4.isEmpty = 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.
*/
;
_proto4.setCursor = function setCursor(absPos) {
if (this.pos !== absPos) {
this.pos = absPos;
}
if (this.pos < 0) {
this.logger.log(VerboseLevel.DEBUG, 'Negative cursor position ' + this.pos);
this.pos = 0;
} else if (this.pos > NR_COLS) {
this.logger.log(VerboseLevel.DEBUG, 'Too large cursor position ' + this.pos);
this.pos = NR_COLS;
}
}
/**
* Move the cursor relative to current position.
*/
;
_proto4.moveCursor = 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.
*/
;
_proto4.backSpace = function backSpace() {
this.moveCursor(-1);
this.chars[this.pos].setChar(' ', this.currPenState);
};
_proto4.insertChar = function insertChar(_byte2) {
if (_byte2 >= 0x90) {
// Extended char
this.backSpace();
}
var _char = getCharForByte(_byte2);
if (this.pos >= NR_COLS) {
this.logger.log(VerboseLevel.ERROR, 'Cannot insert ' + _byte2.toString(16) + ' (' + _char + ') at position ' + this.pos + '. Skipping it!');
return;
}
this.chars[this.pos].setChar(_char, this.currPenState);
this.moveCursor(1);
};
_proto4.clearFromPos = function clearFromPos(startPos) {
var i;
for (i = startPos; i < NR_COLS; i++) {
this.chars[i].reset();
}
};
_proto4.clear = function clear() {
this.clearFromPos(0);
this.pos = 0;
this.currPenState.reset();
};
_proto4.clearToEndOfRow = function clearToEndOfRow() {
this.clearFromPos(this.pos);
};
_proto4.getTextString = function getTextString() {
var chars = [];
var empty = true;
for (var i = 0; i < NR_COLS; i++) {
var _char2 = this.chars[i].uchar;
if (_char2 !== ' ') {
empty = false;
}
chars.push(_char2);
}
if (empty) {
return '';
} else {
return chars.join('');
}
};
_proto4.setPenStyles = 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 = /*#__PURE__*/function () {
function CaptionScreen(logger) {
this.rows = void 0;
this.currRow = void 0;
this.nrRollUpRows = void 0;
this.lastOutputScreen = void 0;
this.logger = void 0;
this.rows = [];
for (var i = 0; i < NR_ROWS; i++) {
this.rows.push(new Row(logger));
} // Note that we use zero-based numbering (0-14)
this.logger = logger;
this.currRow = NR_ROWS - 1;
this.nrRollUpRows = null;
this.lastOutputScreen = null;
this.reset();
}
var _proto5 = CaptionScreen.prototype;
_proto5.reset = function reset() {
for (var i = 0; i < NR_ROWS; i++) {
this.rows[i].clear();
}
this.currRow = NR_ROWS - 1;
};
_proto5.equals = 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;
};
_proto5.copy = function copy(other) {
for (var i = 0; i < NR_ROWS; i++) {
this.rows[i].copy(other.rows[i]);
}
};
_proto5.isEmpty = function isEmpty() {
var empty = true;
for (var i = 0; i < NR_ROWS; i++) {
if (!this.rows[i].isEmpty()) {
empty = false;
break;
}
}
return empty;
};
_proto5.backSpace = function backSpace() {
var row = this.rows[this.currRow];
row.backSpace();
};
_proto5.clearToEndOfRow = function clearToEndOfRow() {
var row = this.rows[this.currRow];
row.clearToEndOfRow();
}
/**
* Insert a character (without styling) in the current row.
*/
;
_proto5.insertChar = function insertChar(_char3) {
var row = this.rows[this.currRow];
row.insertChar(_char3);
};
_proto5.setPen = function setPen(styles) {
var row = this.rows[this.currRow];
row.setPenStyles(styles);
};
_proto5.moveCursor = function moveCursor(relPos) {
var row = this.rows[this.currRow];
row.moveCursor(relPos);
};
_proto5.setCursor = function setCursor(absPos) {
this.logger.log(VerboseLevel.INFO, 'setCursor: ' + absPos);
var row = this.rows[this.currRow];
row.setCursor(absPos);
};
_proto5.setPAC = function setPAC(pacData) {
this.logger.log(VerboseLevel.INFO, 'pacData = ' + JSON.stringify(pacData));
var newRow = pacData.row - 1;
if (this.nrRollUpRows && newRow < this.nrRollUpRows - 1) {
newRow = this.nrRollUpRows - 1;
} // Make sure this only affects Roll-up Captions by checking this.nrRollUpRows
if (this.nrRollUpRows && this.currRow !== newRow) {
// clear all rows first
for (var i = 0; i < NR_ROWS; i++) {
this.rows[i].clear();
} // Copy this.nrRollUpRows rows from lastOutputScreen and place it in the newRow location
// topRowIndex - the start of rows to copy (inclusive index)
var topRowIndex = this.currRow + 1 - this.nrRollUpRows; // We only copy if the last position was already shown.
// We use the cueStartTime value to check this.
var lastOutputScreen = this.lastOutputScreen;
if (lastOutputScreen) {
var prevLineTime = lastOutputScreen.rows[topRowIndex].cueStartTime;
var time = this.logger.time;
if (prevLineTime && time !== null && prevLineTime < time) {
for (var _i = 0; _i < this.nrRollUpRows; _i++) {
this.rows[newRow - this.nrRollUpRows + _i + 1].copy(lastOutputScreen.rows[topRowIndex + _i]);
}
}
}
}
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).
*/
;
_proto5.setBkgData = function setBkgData(bkgData) {
this.logger.log(VerboseLevel.INFO, 'bkgData = ' + JSON.stringify(bkgData));
this.backSpace();
this.setPen(bkgData);
this.insertChar(0x20); // Space
};
_proto5.setRollUpRows = function setRollUpRows(nrRows) {
this.nrRollUpRows = nrRows;
};
_proto5.rollUp = function rollUp() {
if (this.nrRollUpRows === null) {
this.logger.log(VerboseLevel.DEBUG, 'roll_up but nrRollUpRows not set yet');
return; // Not properly setup
}
this.logger.log(VerboseLevel.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);
this.logger.log(VerboseLevel.INFO, 'Rolling up'); // this.logger.log(VerboseLevel.TEXT, this.get_display_text())
}
/**
* Get all non-empty rows with as unicode text.
*/
;
_proto5.getDisplayText = 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;
};
_proto5.getTextAndFormat = function getTextAndFormat() {
return this.rows;
};
return CaptionScreen;
}(); // var modes = ['MODE_ROLL-UP', 'MODE_POP-ON', 'MODE_PAINT-ON', 'MODE_TEXT'];
var Cea608Channel = /*#__PURE__*/function () {
function Cea608Channel(channelNumber, outputFilter, logger) {
this.chNr = void 0;
this.outputFilter = void 0;
this.mode = void 0;
this.verbose = void 0;
this.displayedMemory = void 0;
this.nonDisplayedMemory = void 0;
this.lastOutputScreen = void 0;
this.currRollUpRow = void 0;
this.writeScreen = void 0;
this.cueStartTime = void 0;
this.logger = void 0;
this.chNr = channelNumber;
this.outputFilter = outputFilter;
this.mode = null;
this.verbose = 0;
this.displayedMemory = new CaptionScreen(logger);
this.nonDisplayedMemory = new CaptionScreen(logger);
this.lastOutputScreen = new CaptionScreen(logger);
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.
this.logger = logger;
}
var _proto6 = Cea608Channel.prototype;
_proto6.reset = function reset() {
this.mode = null;
this.displayedMemory.reset();
this.nonDisplayedMemory.reset();
this.lastOutputScreen.reset();
this.outputFilter.reset();
this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1];
this.writeScreen = this.displayedMemory;
this.mode = null;
this.cueStartTime = null;
};
_proto6.getHandler = function getHandler() {
return this.outputFilter;
};
_proto6.setHandler = function setHandler(newHandler) {
this.outputFilter = newHandler;
};
_proto6.setPAC = function setPAC(pacData) {
this.writeScreen.setPAC(pacData);
};
_proto6.setBkgData = function setBkgData(bkgData) {
this.writeScreen.setBkgData(bkgData);
};
_proto6.setMode = function setMode(newMode) {
if (newMode === this.mode) {
return;
}
this.mode = newMode;
this.logger.log(VerboseLevel.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;
};
_proto6.insertChars = 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';
this.logger.log(VerboseLevel.INFO, screen + ': ' + this.writeScreen.getDisplayText(true));
if (this.mode === 'MODE_PAINT-ON' || this.mode === 'MODE_ROLL-UP') {
this.logger.log(VerboseLevel.TEXT, 'DISPLAYED: ' + this.displayedMemory.getDisplayText(true));
this.outputDataUpdate();
}
};
_proto6.ccRCL = function ccRCL() {
// Resume Caption Loading (switch mode to Pop On)
this.logger.log(VerboseLevel.INFO, 'RCL - Resume Caption Loading');
this.setMode('MODE_POP-ON');
};
_proto6.ccBS = function ccBS() {
// BackSpace
this.logger.log(VerboseLevel.INFO, 'BS - BackSpace');
if (this.mode === 'MODE_TEXT') {
return;
}
this.writeScreen.backSpace();
if (this.writeScreen === this.displayedMemory) {
this.outputDataUpdate();
}
};
_proto6.ccAOF = function ccAOF() {// Reserved (formerly Alarm Off)
};
_proto6.ccAON = function ccAON() {// Reserved (formerly Alarm On)
};
_proto6.ccDER = function ccDER() {
// Delete to End of Row
this.logger.log(VerboseLevel.INFO, 'DER- Delete to End of Row');
this.writeScreen.clearToEndOfRow();
this.outputDataUpdate();
};
_proto6.ccRU = function ccRU(nrRows) {
// Roll-Up Captions-2,3,or 4 Rows
this.logger.log(VerboseLevel.INFO, 'RU(' + nrRows + ') - Roll Up');
this.writeScreen = this.displayedMemory;
this.setMode('MODE_ROLL-UP');
this.writeScreen.setRollUpRows(nrRows);
};
_proto6.ccFON = function ccFON() {
// Flash On
this.logger.log(VerboseLevel.INFO, 'FON - Flash On');
this.writeScreen.setPen({
flash: true
});
};
_proto6.ccRDC = function ccRDC() {
// Resume Direct Captioning (switch mode to PaintOn)
this.logger.log(VerboseLevel.INFO, 'RDC - Resume Direct Captioning');
this.setMode('MODE_PAINT-ON');
};
_proto6.ccTR = function ccTR() {
// Text Restart in text mode (not supported, however)
this.logger.log(VerboseLevel.INFO, 'TR');
this.setMode('MODE_TEXT');
};
_proto6.ccRTD = function ccRTD() {
// Resume Text Display in Text mode (not supported, however)
this.logger.log(VerboseLevel.INFO, 'RTD');
this.setMode('MODE_TEXT');
};
_proto6.ccEDM = function ccEDM() {
// Erase Displayed Memory
this.logger.log(VerboseLevel.INFO, 'EDM - Erase Displayed Memory');
this.displayedMemory.reset();
this.outputDataUpdate(true);
};
_proto6.ccCR = function ccCR() {
// Carriage Return
this.logger.log(VerboseLevel.INFO, 'CR - Carriage Return');
this.writeScreen.rollUp();
this.outputDataUpdate(true);
};
_proto6.ccENM = function ccENM() {
// Erase Non-Displayed Memory
this.logger.log(VerboseLevel.INFO, 'ENM - Erase Non-displayed Memory');
this.nonDisplayedMemory.reset();
};
_proto6.ccEOC = function ccEOC() {
// End of Caption (Flip Memories)
this.logger.log(VerboseLevel.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;
this.logger.log(VerboseLevel.TEXT, 'DISP: ' + this.displayedMemory.getDisplayText());
}
this.outputDataUpdate(true);
};
_proto6.ccTO = function ccTO(nrCols) {
// Tab Offset 1,2, or 3 columns
this.logger.log(VerboseLevel.INFO, 'TO(' + nrCols + ') - Tab Offset');
this.writeScreen.moveCursor(nrCols);
};
_proto6.ccMIDROW = 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';
}
this.logger.log(VerboseLevel.INFO, 'MIDROW: ' + JSON.stringify(styles));
this.writeScreen.setPen(styles);
};
_proto6.outputDataUpdate = function outputDataUpdate(dispatch) {
if (dispatch === void 0) {
dispatch = false;
}
var time = this.logger.time;
if (time === null) {
return;
}
if (this.outputFilter) {
if (this.cueStartTime === null && !this.displayedMemory.isEmpty()) {
// Start of a new cue
this.cueStartTime = time;
} else {
if (!this.displayedMemory.equals(this.lastOutputScreen)) {
this.outputFilter.newCue(this.cueStartTime, time, this.lastOutputScreen);
if (dispatch && this.outputFilter.dispatchCue) {
this.outputFilter.dispatchCue();
}
this.cueStartTime = this.displayedMemory.isEmpty() ? null : time;
}
}
this.lastOutputScreen.copy(this.displayedMemory);
}
};
_proto6.cueSplitAtTime = 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 = /*#__PURE__*/function () {
function Cea608Parser(field, out1, out2) {
this.channels = void 0;
this.currentChannel = 0;
this.cmdHistory = void 0;
this.logger = void 0;
var logger = new CaptionsLogger();
this.channels = [null, new Cea608Channel(field, out1, logger), new Cea608Channel(field + 1, out2, logger)];
this.cmdHistory = createCmdHistory();
this.logger = logger;
}
var _proto7 = Cea608Parser.prototype;
_proto7.getHandler = function getHandler(channel) {
return this.channels[channel].getHandler();
};
_proto7.setHandler = function setHandler(channel, newHandler) {
this.channels[channel].setHandler(newHandler);
}
/**
* Add data for time t in forms of list of bytes (unsigned ints). The bytes are treated as pairs.
*/
;
_proto7.addData = function addData(time, byteList) {
var cmdFound;
var a;
var b;
var charsFound = false;
this.logger.time = time;
for (var i = 0; i < byteList.length; i += 2) {
a = byteList[i] & 0x7f;
b = byteList[i + 1] & 0x7f;
if (a === 0 && b === 0) {
continue;
} else {
this.logger.log(VerboseLevel.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) {
var currChNr = this.currentChannel;
if (currChNr && currChNr > 0) {
var channel = this.channels[currChNr];
channel.insertChars(charsFound);
} else {
this.logger.log(VerboseLevel.WARNING, 'No channel found yet. TEXT-MODE?');
}
}
}
if (!cmdFound && !charsFound) {
this.logger.log(VerboseLevel.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
*/
;
_proto7.parseCmd = function parseCmd(a, b) {
var cmdHistory = this.cmdHistory;
var cond1 = (a === 0x14 || a === 0x1c || a === 0x15 || a === 0x1d) && b >= 0x20 && b <= 0x2f;
var cond2 = (a === 0x17 || a === 0x1f) && b >= 0x21 && b <= 0x23;
if (!(cond1 || cond2)) {
return false;
}
if (hasCmdRepeated(a, b, cmdHistory)) {
setLastCmd(null, null, cmdHistory);
this.logger.log(VerboseLevel.DEBUG, 'Repeated command (' + numArrayToHexArray([a, b]) + ') is dropped');
return true;
}
var chNr = a === 0x14 || a === 0x15 || a === 0x17 ? 1 : 2;
var channel = this.channels[chNr];
if (a === 0x14 || a === 0x15 || a === 0x1c || a === 0x1d) {
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);
}
setLastCmd(a, b, cmdHistory);
this.currentChannel = chNr;
return true;
}
/**
* Parse midrow styling command
* @returns {Boolean}
*/
;
_proto7.parseMidrow = function parseMidrow(a, b) {
var chNr = 0;
if ((a === 0x11 || a === 0x19) && b >= 0x20 && b <= 0x2f) {
if (a === 0x11) {
chNr = 1;
} else {
chNr = 2;
}
if (chNr !== this.currentChannel) {
this.logger.log(VerboseLevel.ERROR, 'Mismatch channel in midrow parsing');
return false;
}
var channel = this.channels[chNr];
if (!channel) {
return false;
}
channel.ccMIDROW(b);
this.logger.log(VerboseLevel.DEBUG, 'MIDROW (' + numArrayToHexArray([a, b]) + ')');
return true;
}
return false;
}
/**
* Parse Preable Access Codes (Table 53).
* @returns {Boolean} Tells if PAC found
*/
;
_proto7.parsePAC = function parsePAC(a, b) {
var row;
var cmdHistory = this.cmdHistory;
var case1 = (a >= 0x11 && a <= 0x17 || a >= 0x19 && a <= 0x1f) && b >= 0x40 && b <= 0x7f;
var case2 = (a === 0x10 || a === 0x18) && b >= 0x40 && b <= 0x5f;
if (!(case1 || case2)) {
return false;
}
if (hasCmdRepeated(a, b, cmdHistory)) {
setLastCmd(null, null, cmdHistory);
return true; // Repeated commands are dropped (once)
}
var chNr = a <= 0x17 ? 1 : 2;
if (b >= 0x40 && b <= 0x5f) {
row = chNr === 1 ? rowsLowCh1[a] : rowsLowCh2[a];
} else {
// 0x60 <= b <= 0x7F
row = chNr === 1 ? rowsHighCh1[a] : rowsHighCh2[a];
}
var channel = this.channels[chNr];
if (!channel) {
return false;
}
channel.setPAC(this.interpretPAC(row, b));
setLastCmd(a, b, cmdHistory);
this.currentChannel = chNr;
return true;
}
/**
* Interpret the second byte of the pac, and return the information.
* @returns {Object} pacData with style parameters.
*/
;
_proto7.interpretPAC = function interpretPAC(row, _byte3) {
var pacIndex;
var pacData = {
color: null,
italics: false,
indent: null,
underline: false,
row: row
};
if (_byte3 > 0x5f) {
pacIndex = _byte3 - 0x60;
} else {
pacIndex = _byte3 - 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.
*/
;
_proto7.parseChars = function parseChars(a, b) {
var channelNr;
var charCodes = null;
var charCode1 = null;
if (a >= 0x19) {
channelNr = 2;
charCode1 = a - 8;
} else {
channelNr = 1;
charCode1 = a;
}
if (charCode1 >= 0x11 && charCode1 <= 0x13) {
// Special character
var oneCode;
if (charCode1 === 0x11) {
oneCode = b + 0x50;
} else if (charCode1 === 0x12) {
oneCode = b + 0x70;
} else {
oneCode = b + 0x90;
}
this.logger.log(VerboseLevel.INFO, "Special char '" + getCharForByte(oneCode) + "' in channel " + channelNr);
charCodes = [oneCode];
} else if (a >= 0x20 && a <= 0x7f) {
charCodes = b === 0 ? [a] : [a, b];
}
if (charCodes) {
var hexCodes = numArrayToHexArray(charCodes);
this.logger.log(VerboseLevel.DEBUG, 'Char codes = ' + hexCodes.join(','));
setLastCmd(a, b, this.cmdHistory);
}
return charCodes;
}
/**
* Parse extended background attributes as well as new foreground color black.
* @returns {Boolean} Tells if background attributes are found
*/
;
_proto7.parseBackgroundAttributes = function parseBackgroundAttributes(a, b) {
var case1 = (a === 0x10 || a === 0x18) && b >= 0x20 && b <= 0x2f;
var case2 = (a === 0x17 || a === 0x1f) && b >= 0x2d && b <= 0x2f;
if (!(case1 || case2)) {
return false;
}
var index;
var 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;
}
}
var chNr = a <= 0x17 ? 1 : 2;
var channel = this.channels[chNr];
channel.setBkgData(bkgData);
setLastCmd(a, b, this.cmdHistory);
return true;
}
/**
* Reset state of parser and its channels.
*/
;
_proto7.reset = function reset() {
for (var i = 0; i < Object.keys(this.channels).length; i++) {
var channel = this.channels[i];
if (channel) {
channel.reset();
}
}
this.cmdHistory = createCmdHistory();
}
/**
* Trigger the generation of a cue, and the start of a new one if displayScreens are not empty.
*/
;
_proto7.cueSplitAtTime = function cueSplitAtTime(t) {
for (var i = 0; i < this.channels.length; i++) {
var channel = this.channels[i];
if (channel) {
channel.cueSplitAtTime(t);
}
}
};
return Cea608Parser;
}();
function setLastCmd(a, b, cmdHistory) {
cmdHistory.a = a;
cmdHistory.b = b;
}
function hasCmdRepeated(a, b, cmdHistory) {
return cmdHistory.a === a && cmdHistory.b === b;
}
function createCmdHistory() {
return {
a: null,
b: null
};
}
/* harmony default export */ __webpack_exports__["default"] = (Cea608Parser);
/***/ }),
/***/ "./src/utils/codecs.ts":
/*!*****************************!*\
!*** ./src/utils/codecs.ts ***!
\*****************************/
/*! exports provided: isCodecType, isCodecSupportedInMp4 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isCodecType", function() { return isCodecType; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isCodecSupportedInMp4", function() { return isCodecSupportedInMp4; });
// from http://mp4ra.org/codecs.html
var sampleEntryCodesISO = {
audio: {
a3ds: true,
'ac-3': true,
'ac-4': true,
alac: true,
alaw: true,
dra1: true,
'dts+': true,
'dts-': true,
dtsc: true,
dtse: true,
dtsh: true,
'ec-3': true,
enca: true,
g719: true,
g726: true,
m4ae: true,
mha1: true,
mha2: true,
mhm1: true,
mhm2: true,
mlpa: true,
mp4a: true,
'raw ': true,
Opus: true,
samr: true,
sawb: true,
sawp: true,
sevc: true,
sqcp: true,
ssmv: true,
twos: true,
ulaw: true
},
video: {
avc1: true,
avc2: true,
avc3: true,
avc4: true,
avcp: true,
av01: true,
drac: true,
dvav: true,
dvhe: true,
encv: true,
hev1: true,
hvc1: true,
mjp2: true,
mp4v: true,
mvc1: true,
mvc2: true,
mvc3: true,
mvc4: true,
resv: true,
rv60: true,
s263: true,
svc1: true,
svc2: true,
'vc-1': true,
vp08: true,
vp09: true
},
text: {
stpp: true,
wvtt: true
}
};
function isCodecType(codec, type) {
var typeCodes = sampleEntryCodesISO[type];
return !!typeCodes && typeCodes[codec.slice(0, 4)] === true;
}
function isCodecSupportedInMp4(codec, type) {
return MediaSource.isTypeSupported((type || 'video') + "/mp4;codecs=\"" + codec + "\"");
}
/***/ }),
/***/ "./src/utils/cues.ts":
/*!***************************!*\
!*** ./src/utils/cues.ts ***!
\***************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _vttparser__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./vttparser */ "./src/utils/vttparser.ts");
/* harmony import */ var _webvtt_parser__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./webvtt-parser */ "./src/utils/webvtt-parser.ts");
/* harmony import */ var _texttrack_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./texttrack-utils */ "./src/utils/texttrack-utils.ts");
var WHITESPACE_CHAR = /\s/;
var Cues = {
newCue: function newCue(track, startTime, endTime, captionScreen) {
var result = [];
var row; // the type data states this is VTTCue, but it can potentially be a TextTrackCue on old browsers
var cue;
var indenting;
var indent;
var text;
var Cue = self.VTTCue || self.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 (WHITESPACE_CHAR.test(row.chars[c].uchar) && indenting) {
indent++;
} else {
text += row.chars[c].uchar;
indenting = false;
}
} // To be used for cleaning-up orphaned roll-up captions
row.cueStartTime = startTime; // Give a slight bump to the endTime if it's equal to startTime to avoid a SyntaxError in IE
if (startTime === endTime) {
endTime += 0.0001;
}
if (indent >= 16) {
indent--;
} else {
indent++;
}
var cueText = Object(_vttparser__WEBPACK_IMPORTED_MODULE_0__["fixLineBreaks"])(text.trim());
var id = Object(_webvtt_parser__WEBPACK_IMPORTED_MODULE_1__["generateCueId"])(startTime, endTime, cueText); // If this cue already exists in the track do not push it
if (!track || !track.cues || !track.cues.getCueById(id)) {
cue = new Cue(startTime, endTime, cueText);
cue.id = id;
cue.line = r + 1;
cue.align = 'left'; // Clamp the position between 10 and 80 percent (CEA-608 PAC indent code)
// https://dvcs.w3.org/hg/text-tracks/raw-file/default/608toVTT/608toVTT.html#positioning-in-cea-608
// Firefox throws an exception and captions break with out of bounds 0-100 values
cue.position = 10 + Math.min(80, Math.floor(indent * 8 / 32) * 10);
result.push(cue);
}
}
}
if (track && result.length) {
// Sort bottom cues in reverse order so that they render in line order when overlapping in Chrome
result.sort(function (cueA, cueB) {
if (cueA.line === 'auto' || cueB.line === 'auto') {
return 0;
}
if (cueA.line > 8 && cueB.line > 8) {
return cueB.line - cueA.line;
}
return cueA.line - cueB.line;
});
result.forEach(function (cue) {
return Object(_texttrack_utils__WEBPACK_IMPORTED_MODULE_2__["addCueToTrack"])(track, cue);
});
}
return result;
}
};
/* harmony default export */ __webpack_exports__["default"] = (Cues);
/***/ }),
/***/ "./src/utils/discontinuities.ts":
/*!**************************************!*\
!*** ./src/utils/discontinuities.ts ***!
\**************************************/
/*! exports provided: findFirstFragWithCC, shouldAlignOnDiscontinuities, findDiscontinuousReferenceFrag, adjustSlidingStart, alignStream, alignPDT */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findFirstFragWithCC", function() { return findFirstFragWithCC; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "shouldAlignOnDiscontinuities", function() { return shouldAlignOnDiscontinuities; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findDiscontinuousReferenceFrag", function() { return findDiscontinuousReferenceFrag; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "adjustSlidingStart", function() { return adjustSlidingStart; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "alignStream", function() { return alignStream; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "alignPDT", function() { return alignPDT; });
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var _logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./logger */ "./src/utils/logger.ts");
/* harmony import */ var _controller_level_helper__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../controller/level-helper */ "./src/controller/level-helper.ts");
function findFirstFragWithCC(fragments, cc) {
var firstFrag = null;
for (var i = 0, len = fragments.length; i < len; i++) {
var currentFrag = fragments[i];
if (currentFrag && currentFrag.cc === cc) {
firstFrag = currentFrag;
break;
}
}
return firstFrag;
}
function shouldAlignOnDiscontinuities(lastFrag, lastLevel, details) {
if (lastLevel.details) {
if (details.endCC > details.startCC || lastFrag && lastFrag.cc < details.startCC) {
return true;
}
}
return false;
} // Find the first frag in the previous level which matches the CC of the first frag of the new level
function findDiscontinuousReferenceFrag(prevDetails, curDetails) {
var prevFrags = prevDetails.fragments;
var curFrags = curDetails.fragments;
if (!curFrags.length || !prevFrags.length) {
_logger__WEBPACK_IMPORTED_MODULE_1__["logger"].log('No fragments to align');
return;
}
var prevStartFrag = findFirstFragWithCC(prevFrags, curFrags[0].cc);
if (!prevStartFrag || prevStartFrag && !prevStartFrag.startPTS) {
_logger__WEBPACK_IMPORTED_MODULE_1__["logger"].log('No frag in previous level to align on');
return;
}
return prevStartFrag;
}
function adjustFragmentStart(frag, sliding) {
if (frag) {
var start = frag.start + sliding;
frag.start = frag.startPTS = start;
frag.endPTS = start + frag.duration;
}
}
function adjustSlidingStart(sliding, details) {
// Update segments
var fragments = details.fragments;
for (var i = 0, len = fragments.length; i < len; i++) {
adjustFragmentStart(fragments[i], sliding);
} // Update LL-HLS parts at the end of the playlist
if (details.fragmentHint) {
adjustFragmentStart(details.fragmentHint, sliding);
}
details.alignedSliding = true;
}
/**
* Using the parameters of the last level, this function computes PTS' of the new fragments so that they form a
* contiguous stream with the last fragments.
* The PTS of a fragment lets Hls.js know where it fits into a stream - by knowing every PTS, we know which fragment to
* download at any given time. PTS is normally computed when the fragment is demuxed, so taking this step saves us time
* and an extra download.
* @param lastFrag
* @param lastLevel
* @param details
*/
function alignStream(lastFrag, lastLevel, details) {
if (!lastLevel) {
return;
}
alignDiscontinuities(lastFrag, details, lastLevel);
if (!details.alignedSliding && lastLevel.details) {
// If the PTS wasn't figured out via discontinuity sequence that means there was no CC increase within the level.
// Aligning via Program Date Time should therefore be reliable, since PDT should be the same within the same
// discontinuity sequence.
alignPDT(details, lastLevel.details);
}
if (!details.alignedSliding && lastLevel.details && !details.skippedSegments) {
// Try to align on sn so that we pick a better start fragment.
// Do not perform this on playlists with delta updates as this is only to align levels on switch
// and adjustSliding only adjusts fragments after skippedSegments.
Object(_controller_level_helper__WEBPACK_IMPORTED_MODULE_2__["adjustSliding"])(lastLevel.details, details);
}
}
/**
* Computes the PTS if a new level's fragments using the PTS of a fragment in the last level which shares the same
* discontinuity sequence.
* @param lastFrag - The last Fragment which shares the same discontinuity sequence
* @param lastLevel - The details of the last loaded level
* @param details - The details of the new level
*/
function alignDiscontinuities(lastFrag, details, lastLevel) {
if (shouldAlignOnDiscontinuities(lastFrag, lastLevel, details)) {
var referenceFrag = findDiscontinuousReferenceFrag(lastLevel.details, details);
if (referenceFrag && Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(referenceFrag.start)) {
_logger__WEBPACK_IMPORTED_MODULE_1__["logger"].log("Adjusting PTS using last level due to CC increase within current level " + details.url);
adjustSlidingStart(referenceFrag.start, details);
}
}
}
/**
* Computes the PTS of a new level's fragments using the difference in Program Date Time from the last level.
* @param details - The details of the new level
* @param lastDetails - The details of the last loaded level
*/
function alignPDT(details, lastDetails) {
// This check protects the unsafe "!" usage below for null program date time access.
if (!lastDetails.fragments.length || !details.hasProgramDateTime || !lastDetails.hasProgramDateTime) {
return;
} // if last level sliding is 1000 and its first frag PROGRAM-DATE-TIME is 2017-08-20 1:10:00 AM
// and if new details first frag PROGRAM DATE-TIME is 2017-08-20 1:10:08 AM
// then we can deduce that playlist B sliding is 1000+8 = 1008s
var lastPDT = lastDetails.fragments[0].programDateTime; // hasProgramDateTime check above makes this safe.
var newPDT = details.fragments[0].programDateTime; // date diff is in ms. frag.start is in seconds
var sliding = (newPDT - lastPDT) / 1000 + lastDetails.fragments[0].start;
if (sliding && Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(sliding)) {
_logger__WEBPACK_IMPORTED_MODULE_1__["logger"].log("Adjusting PTS using programDateTime delta " + (newPDT - lastPDT) + "ms, sliding:" + sliding.toFixed(3) + " " + details.url + " ");
adjustSlidingStart(sliding, details);
}
}
/***/ }),
/***/ "./src/utils/ewma-bandwidth-estimator.ts":
/*!***********************************************!*\
!*** ./src/utils/ewma-bandwidth-estimator.ts ***!
\***********************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _utils_ewma__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/ewma */ "./src/utils/ewma.ts");
/*
* EWMA Bandwidth Estimator
* - heavily inspired from shaka-player
* Tracks bandwidth samples and estimates available bandwidth.
* Based on the minimum of two exponentially-weighted moving averages with
* different half-lives.
*/
var EwmaBandWidthEstimator = /*#__PURE__*/function () {
function EwmaBandWidthEstimator(slow, fast, defaultEstimate) {
this.defaultEstimate_ = void 0;
this.minWeight_ = void 0;
this.minDelayMs_ = void 0;
this.slow_ = void 0;
this.fast_ = void 0;
this.defaultEstimate_ = defaultEstimate;
this.minWeight_ = 0.001;
this.minDelayMs_ = 50;
this.slow_ = new _utils_ewma__WEBPACK_IMPORTED_MODULE_0__["default"](slow);
this.fast_ = new _utils_ewma__WEBPACK_IMPORTED_MODULE_0__["default"](fast);
}
var _proto = EwmaBandWidthEstimator.prototype;
_proto.update = function update(slow, fast) {
var slow_ = this.slow_,
fast_ = this.fast_;
if (this.slow_.halfLife !== slow) {
this.slow_ = new _utils_ewma__WEBPACK_IMPORTED_MODULE_0__["default"](slow, slow_.getEstimate(), slow_.getTotalWeight());
}
if (this.fast_.halfLife !== fast) {
this.fast_ = new _utils_ewma__WEBPACK_IMPORTED_MODULE_0__["default"](fast, fast_.getEstimate(), fast_.getTotalWeight());
}
};
_proto.sample = function sample(durationMs, numBytes) {
durationMs = Math.max(durationMs, this.minDelayMs_);
var numBits = 8 * numBytes; // weight is duration in seconds
var durationS = durationMs / 1000; // value is bandwidth in bits/s
var bandwidthInBps = numBits / durationS;
this.fast_.sample(durationS, bandwidthInBps);
this.slow_.sample(durationS, bandwidthInBps);
};
_proto.canEstimate = function canEstimate() {
var fast = this.fast_;
return fast && fast.getTotalWeight() >= this.minWeight_;
};
_proto.getEstimate = function getEstimate() {
if (this.canEstimate()) {
// console.log('slow estimate:'+ Math.round(this.slow_.getEstimate()));
// console.log('fast estimate:'+ Math.round(this.fast_.getEstimate()));
// Take the minimum of these two estimates. This should have the effect of
// adapting down quickly, but up more slowly.
return Math.min(this.fast_.getEstimate(), this.slow_.getEstimate());
} else {
return this.defaultEstimate_;
}
};
_proto.destroy = function destroy() {};
return EwmaBandWidthEstimator;
}();
/* harmony default export */ __webpack_exports__["default"] = (EwmaBandWidthEstimator);
/***/ }),
/***/ "./src/utils/ewma.ts":
/*!***************************!*\
!*** ./src/utils/ewma.ts ***!
\***************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/*
* compute an Exponential Weighted moving average
* - https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average
* - heavily inspired from shaka-player
*/
var EWMA = /*#__PURE__*/function () {
// About half of the estimated value will be from the last |halfLife| samples by weight.
function EWMA(halfLife, estimate, weight) {
if (estimate === void 0) {
estimate = 0;
}
if (weight === void 0) {
weight = 0;
}
this.halfLife = void 0;
this.alpha_ = void 0;
this.estimate_ = void 0;
this.totalWeight_ = void 0;
this.halfLife = halfLife; // Larger values of alpha expire historical data more slowly.
this.alpha_ = halfLife ? Math.exp(Math.log(0.5) / halfLife) : 0;
this.estimate_ = estimate;
this.totalWeight_ = weight;
}
var _proto = EWMA.prototype;
_proto.sample = function sample(weight, value) {
var adjAlpha = Math.pow(this.alpha_, weight);
this.estimate_ = value * (1 - adjAlpha) + adjAlpha * this.estimate_;
this.totalWeight_ += weight;
};
_proto.getTotalWeight = function getTotalWeight() {
return this.totalWeight_;
};
_proto.getEstimate = function getEstimate() {
if (this.alpha_) {
var zeroFactor = 1 - Math.pow(this.alpha_, this.totalWeight_);
if (zeroFactor) {
return this.estimate_ / zeroFactor;
}
}
return this.estimate_;
};
return EWMA;
}();
/* harmony default export */ __webpack_exports__["default"] = (EWMA);
/***/ }),
/***/ "./src/utils/fetch-loader.ts":
/*!***********************************!*\
!*** ./src/utils/fetch-loader.ts ***!
\***********************************/
/*! exports provided: fetchSupported, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "fetchSupported", function() { return fetchSupported; });
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var _loader_load_stats__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../loader/load-stats */ "./src/loader/load-stats.ts");
/* harmony import */ var _demux_chunk_cache__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../demux/chunk-cache */ "./src/demux/chunk-cache.ts");
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); }
function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
function fetchSupported() {
if (self.fetch && self.AbortController && self.ReadableStream && self.Request) {
try {
new self.ReadableStream({}); // eslint-disable-line no-new
return true;
} catch (e) {
/* noop */
}
}
return false;
}
var FetchLoader = /*#__PURE__*/function () {
function FetchLoader(config
/* HlsConfig */
) {
this.fetchSetup = void 0;
this.requestTimeout = void 0;
this.request = void 0;
this.response = void 0;
this.controller = void 0;
this.context = void 0;
this.config = null;
this.callbacks = null;
this.stats = void 0;
this.loader = null;
this.fetchSetup = config.fetchSetup || getRequest;
this.controller = new self.AbortController();
this.stats = new _loader_load_stats__WEBPACK_IMPORTED_MODULE_1__["LoadStats"]();
}
var _proto = FetchLoader.prototype;
_proto.destroy = function destroy() {
this.loader = this.callbacks = null;
this.abortInternal();
};
_proto.abortInternal = function abortInternal() {
this.stats.aborted = true;
this.controller.abort();
};
_proto.abort = function abort() {
var _this$callbacks;
this.abortInternal();
if ((_this$callbacks = this.callbacks) !== null && _this$callbacks !== void 0 && _this$callbacks.onAbort) {
this.callbacks.onAbort(this.stats, this.context, this.response);
}
};
_proto.load = function load(context, config, callbacks) {
var _this = this;
var stats = this.stats;
if (stats.loading.start) {
throw new Error('Loader can only be used once.');
}
stats.loading.start = self.performance.now();
var initParams = getRequestParameters(context, this.controller.signal);
var onProgress = callbacks.onProgress;
var isArrayBuffer = context.responseType === 'arraybuffer';
var LENGTH = isArrayBuffer ? 'byteLength' : 'length';
this.context = context;
this.config = config;
this.callbacks = callbacks;
this.request = this.fetchSetup(context, initParams);
self.clearTimeout(this.requestTimeout);
this.requestTimeout = self.setTimeout(function () {
_this.abortInternal();
callbacks.onTimeout(stats, context, _this.response);
}, config.timeout);
self.fetch(this.request).then(function (response) {
_this.response = _this.loader = response;
if (!response.ok) {
var status = response.status,
statusText = response.statusText;
throw new FetchError(statusText || 'fetch, bad network response', status, response);
}
stats.loading.first = Math.max(self.performance.now(), stats.loading.start);
stats.total = parseInt(response.headers.get('Content-Length') || '0');
if (onProgress && Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(config.highWaterMark)) {
_this.loadProgressively(response, stats, context, config.highWaterMark, onProgress);
}
if (isArrayBuffer) {
return response.arrayBuffer();
}
return response.text();
}).then(function (responseData) {
var response = _this.response;
self.clearTimeout(_this.requestTimeout);
stats.loading.end = Math.max(self.performance.now(), stats.loading.first);
stats.loaded = stats.total = responseData[LENGTH];
var loaderResponse = {
url: response.url,
data: responseData
};
if (onProgress && !Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(config.highWaterMark)) {
onProgress(stats, context, responseData, response);
}
callbacks.onSuccess(loaderResponse, stats, context, response);
}).catch(function (error) {
self.clearTimeout(_this.requestTimeout);
if (stats.aborted) {
return;
} // CORS errors result in an undefined code. Set it to 0 here to align with XHR's behavior
var code = error.code || 0;
callbacks.onError({
code: code,
text: error.message
}, context, error.details);
});
};
_proto.getResponseHeader = function getResponseHeader(name) {
if (this.response) {
try {
return this.response.headers.get(name);
} catch (error) {
/* Could not get header */
}
}
return null;
};
_proto.loadProgressively = function loadProgressively(response, stats, context, highWaterMark, onProgress) {
if (highWaterMark === void 0) {
highWaterMark = 0;
}
var chunkCache = new _demux_chunk_cache__WEBPACK_IMPORTED_MODULE_2__["default"]();
var reader = response.clone().body.getReader();
var pump = function pump() {
reader.read().then(function (data) {
if (data.done) {
if (chunkCache.dataLength) {
onProgress(stats, context, chunkCache.flush(), response);
}
return;
}
var chunk = data.value;
var len = chunk.length;
stats.loaded += len;
if (len < highWaterMark || chunkCache.dataLength) {
// The current chunk is too small to to be emitted or the cache already has data
// Push it to the cache
chunkCache.push(chunk);
if (chunkCache.dataLength >= highWaterMark) {
// flush in order to join the typed arrays
onProgress(stats, context, chunkCache.flush(), response);
}
} else {
// If there's nothing cached already, and the chache is large enough
// just emit the progress event
onProgress(stats, context, chunk, response);
}
pump();
}).catch(function () {
/* aborted */
});
};
pump();
};
return FetchLoader;
}();
function getRequestParameters(context, signal) {
var initParams = {
method: 'GET',
mode: 'cors',
credentials: 'same-origin',
signal: signal
};
if (context.rangeEnd) {
initParams.headers = new self.Headers({
Range: 'bytes=' + context.rangeStart + '-' + String(context.rangeEnd - 1)
});
}
return initParams;
}
function getRequest(context, initParams) {
return new self.Request(context.url, initParams);
}
var FetchError = /*#__PURE__*/function (_Error) {
_inheritsLoose(FetchError, _Error);
function FetchError(message, code, details) {
var _this2;
_this2 = _Error.call(this, message) || this;
_this2.code = void 0;
_this2.details = void 0;
_this2.code = code;
_this2.details = details;
return _this2;
}
return FetchError;
}( /*#__PURE__*/_wrapNativeSuper(Error));
/* harmony default export */ __webpack_exports__["default"] = (FetchLoader);
/***/ }),
/***/ "./src/utils/imsc1-ttml-parser.ts":
/*!****************************************!*\
!*** ./src/utils/imsc1-ttml-parser.ts ***!
\****************************************/
/*! exports provided: IMSC1_CODEC, parseIMSC1 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "IMSC1_CODEC", function() { return IMSC1_CODEC; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseIMSC1", function() { return parseIMSC1; });
/* harmony import */ var _mp4_tools__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./mp4-tools */ "./src/utils/mp4-tools.ts");
/* harmony import */ var _vttparser__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./vttparser */ "./src/utils/vttparser.ts");
/* harmony import */ var _vttcue__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./vttcue */ "./src/utils/vttcue.ts");
/* harmony import */ var _demux_id3__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../demux/id3 */ "./src/demux/id3.ts");
/* harmony import */ var _timescale_conversion__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./timescale-conversion */ "./src/utils/timescale-conversion.ts");
/* harmony import */ var _webvtt_parser__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./webvtt-parser */ "./src/utils/webvtt-parser.ts");
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
var IMSC1_CODEC = 'stpp.ttml.im1t'; // Time format: h:m:s:frames(.subframes)
var HMSF_REGEX = /^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/; // Time format: hours, minutes, seconds, milliseconds, frames, ticks
var TIME_UNIT_REGEX = /^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/;
function parseIMSC1(payload, initPTS, timescale, callBack, errorCallBack) {
var results = Object(_mp4_tools__WEBPACK_IMPORTED_MODULE_0__["findBox"])(new Uint8Array(payload), ['mdat']);
if (results.length === 0) {
errorCallBack(new Error('Could not parse IMSC1 mdat'));
return;
}
var mdat = results[0];
var ttml = Object(_demux_id3__WEBPACK_IMPORTED_MODULE_3__["utf8ArrayToStr"])(new Uint8Array(payload, mdat.start, mdat.end - mdat.start));
var syncTime = Object(_timescale_conversion__WEBPACK_IMPORTED_MODULE_4__["toTimescaleFromScale"])(initPTS, 1, timescale);
try {
callBack(parseTTML(ttml, syncTime));
} catch (error) {
errorCallBack(error);
}
}
function parseTTML(ttml, syncTime) {
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(ttml, 'text/xml');
var tt = xmlDoc.getElementsByTagName('tt')[0];
if (!tt) {
throw new Error('Invalid ttml');
}
var defaultRateInfo = {
frameRate: 30,
subFrameRate: 1,
frameRateMultiplier: 0,
tickRate: 0
};
var rateInfo = Object.keys(defaultRateInfo).reduce(function (result, key) {
result[key] = tt.getAttribute("ttp:" + key) || defaultRateInfo[key];
return result;
}, {});
var trim = tt.getAttribute('xml:space') !== 'preserve';
var styleElements = collectionToDictionary(getElementCollection(tt, 'styling', 'style'));
var regionElements = collectionToDictionary(getElementCollection(tt, 'layout', 'region'));
var cueElements = getElementCollection(tt, 'body', '[begin]');
return [].map.call(cueElements, function (cueElement) {
var cueText = getTextContent(cueElement, trim);
if (!cueText || !cueElement.hasAttribute('begin')) {
return null;
}
var startTime = parseTtmlTime(cueElement.getAttribute('begin'), rateInfo);
var duration = parseTtmlTime(cueElement.getAttribute('dur'), rateInfo);
var endTime = parseTtmlTime(cueElement.getAttribute('end'), rateInfo);
if (startTime === null) {
throw timestampParsingError(cueElement);
}
if (endTime === null) {
if (duration === null) {
throw timestampParsingError(cueElement);
}
endTime = startTime + duration;
}
var cue = new _vttcue__WEBPACK_IMPORTED_MODULE_2__["default"](startTime - syncTime, endTime - syncTime, cueText);
cue.id = Object(_webvtt_parser__WEBPACK_IMPORTED_MODULE_5__["generateCueId"])(cue.startTime, cue.endTime, cue.text);
var region = regionElements[cueElement.getAttribute('region')];
var style = styleElements[cueElement.getAttribute('style')]; // TODO: Add regions to track and cue (origin and extend)
// These values are hard-coded (for now) to simulate region settings in the demo
cue.position = 10;
cue.size = 80; // Apply styles to cue
var styles = getTtmlStyles(region, style);
var textAlign = styles.textAlign;
if (textAlign) {
// cue.positionAlign not settable in FF~2016
cue.lineAlign = {
left: 'start',
center: 'center',
right: 'end',
start: 'start',
end: 'end'
}[textAlign];
cue.align = textAlign;
}
_extends(cue, styles);
return cue;
}).filter(function (cue) {
return cue !== null;
});
}
function getElementCollection(fromElement, parentName, childName) {
var parent = fromElement.getElementsByTagName(parentName)[0];
if (parent) {
return [].slice.call(parent.querySelectorAll(childName));
}
return [];
}
function collectionToDictionary(elementsWithId) {
return elementsWithId.reduce(function (dict, element) {
var id = element.getAttribute('xml:id');
if (id) {
dict[id] = element;
}
return dict;
}, {});
}
function getTextContent(element, trim) {
return [].slice.call(element.childNodes).reduce(function (str, node, i) {
var _node$childNodes;
if (node.nodeName === 'br' && i) {
return str + '\n';
}
if ((_node$childNodes = node.childNodes) !== null && _node$childNodes !== void 0 && _node$childNodes.length) {
return getTextContent(node, trim);
} else if (trim) {
return str + node.textContent.trim().replace(/\s+/g, ' ');
}
return str + node.textContent;
}, '');
}
function getTtmlStyles(region, style) {
var ttsNs = 'http://www.w3.org/ns/ttml#styling';
var styleAttributes = ['displayAlign', 'textAlign', 'color', 'backgroundColor', 'fontSize', 'fontFamily' // 'fontWeight',
// 'lineHeight',
// 'wrapOption',
// 'fontStyle',
// 'direction',
// 'writingMode'
];
return styleAttributes.reduce(function (styles, name) {
var value = getAttributeNS(style, ttsNs, name) || getAttributeNS(region, ttsNs, name);
if (value) {
styles[name] = value;
}
return styles;
}, {});
}
function getAttributeNS(element, ns, name) {
return element.hasAttributeNS(ns, name) ? element.getAttributeNS(ns, name) : null;
}
function timestampParsingError(node) {
return new Error("Could not parse ttml timestamp " + node);
}
function parseTtmlTime(timeAttributeValue, rateInfo) {
if (!timeAttributeValue) {
return null;
}
var seconds = Object(_vttparser__WEBPACK_IMPORTED_MODULE_1__["parseTimeStamp"])(timeAttributeValue);
if (seconds === null) {
if (HMSF_REGEX.test(timeAttributeValue)) {
seconds = parseHoursMinutesSecondsFrames(timeAttributeValue, rateInfo);
} else if (TIME_UNIT_REGEX.test(timeAttributeValue)) {
seconds = parseTimeUnits(timeAttributeValue, rateInfo);
}
}
return seconds;
}
function parseHoursMinutesSecondsFrames(timeAttributeValue, rateInfo) {
var m = HMSF_REGEX.exec(timeAttributeValue);
var frames = (m[4] | 0) + (m[5] | 0) / rateInfo.subFrameRate;
return (m[1] | 0) * 3600 + (m[2] | 0) * 60 + (m[3] | 0) + frames / rateInfo.frameRate;
}
function parseTimeUnits(timeAttributeValue, rateInfo) {
var m = TIME_UNIT_REGEX.exec(timeAttributeValue);
var value = Number(m[1]);
var unit = m[2];
switch (unit) {
case 'h':
return value * 3600;
case 'm':
return value * 60;
case 'ms':
return value * 1000;
case 'f':
return value / rateInfo.frameRate;
case 't':
return value / rateInfo.tickRate;
}
return value;
}
/***/ }),
/***/ "./src/utils/logger.ts":
/*!*****************************!*\
!*** ./src/utils/logger.ts ***!
\*****************************/
/*! exports provided: enableLogs, logger */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "enableLogs", function() { return enableLogs; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "logger", function() { return logger; });
var noop = function noop() {};
var fakeLogger = {
trace: noop,
debug: noop,
log: noop,
warn: noop,
info: noop,
error: noop
};
var exportedLogger = fakeLogger; // let lastCallTime;
// function formatMsgWithTimeInfo(type, msg) {
// const now = Date.now();
// const diff = lastCallTime ? '+' + (now - lastCallTime) : '0';
// lastCallTime = now;
// msg = (new Date(now)).toISOString() + ' | [' + type + '] > ' + msg + ' ( ' + diff + ' ms )';
// return msg;
// }
function consolePrintFn(type) {
var func = self.console[type];
if (func) {
return func.bind(self.console, "[" + type + "] >");
}
return noop;
}
function exportLoggerFunctions(debugConfig) {
for (var _len = arguments.length, functions = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
functions[_key - 1] = arguments[_key];
}
functions.forEach(function (type) {
exportedLogger[type] = debugConfig[type] ? debugConfig[type].bind(debugConfig) : consolePrintFn(type);
});
}
function enableLogs(debugConfig) {
// check that console is available
if (self.console && debugConfig === true || typeof debugConfig === 'object') {
exportLoggerFunctions(debugConfig, // Remove out from list here to hard-disable a log-level
// 'trace',
'debug', 'log', 'info', 'warn', 'error'); // Some browsers don't allow to use bind on console object anyway
// fallback to default if needed
try {
exportedLogger.log();
} catch (e) {
exportedLogger = fakeLogger;
}
} else {
exportedLogger = fakeLogger;
}
}
var logger = exportedLogger;
/***/ }),
/***/ "./src/utils/mediakeys-helper.ts":
/*!***************************************!*\
!*** ./src/utils/mediakeys-helper.ts ***!
\***************************************/
/*! exports provided: KeySystems, requestMediaKeySystemAccess */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "KeySystems", function() { return KeySystems; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "requestMediaKeySystemAccess", function() { return requestMediaKeySystemAccess; });
/**
* @see https://developer.mozilla.org/en-US/docs/Web/API/Navigator/requestMediaKeySystemAccess
*/
var KeySystems;
(function (KeySystems) {
KeySystems["WIDEVINE"] = "com.widevine.alpha";
KeySystems["PLAYREADY"] = "com.microsoft.playready";
})(KeySystems || (KeySystems = {}));
var requestMediaKeySystemAccess = function () {
if (typeof self !== 'undefined' && self.navigator && self.navigator.requestMediaKeySystemAccess) {
return self.navigator.requestMediaKeySystemAccess.bind(self.navigator);
} else {
return null;
}
}();
/***/ }),
/***/ "./src/utils/mediasource-helper.ts":
/*!*****************************************!*\
!*** ./src/utils/mediasource-helper.ts ***!
\*****************************************/
/*! exports provided: getMediaSource */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getMediaSource", function() { return getMediaSource; });
/**
* MediaSource helper
*/
function getMediaSource() {
return self.MediaSource || self.WebKitMediaSource;
}
/***/ }),
/***/ "./src/utils/mp4-tools.ts":
/*!********************************!*\
!*** ./src/utils/mp4-tools.ts ***!
\********************************/
/*! exports provided: bin2str, readUint16, readUint32, writeUint32, findBox, parseSegmentIndex, parseInitSegment, getStartDTS, getDuration, computeRawDurationFromSamples, offsetStartDTS, segmentValidRange, appendUint8Array */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "bin2str", function() { return bin2str; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "readUint16", function() { return readUint16; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "readUint32", function() { return readUint32; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "writeUint32", function() { return writeUint32; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findBox", function() { return findBox; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseSegmentIndex", function() { return parseSegmentIndex; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseInitSegment", function() { return parseInitSegment; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getStartDTS", function() { return getStartDTS; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getDuration", function() { return getDuration; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "computeRawDurationFromSamples", function() { return computeRawDurationFromSamples; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "offsetStartDTS", function() { return offsetStartDTS; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "segmentValidRange", function() { return segmentValidRange; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "appendUint8Array", function() { return appendUint8Array; });
/* harmony import */ var _typed_array__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./typed-array */ "./src/utils/typed-array.ts");
/* harmony import */ var _loader_fragment__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../loader/fragment */ "./src/loader/fragment.ts");
var UINT32_MAX = Math.pow(2, 32) - 1;
var push = [].push;
function bin2str(data) {
return String.fromCharCode.apply(null, data);
}
function readUint16(buffer, offset) {
if ('data' in buffer) {
offset += buffer.start;
buffer = buffer.data;
}
var val = buffer[offset] << 8 | buffer[offset + 1];
return val < 0 ? 65536 + val : val;
}
function readUint32(buffer, offset) {
if ('data' in buffer) {
offset += buffer.start;
buffer = buffer.data;
}
var val = buffer[offset] << 24 | buffer[offset + 1] << 16 | buffer[offset + 2] << 8 | buffer[offset + 3];
return val < 0 ? 4294967296 + val : val;
}
function writeUint32(buffer, offset, value) {
if ('data' in buffer) {
offset += buffer.start;
buffer = buffer.data;
}
buffer[offset] = value >> 24;
buffer[offset + 1] = value >> 16 & 0xff;
buffer[offset + 2] = value >> 8 & 0xff;
buffer[offset + 3] = value & 0xff;
} // Find the data for a box specified by its path
function findBox(input, path) {
var results = [];
if (!path.length) {
// short-circuit the search for empty paths
return results;
}
var data;
var start;
var end;
if ('data' in input) {
data = input.data;
start = input.start;
end = input.end;
} else {
data = input;
start = 0;
end = data.byteLength;
}
for (var i = start; i < end;) {
var size = readUint32(data, i);
var type = bin2str(data.subarray(i + 4, i + 8));
var endbox = size > 1 ? i + size : end;
if (type === path[0]) {
if (path.length === 1) {
// this is the end of the path and we've found the box we were
// looking for
results.push({
data: data,
start: i + 8,
end: endbox
});
} else {
// recursively search for the next box along the path
var subresults = findBox({
data: data,
start: i + 8,
end: endbox
}, path.slice(1));
if (subresults.length) {
push.apply(results, subresults);
}
}
}
i = endbox;
} // we've finished searching all of data
return results;
}
function parseSegmentIndex(initSegment) {
var moovBox = findBox(initSegment, ['moov']);
var moov = moovBox[0];
var moovEndOffset = moov ? moov.end : null; // we need this in case we need to chop of garbage of the end of current data
var sidxBox = findBox(initSegment, ['sidx']);
if (!sidxBox || !sidxBox[0]) {
return null;
}
var references = [];
var sidx = sidxBox[0];
var version = sidx.data[0]; // set initial offset, we skip the reference ID (not needed)
var index = version === 0 ? 8 : 16;
var timescale = readUint32(sidx, index);
index += 4; // TODO: parse earliestPresentationTime and firstOffset
// usually zero in our case
var earliestPresentationTime = 0;
var firstOffset = 0;
if (version === 0) {
index += 8;
} else {
index += 16;
} // skip reserved
index += 2;
var startByte = sidx.end + firstOffset;
var referencesCount = readUint16(sidx, index);
index += 2;
for (var i = 0; i < referencesCount; i++) {
var referenceIndex = index;
var referenceInfo = readUint32(sidx, referenceIndex);
referenceIndex += 4;
var referenceSize = referenceInfo & 0x7fffffff;
var referenceType = (referenceInfo & 0x80000000) >>> 31;
if (referenceType === 1) {
// eslint-disable-next-line no-console
console.warn('SIDX has hierarchical references (not supported)');
return null;
}
var subsegmentDuration = readUint32(sidx, referenceIndex);
referenceIndex += 4;
references.push({
referenceSize: referenceSize,
subsegmentDuration: subsegmentDuration,
// unscaled
info: {
duration: subsegmentDuration / timescale,
start: startByte,
end: startByte + referenceSize - 1
}
});
startByte += referenceSize; // Skipping 1 bit for |startsWithSap|, 3 bits for |sapType|, and 28 bits
// for |sapDelta|.
referenceIndex += 4; // skip to next ref
index = referenceIndex;
}
return {
earliestPresentationTime: earliestPresentationTime,
timescale: timescale,
version: version,
referencesCount: referencesCount,
references: references,
moovEndOffset: moovEndOffset
};
}
/**
* Parses an MP4 initialization segment and extracts stream type and
* timescale values for any declared tracks. Timescale values indicate the
* number of clock ticks per second to assume for time-based values
* elsewhere in the MP4.
*
* To determine the start time of an MP4, you need two pieces of
* information: the timescale unit and the earliest base media decode
* time. Multiple timescales can be specified within an MP4 but the
* base media decode time is always expressed in the timescale from
* the media header box for the track:
* ```
* moov > trak > mdia > mdhd.timescale
* moov > trak > mdia > hdlr
* ```
* @param initSegment {Uint8Array} the bytes of the init segment
* @return {InitData} a hash of track type to timescale values or null if
* the init segment is malformed.
*/
function parseInitSegment(initSegment) {
var result = [];
var traks = findBox(initSegment, ['moov', 'trak']);
for (var i = 0; i < traks.length; i++) {
var trak = traks[i];
var tkhd = findBox(trak, ['tkhd'])[0];
if (tkhd) {
var version = tkhd.data[tkhd.start];
var _index = version === 0 ? 12 : 20;
var trackId = readUint32(tkhd, _index);
var mdhd = findBox(trak, ['mdia', 'mdhd'])[0];
if (mdhd) {
version = mdhd.data[mdhd.start];
_index = version === 0 ? 12 : 20;
var timescale = readUint32(mdhd, _index);
var hdlr = findBox(trak, ['mdia', 'hdlr'])[0];
if (hdlr) {
var hdlrType = bin2str(hdlr.data.subarray(hdlr.start + 8, hdlr.start + 12));
var type = {
soun: _loader_fragment__WEBPACK_IMPORTED_MODULE_1__["ElementaryStreamTypes"].AUDIO,
vide: _loader_fragment__WEBPACK_IMPORTED_MODULE_1__["ElementaryStreamTypes"].VIDEO
}[hdlrType];
if (type) {
// Parse codec details
var stsd = findBox(trak, ['mdia', 'minf', 'stbl', 'stsd'])[0];
var codec = void 0;
if (stsd) {
codec = bin2str(stsd.data.subarray(stsd.start + 12, stsd.start + 16)); // TODO: Parse codec details to be able to build MIME type.
// stsd.start += 8;
// const codecBox = findBox(stsd, [codec])[0];
// if (codecBox) {
// TODO: Codec parsing support for avc1, mp4a, hevc, av01...
// }
}
result[trackId] = {
timescale: timescale,
type: type
};
result[type] = {
timescale: timescale,
id: trackId,
codec: codec
};
}
}
}
}
}
var trex = findBox(initSegment, ['moov', 'mvex', 'trex']);
trex.forEach(function (trex) {
var trackId = readUint32(trex, 4);
var track = result[trackId];
if (track) {
track.default = {
duration: readUint32(trex, 12),
flags: readUint32(trex, 20)
};
}
});
return result;
}
/**
* Determine the base media decode start time, in seconds, for an MP4
* fragment. If multiple fragments are specified, the earliest time is
* returned.
*
* The base media decode time can be parsed from track fragment
* metadata:
* ```
* moof > traf > tfdt.baseMediaDecodeTime
* ```
* It requires the timescale value from the mdhd to interpret.
*
* @param initData {InitData} a hash of track type to timescale values
* @param fmp4 {Uint8Array} the bytes of the mp4 fragment
* @return {number} the earliest base media decode start time for the
* fragment, in seconds
*/
function getStartDTS(initData, fmp4) {
// we need info from two children of each track fragment box
return findBox(fmp4, ['moof', 'traf']).reduce(function (result, traf) {
var tfdt = findBox(traf, ['tfdt'])[0];
var version = tfdt.data[tfdt.start];
var start = findBox(traf, ['tfhd']).reduce(function (result, tfhd) {
// get the track id from the tfhd
var id = readUint32(tfhd, 4);
var track = initData[id];
if (track) {
var baseTime = readUint32(tfdt, 4);
if (version === 1) {
baseTime *= Math.pow(2, 32);
baseTime += readUint32(tfdt, 8);
} // assume a 90kHz clock if no timescale was specified
var scale = track.timescale || 90e3; // convert base time to seconds
var startTime = baseTime / scale;
if (isFinite(startTime) && (result === null || startTime < result)) {
return startTime;
}
}
return result;
}, null);
if (start !== null && isFinite(start) && (result === null || start < result)) {
return start;
}
return result;
}, null) || 0;
}
/*
For Reference:
aligned(8) class TrackFragmentHeaderBox
extends FullBox(‘tfhd’, 0, tf_flags){
unsigned int(32) track_ID;
// all the following are optional fields
unsigned int(64) base_data_offset;
unsigned int(32) sample_description_index;
unsigned int(32) default_sample_duration;
unsigned int(32) default_sample_size;
unsigned int(32) default_sample_flags
}
*/
function getDuration(data, initData) {
var rawDuration = 0;
var videoDuration = 0;
var audioDuration = 0;
var trafs = findBox(data, ['moof', 'traf']);
for (var i = 0; i < trafs.length; i++) {
var traf = trafs[i]; // There is only one tfhd & trun per traf
// This is true for CMAF style content, and we should perhaps check the ftyp
// and only look for a single trun then, but for ISOBMFF we should check
// for multiple track runs.
var tfhd = findBox(traf, ['tfhd'])[0]; // get the track id from the tfhd
var id = readUint32(tfhd, 4);
var track = initData[id];
if (!track) {
continue;
}
var trackDefault = track.default;
var tfhdFlags = readUint32(tfhd, 0) | (trackDefault === null || trackDefault === void 0 ? void 0 : trackDefault.flags);
var sampleDuration = trackDefault === null || trackDefault === void 0 ? void 0 : trackDefault.duration;
if (tfhdFlags & 0x000008) {
// 0x000008 indicates the presence of the default_sample_duration field
if (tfhdFlags & 0x000002) {
// 0x000002 indicates the presence of the sample_description_index field, which precedes default_sample_duration
// If present, the default_sample_duration exists at byte offset 12
sampleDuration = readUint32(tfhd, 12);
} else {
// Otherwise, the duration is at byte offset 8
sampleDuration = readUint32(tfhd, 8);
}
} // assume a 90kHz clock if no timescale was specified
var timescale = track.timescale || 90e3;
var truns = findBox(traf, ['trun']);
for (var j = 0; j < truns.length; j++) {
if (sampleDuration) {
var sampleCount = readUint32(truns[j], 4);
rawDuration = sampleDuration * sampleCount;
} else {
rawDuration = computeRawDurationFromSamples(truns[j]);
}
if (track.type === _loader_fragment__WEBPACK_IMPORTED_MODULE_1__["ElementaryStreamTypes"].VIDEO) {
videoDuration += rawDuration / timescale;
} else if (track.type === _loader_fragment__WEBPACK_IMPORTED_MODULE_1__["ElementaryStreamTypes"].AUDIO) {
audioDuration += rawDuration / timescale;
}
}
}
if (videoDuration === 0 && audioDuration === 0) {
// If duration samples are not available in the traf use sidx subsegment_duration
var sidx = parseSegmentIndex(data);
if (sidx !== null && sidx !== void 0 && sidx.references) {
return sidx.references.reduce(function (dur, ref) {
return dur + ref.info.duration || 0;
}, 0);
}
}
if (videoDuration) {
return videoDuration;
}
return audioDuration;
}
/*
For Reference:
aligned(8) class TrackRunBox
extends FullBox(‘trun’, version, tr_flags) {
unsigned int(32) sample_count;
// the following are optional fields
signed int(32) data_offset;
unsigned int(32) first_sample_flags;
// all fields in the following array are optional
{
unsigned int(32) sample_duration;
unsigned int(32) sample_size;
unsigned int(32) sample_flags
if (version == 0)
{ unsigned int(32)
else
{ signed int(32)
}[ sample_count ]
}
*/
function computeRawDurationFromSamples(trun) {
var flags = readUint32(trun, 0); // Flags are at offset 0, non-optional sample_count is at offset 4. Therefore we start 8 bytes in.
// Each field is an int32, which is 4 bytes
var offset = 8; // data-offset-present flag
if (flags & 0x000001) {
offset += 4;
} // first-sample-flags-present flag
if (flags & 0x000004) {
offset += 4;
}
var duration = 0;
var sampleCount = readUint32(trun, 4);
for (var i = 0; i < sampleCount; i++) {
// sample-duration-present flag
if (flags & 0x000100) {
var sampleDuration = readUint32(trun, offset);
duration += sampleDuration;
offset += 4;
} // sample-size-present flag
if (flags & 0x000200) {
offset += 4;
} // sample-flags-present flag
if (flags & 0x000400) {
offset += 4;
} // sample-composition-time-offsets-present flag
if (flags & 0x000800) {
offset += 4;
}
}
return duration;
}
function offsetStartDTS(initData, fmp4, timeOffset) {
findBox(fmp4, ['moof', 'traf']).forEach(function (traf) {
findBox(traf, ['tfhd']).forEach(function (tfhd) {
// get the track id from the tfhd
var id = readUint32(tfhd, 4);
var track = initData[id];
if (!track) {
return;
} // assume a 90kHz clock if no timescale was specified
var timescale = track.timescale || 90e3; // get the base media decode time from the tfdt
findBox(traf, ['tfdt']).forEach(function (tfdt) {
var version = tfdt.data[tfdt.start];
var baseMediaDecodeTime = readUint32(tfdt, 4);
if (version === 0) {
writeUint32(tfdt, 4, baseMediaDecodeTime - timeOffset * timescale);
} else {
baseMediaDecodeTime *= Math.pow(2, 32);
baseMediaDecodeTime += readUint32(tfdt, 8);
baseMediaDecodeTime -= timeOffset * timescale;
baseMediaDecodeTime = Math.max(baseMediaDecodeTime, 0);
var upper = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1));
var lower = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1));
writeUint32(tfdt, 4, upper);
writeUint32(tfdt, 8, lower);
}
});
});
});
} // TODO: Check if the last moof+mdat pair is part of the valid range
function segmentValidRange(data) {
var segmentedRange = {
valid: null,
remainder: null
};
var moofs = findBox(data, ['moof']);
if (!moofs) {
return segmentedRange;
} else if (moofs.length < 2) {
segmentedRange.remainder = data;
return segmentedRange;
}
var last = moofs[moofs.length - 1]; // Offset by 8 bytes; findBox offsets the start by as much
segmentedRange.valid = Object(_typed_array__WEBPACK_IMPORTED_MODULE_0__["sliceUint8"])(data, 0, last.start - 8);
segmentedRange.remainder = Object(_typed_array__WEBPACK_IMPORTED_MODULE_0__["sliceUint8"])(data, last.start - 8);
return segmentedRange;
}
function appendUint8Array(data1, data2) {
var temp = new Uint8Array(data1.length + data2.length);
temp.set(data1);
temp.set(data2, data1.length);
return temp;
}
/***/ }),
/***/ "./src/utils/output-filter.ts":
/*!************************************!*\
!*** ./src/utils/output-filter.ts ***!
\************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return OutputFilter; });
var OutputFilter = /*#__PURE__*/function () {
function OutputFilter(timelineController, trackName) {
this.timelineController = void 0;
this.cueRanges = [];
this.trackName = void 0;
this.startTime = null;
this.endTime = null;
this.screen = null;
this.timelineController = timelineController;
this.trackName = trackName;
}
var _proto = OutputFilter.prototype;
_proto.dispatchCue = function dispatchCue() {
if (this.startTime === null) {
return;
}
this.timelineController.addCues(this.trackName, this.startTime, this.endTime, this.screen, this.cueRanges);
this.startTime = null;
};
_proto.newCue = function newCue(startTime, endTime, screen) {
if (this.startTime === null || this.startTime > startTime) {
this.startTime = startTime;
}
this.endTime = endTime;
this.screen = screen;
this.timelineController.createCaptionsTrack(this.trackName);
};
_proto.reset = function reset() {
this.cueRanges = [];
};
return OutputFilter;
}();
/***/ }),
/***/ "./src/utils/texttrack-utils.ts":
/*!**************************************!*\
!*** ./src/utils/texttrack-utils.ts ***!
\**************************************/
/*! exports provided: sendAddTrackEvent, addCueToTrack, clearCurrentCues, removeCuesInRange, getCuesInRange */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sendAddTrackEvent", function() { return sendAddTrackEvent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "addCueToTrack", function() { return addCueToTrack; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "clearCurrentCues", function() { return clearCurrentCues; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "removeCuesInRange", function() { return removeCuesInRange; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getCuesInRange", function() { return getCuesInRange; });
/* harmony import */ var _logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./logger */ "./src/utils/logger.ts");
function sendAddTrackEvent(track, videoEl) {
var event;
try {
event = new Event('addtrack');
} catch (err) {
// for IE11
event = document.createEvent('Event');
event.initEvent('addtrack', false, false);
}
event.track = track;
videoEl.dispatchEvent(event);
}
function addCueToTrack(track, cue) {
// Sometimes there are cue overlaps on segmented vtts so the same
// cue can appear more than once in different vtt files.
// This avoid showing duplicated cues with same timecode and text.
var mode = track.mode;
if (mode === 'disabled') {
track.mode = 'hidden';
}
if (track.cues && !track.cues.getCueById(cue.id)) {
try {
track.addCue(cue);
if (!track.cues.getCueById(cue.id)) {
throw new Error("addCue is failed for: " + cue);
}
} catch (err) {
_logger__WEBPACK_IMPORTED_MODULE_0__["logger"].debug("[texttrack-utils]: " + err);
var textTrackCue = new self.TextTrackCue(cue.startTime, cue.endTime, cue.text);
textTrackCue.id = cue.id;
track.addCue(textTrackCue);
}
}
if (mode === 'disabled') {
track.mode = mode;
}
}
function clearCurrentCues(track) {
// When track.mode is disabled, track.cues will be null.
// To guarantee the removal of cues, we need to temporarily
// change the mode to hidden
var mode = track.mode;
if (mode === 'disabled') {
track.mode = 'hidden';
}
if (!track.cues) {
return;
}
for (var i = track.cues.length; i--;) {
track.removeCue(track.cues[i]);
}
if (mode === 'disabled') {
track.mode = mode;
}
}
function removeCuesInRange(track, start, end) {
var mode = track.mode;
if (mode === 'disabled') {
track.mode = 'hidden';
}
if (!track.cues || !track.cues.length) {
return;
}
var cues = getCuesInRange(track.cues, start, end);
for (var i = 0; i < cues.length; i++) {
track.removeCue(cues[i]);
}
if (mode === 'disabled') {
track.mode = mode;
}
} // Find first cue starting after given time.
// Modified version of binary search O(log(n)).
function getFirstCueIndexAfterTime(cues, time) {
// If first cue starts after time, start there
if (time < cues[0].startTime) {
return 0;
} // If the last cue ends before time there is no overlap
var len = cues.length - 1;
if (time > cues[len].endTime) {
return -1;
}
var left = 0;
var right = len;
while (left <= right) {
var mid = Math.floor((right + left) / 2);
if (time < cues[mid].startTime) {
right = mid - 1;
} else if (time > cues[mid].startTime && left < len) {
left = mid + 1;
} else {
// If it's not lower or higher, it must be equal.
return mid;
}
} // At this point, left and right have swapped.
// No direct match was found, left or right element must be the closest. Check which one has the smallest diff.
return cues[left].startTime - time < time - cues[right].startTime ? left : right;
}
function getCuesInRange(cues, start, end) {
var cuesFound = [];
var firstCueInRange = getFirstCueIndexAfterTime(cues, start);
if (firstCueInRange > -1) {
for (var i = firstCueInRange, len = cues.length; i < len; i++) {
var cue = cues[i];
if (cue.startTime >= start && cue.endTime <= end) {
cuesFound.push(cue);
} else if (cue.startTime > end) {
return cuesFound;
}
}
}
return cuesFound;
}
/***/ }),
/***/ "./src/utils/time-ranges.ts":
/*!**********************************!*\
!*** ./src/utils/time-ranges.ts ***!
\**********************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/**
* TimeRanges to string helper
*/
var TimeRanges = {
toString: function toString(r) {
var log = '';
var len = r.length;
for (var i = 0; i < len; i++) {
log += '[' + r.start(i).toFixed(3) + ',' + r.end(i).toFixed(3) + ']';
}
return log;
}
};
/* harmony default export */ __webpack_exports__["default"] = (TimeRanges);
/***/ }),
/***/ "./src/utils/timescale-conversion.ts":
/*!*******************************************!*\
!*** ./src/utils/timescale-conversion.ts ***!
\*******************************************/
/*! exports provided: toTimescaleFromBase, toTimescaleFromScale, toMsFromMpegTsClock, toMpegTsClockFromTimescale */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toTimescaleFromBase", function() { return toTimescaleFromBase; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toTimescaleFromScale", function() { return toTimescaleFromScale; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toMsFromMpegTsClock", function() { return toMsFromMpegTsClock; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toMpegTsClockFromTimescale", function() { return toMpegTsClockFromTimescale; });
var MPEG_TS_CLOCK_FREQ_HZ = 90000;
function toTimescaleFromBase(value, destScale, srcBase, round) {
if (srcBase === void 0) {
srcBase = 1;
}
if (round === void 0) {
round = false;
}
var result = value * destScale * srcBase; // equivalent to `(value * scale) / (1 / base)`
return round ? Math.round(result) : result;
}
function toTimescaleFromScale(value, destScale, srcScale, round) {
if (srcScale === void 0) {
srcScale = 1;
}
if (round === void 0) {
round = false;
}
return toTimescaleFromBase(value, destScale, 1 / srcScale, round);
}
function toMsFromMpegTsClock(value, round) {
if (round === void 0) {
round = false;
}
return toTimescaleFromBase(value, 1000, 1 / MPEG_TS_CLOCK_FREQ_HZ, round);
}
function toMpegTsClockFromTimescale(value, srcScale) {
if (srcScale === void 0) {
srcScale = 1;
}
return toTimescaleFromBase(value, MPEG_TS_CLOCK_FREQ_HZ, 1 / srcScale);
}
/***/ }),
/***/ "./src/utils/typed-array.ts":
/*!**********************************!*\
!*** ./src/utils/typed-array.ts ***!
\**********************************/
/*! exports provided: sliceUint8 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sliceUint8", function() { return sliceUint8; });
function sliceUint8(array, start, end) {
// @ts-expect-error This polyfills IE11 usage of Uint8Array slice.
// It always exists in the TypeScript definition so fails, but it fails at runtime on IE11.
return Uint8Array.prototype.slice ? array.slice(start, end) : new Uint8Array(Array.prototype.slice.call(array, start, end));
}
/***/ }),
/***/ "./src/utils/vttcue.ts":
/*!*****************************!*\
!*** ./src/utils/vttcue.ts ***!
\*****************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/**
* Copyright 2013 vtt.js Contributors
*
* 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.
*/
/* harmony default export */ __webpack_exports__["default"] = ((function () {
if (typeof self !== 'undefined' && self.VTTCue) {
return self.VTTCue;
}
var AllowedDirections = ['', 'lr', 'rl'];
var AllowedAlignments = ['start', 'middle', 'end', 'left', 'right'];
function isAllowedValue(allowed, value) {
if (typeof value !== 'string') {
return false;
} // necessary for assuring the generic conforms to the Array interface
if (!Array.isArray(allowed)) {
return false;
} // reset the type so that the next narrowing works well
var lcValue = value.toLowerCase(); // use the allow list to narrow the type to a specific subset of strings
if (~allowed.indexOf(lcValue)) {
return lcValue;
}
return false;
}
function findDirectionSetting(value) {
return isAllowedValue(AllowedDirections, value);
}
function findAlignSetting(value) {
return isAllowedValue(AllowedAlignments, value);
}
function extend(obj) {
for (var _len = arguments.length, rest = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
rest[_key - 1] = arguments[_key];
}
var i = 1;
for (; i < arguments.length; i++) {
var cobj = arguments[i];
for (var p in cobj) {
obj[p] = cobj[p];
}
}
return obj;
}
function VTTCue(startTime, endTime, text) {
var cue = this;
var baseObj = {
enumerable: true
};
/**
* Shim implementation specific properties. These properties are not in
* the spec.
*/
// Lets us know when the VTTCue's data has changed in such a way that we need
// to recompute its display state. This lets us compute its display state
// lazily.
cue.hasBeenReset = false;
/**
* VTTCue and TextTrackCue properties
* http://dev.w3.org/html5/webvtt/#vttcue-interface
*/
var _id = '';
var _pauseOnExit = false;
var _startTime = startTime;
var _endTime = endTime;
var _text = text;
var _region = null;
var _vertical = '';
var _snapToLines = true;
var _line = 'auto';
var _lineAlign = 'start';
var _position = 50;
var _positionAlign = 'middle';
var _size = 50;
var _align = 'middle';
Object.defineProperty(cue, 'id', extend({}, baseObj, {
get: function get() {
return _id;
},
set: function set(value) {
_id = '' + value;
}
}));
Object.defineProperty(cue, 'pauseOnExit', extend({}, baseObj, {
get: function get() {
return _pauseOnExit;
},
set: function set(value) {
_pauseOnExit = !!value;
}
}));
Object.defineProperty(cue, 'startTime', extend({}, baseObj, {
get: function get() {
return _startTime;
},
set: function set(value) {
if (typeof value !== 'number') {
throw new TypeError('Start time must be set to a number.');
}
_startTime = value;
this.hasBeenReset = true;
}
}));
Object.defineProperty(cue, 'endTime', extend({}, baseObj, {
get: function get() {
return _endTime;
},
set: function set(value) {
if (typeof value !== 'number') {
throw new TypeError('End time must be set to a number.');
}
_endTime = value;
this.hasBeenReset = true;
}
}));
Object.defineProperty(cue, 'text', extend({}, baseObj, {
get: function get() {
return _text;
},
set: function set(value) {
_text = '' + value;
this.hasBeenReset = true;
}
})); // todo: implement VTTRegion polyfill?
Object.defineProperty(cue, 'region', extend({}, baseObj, {
get: function get() {
return _region;
},
set: function set(value) {
_region = value;
this.hasBeenReset = true;
}
}));
Object.defineProperty(cue, 'vertical', extend({}, baseObj, {
get: function get() {
return _vertical;
},
set: function set(value) {
var setting = findDirectionSetting(value); // Have to check for false because the setting an be an empty string.
if (setting === false) {
throw new SyntaxError('An invalid or illegal string was specified.');
}
_vertical = setting;
this.hasBeenReset = true;
}
}));
Object.defineProperty(cue, 'snapToLines', extend({}, baseObj, {
get: function get() {
return _snapToLines;
},
set: function set(value) {
_snapToLines = !!value;
this.hasBeenReset = true;
}
}));
Object.defineProperty(cue, 'line', extend({}, baseObj, {
get: function get() {
return _line;
},
set: function set(value) {
if (typeof value !== 'number' && value !== 'auto') {
throw new SyntaxError('An invalid number or illegal string was specified.');
}
_line = value;
this.hasBeenReset = true;
}
}));
Object.defineProperty(cue, 'lineAlign', extend({}, baseObj, {
get: function get() {
return _lineAlign;
},
set: function set(value) {
var setting = findAlignSetting(value);
if (!setting) {
throw new SyntaxError('An invalid or illegal string was specified.');
}
_lineAlign = setting;
this.hasBeenReset = true;
}
}));
Object.defineProperty(cue, 'position', extend({}, baseObj, {
get: function get() {
return _position;
},
set: function set(value) {
if (value < 0 || value > 100) {
throw new Error('Position must be between 0 and 100.');
}
_position = value;
this.hasBeenReset = true;
}
}));
Object.defineProperty(cue, 'positionAlign', extend({}, baseObj, {
get: function get() {
return _positionAlign;
},
set: function set(value) {
var setting = findAlignSetting(value);
if (!setting) {
throw new SyntaxError('An invalid or illegal string was specified.');
}
_positionAlign = setting;
this.hasBeenReset = true;
}
}));
Object.defineProperty(cue, 'size', extend({}, baseObj, {
get: function get() {
return _size;
},
set: function set(value) {
if (value < 0 || value > 100) {
throw new Error('Size must be between 0 and 100.');
}
_size = value;
this.hasBeenReset = true;
}
}));
Object.defineProperty(cue, 'align', extend({}, baseObj, {
get: function get() {
return _align;
},
set: function set(value) {
var setting = findAlignSetting(value);
if (!setting) {
throw new SyntaxError('An invalid or illegal string was specified.');
}
_align = setting;
this.hasBeenReset = true;
}
}));
/**
* Other <track> spec defined properties
*/
// http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#text-track-cue-display-state
cue.displayState = undefined;
}
/**
* VTTCue methods
*/
VTTCue.prototype.getCueAsHTML = function () {
// Assume WebVTT.convertCueToDOMTree is on the global.
var WebVTT = self.WebVTT;
return WebVTT.convertCueToDOMTree(self, this.text);
}; // this is a polyfill hack
return VTTCue;
})());
/***/ }),
/***/ "./src/utils/vttparser.ts":
/*!********************************!*\
!*** ./src/utils/vttparser.ts ***!
\********************************/
/*! exports provided: parseTimeStamp, fixLineBreaks, VTTParser */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseTimeStamp", function() { return parseTimeStamp; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "fixLineBreaks", function() { return fixLineBreaks; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VTTParser", function() { return VTTParser; });
/* harmony import */ var _vttcue__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./vttcue */ "./src/utils/vttcue.ts");
/*
* Source: https://github.com/mozilla/vtt.js/blob/master/dist/vtt.js
*/
var StringDecoder = /*#__PURE__*/function () {
function StringDecoder() {}
var _proto = StringDecoder.prototype;
// eslint-disable-next-line @typescript-eslint/no-unused-vars
_proto.decode = function decode(data, options) {
if (!data) {
return '';
}
if (typeof data !== 'string') {
throw new Error('Error - expected string data.');
}
return decodeURIComponent(encodeURIComponent(data));
};
return StringDecoder;
}(); // Try to parse input as a time stamp.
function parseTimeStamp(input) {
function computeSeconds(h, m, s, f) {
return (h | 0) * 3600 + (m | 0) * 60 + (s | 0) + parseFloat(f || 0);
}
var m = input.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);
if (!m) {
return null;
}
if (parseFloat(m[2]) > 59) {
// Timestamp takes the form of [hours]:[minutes].[milliseconds]
// First position is hours as it's over 59.
return computeSeconds(m[2], m[3], 0, m[4]);
} // Timestamp takes the form of [hours (optional)]:[minutes]:[seconds].[milliseconds]
return computeSeconds(m[1], m[2], m[3], m[4]);
} // A settings object holds key/value pairs and will ignore anything but the first
// assignment to a specific key.
var Settings = /*#__PURE__*/function () {
function Settings() {
this.values = Object.create(null);
}
var _proto2 = Settings.prototype;
// Only accept the first assignment to any key.
_proto2.set = function set(k, v) {
if (!this.get(k) && v !== '') {
this.values[k] = v;
}
} // Return the value for a key, or a default value.
// If 'defaultKey' is passed then 'dflt' is assumed to be an object with
// a number of possible default values as properties where 'defaultKey' is
// the key of the property that will be chosen; otherwise it's assumed to be
// a single value.
;
_proto2.get = function get(k, dflt, defaultKey) {
if (defaultKey) {
return this.has(k) ? this.values[k] : dflt[defaultKey];
}
return this.has(k) ? this.values[k] : dflt;
} // Check whether we have a value for a key.
;
_proto2.has = function has(k) {
return k in this.values;
} // Accept a setting if its one of the given alternatives.
;
_proto2.alt = function alt(k, v, a) {
for (var n = 0; n < a.length; ++n) {
if (v === a[n]) {
this.set(k, v);
break;
}
}
} // Accept a setting if its a valid (signed) integer.
;
_proto2.integer = function integer(k, v) {
if (/^-?\d+$/.test(v)) {
// integer
this.set(k, parseInt(v, 10));
}
} // Accept a setting if its a valid percentage.
;
_proto2.percent = function percent(k, v) {
if (/^([\d]{1,3})(\.[\d]*)?%$/.test(v)) {
var percent = parseFloat(v);
if (percent >= 0 && percent <= 100) {
this.set(k, percent);
return true;
}
}
return false;
};
return Settings;
}(); // Helper function to parse input into groups separated by 'groupDelim', and
// interpret each group as a key/value pair separated by 'keyValueDelim'.
function parseOptions(input, callback, keyValueDelim, groupDelim) {
var groups = groupDelim ? input.split(groupDelim) : [input];
for (var i in groups) {
if (typeof groups[i] !== 'string') {
continue;
}
var kv = groups[i].split(keyValueDelim);
if (kv.length !== 2) {
continue;
}
var _k = kv[0];
var _v = kv[1];
callback(_k, _v);
}
}
var defaults = new _vttcue__WEBPACK_IMPORTED_MODULE_0__["default"](0, 0, ''); // 'middle' was changed to 'center' in the spec: https://github.com/w3c/webvtt/pull/244
// Safari doesn't yet support this change, but FF and Chrome do.
var center = defaults.align === 'middle' ? 'middle' : 'center';
function parseCue(input, cue, regionList) {
// Remember the original input if we need to throw an error.
var oInput = input; // 4.1 WebVTT timestamp
function consumeTimeStamp() {
var ts = parseTimeStamp(input);
if (ts === null) {
throw new Error('Malformed timestamp: ' + oInput);
} // Remove time stamp from input.
input = input.replace(/^[^\sa-zA-Z-]+/, '');
return ts;
} // 4.4.2 WebVTT cue settings
function consumeCueSettings(input, cue) {
var settings = new Settings();
parseOptions(input, function (k, v) {
var vals;
switch (k) {
case 'region':
// Find the last region we parsed with the same region id.
for (var i = regionList.length - 1; i >= 0; i--) {
if (regionList[i].id === v) {
settings.set(k, regionList[i].region);
break;
}
}
break;
case 'vertical':
settings.alt(k, v, ['rl', 'lr']);
break;
case 'line':
vals = v.split(',');
settings.integer(k, vals[0]);
if (settings.percent(k, vals[0])) {
settings.set('snapToLines', false);
}
settings.alt(k, vals[0], ['auto']);
if (vals.length === 2) {
settings.alt('lineAlign', vals[1], ['start', center, 'end']);
}
break;
case 'position':
vals = v.split(',');
settings.percent(k, vals[0]);
if (vals.length === 2) {
settings.alt('positionAlign', vals[1], ['start', center, 'end', 'line-left', 'line-right', 'auto']);
}
break;
case 'size':
settings.percent(k, v);
break;
case 'align':
settings.alt(k, v, ['start', center, 'end', 'left', 'right']);
break;
}
}, /:/, /\s/); // Apply default values for any missing fields.
cue.region = settings.get('region', null);
cue.vertical = settings.get('vertical', '');
var line = settings.get('line', 'auto');
if (line === 'auto' && defaults.line === -1) {
// set numeric line number for Safari
line = -1;
}
cue.line = line;
cue.lineAlign = settings.get('lineAlign', 'start');
cue.snapToLines = settings.get('snapToLines', true);
cue.size = settings.get('size', 100);
cue.align = settings.get('align', center);
var position = settings.get('position', 'auto');
if (position === 'auto' && defaults.position === 50) {
// set numeric position for Safari
position = cue.align === 'start' || cue.align === 'left' ? 0 : cue.align === 'end' || cue.align === 'right' ? 100 : 50;
}
cue.position = position;
}
function skipWhitespace() {
input = input.replace(/^\s+/, '');
} // 4.1 WebVTT cue timings.
skipWhitespace();
cue.startTime = consumeTimeStamp(); // (1) collect cue start time
skipWhitespace();
if (input.substr(0, 3) !== '-->') {
// (3) next characters must match '-->'
throw new Error("Malformed time stamp (time stamps must be separated by '-->'): " + oInput);
}
input = input.substr(3);
skipWhitespace();
cue.endTime = consumeTimeStamp(); // (5) collect cue end time
// 4.1 WebVTT cue settings list.
skipWhitespace();
consumeCueSettings(input, cue);
}
function fixLineBreaks(input) {
return input.replace(/<br(?: \/)?>/gi, '\n');
}
var VTTParser = /*#__PURE__*/function () {
function VTTParser() {
this.state = 'INITIAL';
this.buffer = '';
this.decoder = new StringDecoder();
this.regionList = [];
this.cue = null;
this.oncue = void 0;
this.onparsingerror = void 0;
this.onflush = void 0;
}
var _proto3 = VTTParser.prototype;
_proto3.parse = function parse(data) {
var _this = this; // If there is no data then we won't decode it, but will just try to parse
// whatever is in buffer already. This may occur in circumstances, for
// example when flush() is called.
if (data) {
// Try to decode the data that we received.
_this.buffer += _this.decoder.decode(data, {
stream: true
});
}
function collectNextLine() {
var buffer = _this.buffer;
var pos = 0;
buffer = fixLineBreaks(buffer);
while (pos < buffer.length && buffer[pos] !== '\r' && buffer[pos] !== '\n') {
++pos;
}
var line = buffer.substr(0, pos); // Advance the buffer early in case we fail below.
if (buffer[pos] === '\r') {
++pos;
}
if (buffer[pos] === '\n') {
++pos;
}
_this.buffer = buffer.substr(pos);
return line;
} // 3.2 WebVTT metadata header syntax
function parseHeader(input) {
parseOptions(input, function (k, v) {// switch (k) {
// case 'region':
// 3.3 WebVTT region metadata header syntax
// console.log('parse region', v);
// parseRegion(v);
// break;
// }
}, /:/);
} // 5.1 WebVTT file parsing.
try {
var line = '';
if (_this.state === 'INITIAL') {
// We can't start parsing until we have the first line.
if (!/\r\n|\n/.test(_this.buffer)) {
return this;
}
line = collectNextLine(); // strip of UTF-8 BOM if any
// https://en.wikipedia.org/wiki/Byte_order_mark#UTF-8
var m = line.match(/^()?WEBVTT([ \t].*)?$/);
if (!m || !m[0]) {
throw new Error('Malformed WebVTT signature.');
}
_this.state = 'HEADER';
}
var alreadyCollectedLine = false;
while (_this.buffer) {
// We can't parse a line until we have the full line.
if (!/\r\n|\n/.test(_this.buffer)) {
return this;
}
if (!alreadyCollectedLine) {
line = collectNextLine();
} else {
alreadyCollectedLine = false;
}
switch (_this.state) {
case 'HEADER':
// 13-18 - Allow a header (metadata) under the WEBVTT line.
if (/:/.test(line)) {
parseHeader(line);
} else if (!line) {
// An empty line terminates the header and starts the body (cues).
_this.state = 'ID';
}
continue;
case 'NOTE':
// Ignore NOTE blocks.
if (!line) {
_this.state = 'ID';
}
continue;
case 'ID':
// Check for the start of NOTE blocks.
if (/^NOTE($|[ \t])/.test(line)) {
_this.state = 'NOTE';
break;
} // 19-29 - Allow any number of line terminators, then initialize new cue values.
if (!line) {
continue;
}
_this.cue = new _vttcue__WEBPACK_IMPORTED_MODULE_0__["default"](0, 0, '');
_this.state = 'CUE'; // 30-39 - Check if self line contains an optional identifier or timing data.
if (line.indexOf('-->') === -1) {
_this.cue.id = line;
continue;
}
// Process line as start of a cue.
/* falls through */
case 'CUE':
// 40 - Collect cue timings and settings.
if (!_this.cue) {
_this.state = 'BADCUE';
continue;
}
try {
parseCue(line, _this.cue, _this.regionList);
} catch (e) {
// In case of an error ignore rest of the cue.
_this.cue = null;
_this.state = 'BADCUE';
continue;
}
_this.state = 'CUETEXT';
continue;
case 'CUETEXT':
{
var hasSubstring = line.indexOf('-->') !== -1; // 34 - If we have an empty line then report the cue.
// 35 - If we have the special substring '-->' then report the cue,
// but do not collect the line as we need to process the current
// one as a new cue.
if (!line || hasSubstring && (alreadyCollectedLine = true)) {
// We are done parsing self cue.
if (_this.oncue && _this.cue) {
_this.oncue(_this.cue);
}
_this.cue = null;
_this.state = 'ID';
continue;
}
if (_this.cue === null) {
continue;
}
if (_this.cue.text) {
_this.cue.text += '\n';
}
_this.cue.text += line;
}
continue;
case 'BADCUE':
// 54-62 - Collect and discard the remaining cue.
if (!line) {
_this.state = 'ID';
}
}
}
} catch (e) {
// If we are currently parsing a cue, report what we have.
if (_this.state === 'CUETEXT' && _this.cue && _this.oncue) {
_this.oncue(_this.cue);
}
_this.cue = null; // Enter BADWEBVTT state if header was not parsed correctly otherwise
// another exception occurred so enter BADCUE state.
_this.state = _this.state === 'INITIAL' ? 'BADWEBVTT' : 'BADCUE';
}
return this;
};
_proto3.flush = function flush() {
var _this = this;
try {
// Finish decoding the stream.
// _this.buffer += _this.decoder.decode();
// Synthesize the end of the current cue or region.
if (_this.cue || _this.state === 'HEADER') {
_this.buffer += '\n\n';
_this.parse();
} // If we've flushed, parsed, and we're still on the INITIAL state then
// that means we don't have enough of the stream to parse the first
// line.
if (_this.state === 'INITIAL' || _this.state === 'BADWEBVTT') {
throw new Error('Malformed WebVTT signature.');
}
} catch (e) {
if (_this.onparsingerror) {
_this.onparsingerror(e);
}
}
if (_this.onflush) {
_this.onflush();
}
return this;
};
return VTTParser;
}();
/***/ }),
/***/ "./src/utils/webvtt-parser.ts":
/*!************************************!*\
!*** ./src/utils/webvtt-parser.ts ***!
\************************************/
/*! exports provided: generateCueId, parseWebVTT */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "generateCueId", function() { return generateCueId; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseWebVTT", function() { return parseWebVTT; });
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var _vttparser__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./vttparser */ "./src/utils/vttparser.ts");
/* harmony import */ var _demux_id3__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../demux/id3 */ "./src/demux/id3.ts");
/* harmony import */ var _timescale_conversion__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./timescale-conversion */ "./src/utils/timescale-conversion.ts");
/* harmony import */ var _remux_mp4_remuxer__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../remux/mp4-remuxer */ "./src/remux/mp4-remuxer.ts");
var LINEBREAKS = /\r\n|\n\r|\n|\r/g; // String.prototype.startsWith is not supported in IE11
var startsWith = function startsWith(inputString, searchString, position) {
if (position === void 0) {
position = 0;
}
return inputString.substr(position, searchString.length) === searchString;
};
var cueString2millis = function cueString2millis(timeString) {
var ts = parseInt(timeString.substr(-3));
var secs = parseInt(timeString.substr(-6, 2));
var mins = parseInt(timeString.substr(-9, 2));
var hours = timeString.length > 9 ? parseInt(timeString.substr(0, timeString.indexOf(':'))) : 0;
if (!Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(ts) || !Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(secs) || !Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(mins) || !Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(hours)) {
throw Error("Malformed X-TIMESTAMP-MAP: Local:" + timeString);
}
ts += 1000 * secs;
ts += 60 * 1000 * mins;
ts += 60 * 60 * 1000 * hours;
return ts;
}; // From https://github.com/darkskyapp/string-hash
var hash = function hash(text) {
var hash = 5381;
var i = text.length;
while (i) {
hash = hash * 33 ^ text.charCodeAt(--i);
}
return (hash >>> 0).toString();
}; // Create a unique hash id for a cue based on start/end times and text.
// This helps timeline-controller to avoid showing repeated captions.
function generateCueId(startTime, endTime, text) {
return hash(startTime.toString()) + hash(endTime.toString()) + hash(text);
}
var calculateOffset = function calculateOffset(vttCCs, cc, presentationTime) {
var currCC = vttCCs[cc];
var prevCC = vttCCs[currCC.prevCC]; // This is the first discontinuity or cues have been processed since the last discontinuity
// Offset = current discontinuity time
if (!prevCC || !prevCC.new && currCC.new) {
vttCCs.ccOffset = vttCCs.presentationOffset = currCC.start;
currCC.new = false;
return;
} // There have been discontinuities since cues were last parsed.
// Offset = time elapsed
while ((_prevCC = prevCC) !== null && _prevCC !== void 0 && _prevCC.new) {
var _prevCC;
vttCCs.ccOffset += currCC.start - prevCC.start;
currCC.new = false;
currCC = prevCC;
prevCC = vttCCs[currCC.prevCC];
}
vttCCs.presentationOffset = presentationTime;
};
function parseWebVTT(vttByteArray, initPTS, timescale, vttCCs, cc, timeOffset, callBack, errorCallBack) {
var parser = new _vttparser__WEBPACK_IMPORTED_MODULE_1__["VTTParser"](); // Convert byteArray into string, replacing any somewhat exotic linefeeds with "\n", then split on that character.
// Uint8Array.prototype.reduce is not implemented in IE11
var vttLines = Object(_demux_id3__WEBPACK_IMPORTED_MODULE_2__["utf8ArrayToStr"])(new Uint8Array(vttByteArray)).trim().replace(LINEBREAKS, '\n').split('\n');
var cues = [];
var initPTS90Hz = Object(_timescale_conversion__WEBPACK_IMPORTED_MODULE_3__["toMpegTsClockFromTimescale"])(initPTS, timescale);
var cueTime = '00:00.000';
var timestampMapMPEGTS = 0;
var timestampMapLOCAL = 0;
var parsingError;
var inHeader = true;
var timestampMap = false;
parser.oncue = function (cue) {
// Adjust cue timing; clamp cues to start no earlier than - and drop cues that don't end after - 0 on timeline.
var currCC = vttCCs[cc];
var cueOffset = vttCCs.ccOffset; // Calculate subtitle PTS offset
var webVttMpegTsMapOffset = (timestampMapMPEGTS - initPTS90Hz) / 90000; // Update offsets for new discontinuities
if (currCC !== null && currCC !== void 0 && currCC.new) {
if (timestampMapLOCAL !== undefined) {
// When local time is provided, offset = discontinuity start time - local time
cueOffset = vttCCs.ccOffset = currCC.start;
} else {
calculateOffset(vttCCs, cc, webVttMpegTsMapOffset);
}
}
if (webVttMpegTsMapOffset) {
// If we have MPEGTS, offset = presentation time + discontinuity offset
cueOffset = webVttMpegTsMapOffset - vttCCs.presentationOffset;
}
if (timestampMap) {
var duration = cue.endTime - cue.startTime;
var startTime = Object(_remux_mp4_remuxer__WEBPACK_IMPORTED_MODULE_4__["normalizePts"])((cue.startTime + cueOffset - timestampMapLOCAL) * 90000, timeOffset * 90000) / 90000;
cue.startTime = startTime;
cue.endTime = startTime + duration;
} //trim trailing webvtt block whitespaces
var text = cue.text.trim(); // Fix encoding of special characters
cue.text = decodeURIComponent(encodeURIComponent(text)); // If the cue was not assigned an id from the VTT file (line above the content), create one.
if (!cue.id) {
cue.id = generateCueId(cue.startTime, cue.endTime, text);
}
if (cue.endTime > 0) {
cues.push(cue);
}
};
parser.onparsingerror = function (error) {
parsingError = error;
};
parser.onflush = function () {
if (parsingError && errorCallBack) {
errorCallBack(parsingError);
return;
}
callBack(cues);
}; // Go through contents line by line.
vttLines.forEach(function (line) {
if (inHeader) {
// Look for X-TIMESTAMP-MAP in header.
if (startsWith(line, 'X-TIMESTAMP-MAP=')) {
// Once found, no more are allowed anyway, so stop searching.
inHeader = false;
timestampMap = true; // Extract LOCAL and MPEGTS.
line.substr(16).split(',').forEach(function (timestamp) {
if (startsWith(timestamp, 'LOCAL:')) {
cueTime = timestamp.substr(6);
} else if (startsWith(timestamp, 'MPEGTS:')) {
timestampMapMPEGTS = parseInt(timestamp.substr(7));
}
});
try {
// Convert cue time to seconds
timestampMapLOCAL = cueString2millis(cueTime) / 1000;
} catch (error) {
timestampMap = false;
parsingError = error;
} // Return without parsing X-TIMESTAMP-MAP line.
return;
} else if (line === '') {
inHeader = false;
}
} // Parse line by default.
parser.parse(line + '\n');
});
parser.flush();
}
/***/ }),
/***/ "./src/utils/xhr-loader.ts":
/*!*********************************!*\
!*** ./src/utils/xhr-loader.ts ***!
\*********************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/* harmony import */ var _loader_load_stats__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../loader/load-stats */ "./src/loader/load-stats.ts");
var XhrLoader = /*#__PURE__*/function () {
function XhrLoader(config
/* HlsConfig */
) {
this.xhrSetup = void 0;
this.requestTimeout = void 0;
this.retryTimeout = void 0;
this.retryDelay = void 0;
this.config = null;
this.callbacks = null;
this.context = void 0;
this.loader = null;
this.stats = void 0;
this.xhrSetup = config ? config.xhrSetup : null;
this.stats = new _loader_load_stats__WEBPACK_IMPORTED_MODULE_1__["LoadStats"]();
this.retryDelay = 0;
}
var _proto = XhrLoader.prototype;
_proto.destroy = function destroy() {
this.callbacks = null;
this.abortInternal();
this.loader = null;
this.config = null;
};
_proto.abortInternal = function abortInternal() {
var loader = this.loader;
self.clearTimeout(this.requestTimeout);
self.clearTimeout(this.retryTimeout);
if (loader) {
loader.onreadystatechange = null;
loader.onprogress = null;
if (loader.readyState !== 4) {
this.stats.aborted = true;
loader.abort();
}
}
};
_proto.abort = function abort() {
var _this$callbacks;
this.abortInternal();
if ((_this$callbacks = this.callbacks) !== null && _this$callbacks !== void 0 && _this$callbacks.onAbort) {
this.callbacks.onAbort(this.stats, this.context, this.loader);
}
};
_proto.load = function load(context, config, callbacks) {
if (this.stats.loading.start) {
throw new Error('Loader can only be used once.');
}
this.stats.loading.start = self.performance.now();
this.context = context;
this.config = config;
this.callbacks = callbacks;
this.retryDelay = config.retryDelay;
this.loadInternal();
};
_proto.loadInternal = function loadInternal() {
var config = this.config,
context = this.context;
if (!config) {
return;
}
var xhr = this.loader = new self.XMLHttpRequest();
var stats = this.stats;
stats.loading.first = 0;
stats.loaded = 0;
var xhrSetup = this.xhrSetup;
try {
if (xhrSetup) {
try {
xhrSetup(xhr, context.url);
} catch (e) {
// fix xhrSetup: (xhr, url) => {xhr.setRequestHeader("Content-Language", "test");}
// not working, as xhr.setRequestHeader expects xhr.readyState === OPEN
xhr.open('GET', context.url, true);
xhrSetup(xhr, context.url);
}
}
if (!xhr.readyState) {
xhr.open('GET', context.url, true);
}
} catch (e) {
// IE11 throws an exception on xhr.open if attempting to access an HTTP resource over HTTPS
this.callbacks.onError({
code: xhr.status,
text: e.message
}, context, xhr);
return;
}
if (context.rangeEnd) {
xhr.setRequestHeader('Range', 'bytes=' + context.rangeStart + '-' + (context.rangeEnd - 1));
}
xhr.onreadystatechange = this.readystatechange.bind(this);
xhr.onprogress = this.loadprogress.bind(this);
xhr.responseType = context.responseType; // setup timeout before we perform request
self.clearTimeout(this.requestTimeout);
this.requestTimeout = self.setTimeout(this.loadtimeout.bind(this), config.timeout);
xhr.send();
};
_proto.readystatechange = function readystatechange() {
var context = this.context,
xhr = this.loader,
stats = this.stats;
if (!context || !xhr) {
return;
}
var readyState = xhr.readyState;
var config = this.config; // don't proceed if xhr has been aborted
if (stats.aborted) {
return;
} // >= HEADERS_RECEIVED
if (readyState >= 2) {
// clear xhr timeout and rearm it if readyState less than 4
self.clearTimeout(this.requestTimeout);
if (stats.loading.first === 0) {
stats.loading.first = Math.max(self.performance.now(), stats.loading.start);
}
if (readyState === 4) {
xhr.onreadystatechange = null;
xhr.onprogress = null;
var status = xhr.status; // http status between 200 to 299 are all successful
if (status >= 200 && status < 300) {
stats.loading.end = Math.max(self.performance.now(), stats.loading.first);
var data;
var len;
if (context.responseType === 'arraybuffer') {
data = xhr.response;
len = data.byteLength;
} else {
data = xhr.responseText;
len = data.length;
}
stats.loaded = stats.total = len;
if (!this.callbacks) {
return;
}
var onProgress = this.callbacks.onProgress;
if (onProgress) {
onProgress(stats, context, data, xhr);
}
if (!this.callbacks) {
return;
}
var response = {
url: xhr.responseURL,
data: data
};
this.callbacks.onSuccess(response, stats, context, xhr);
} else {
// if max nb of retries reached or if http status between 400 and 499 (such error cannot be recovered, retrying is useless), return error
if (stats.retry >= config.maxRetry || status >= 400 && status < 499) {
_utils_logger__WEBPACK_IMPORTED_MODULE_0__["logger"].error(status + " while loading " + context.url);
this.callbacks.onError({
code: status,
text: xhr.statusText
}, context, xhr);
} else {
// retry
_utils_logger__WEBPACK_IMPORTED_MODULE_0__["logger"].warn(status + " while loading " + context.url + ", retrying in " + this.retryDelay + "..."); // abort and reset internal state
this.abortInternal();
this.loader = null; // schedule retry
self.clearTimeout(this.retryTimeout);
this.retryTimeout = self.setTimeout(this.loadInternal.bind(this), this.retryDelay); // set exponential backoff
this.retryDelay = Math.min(2 * this.retryDelay, config.maxRetryDelay);
stats.retry++;
}
}
} else {
// readyState >= 2 AND readyState !==4 (readyState = HEADERS_RECEIVED || LOADING) rearm timeout as xhr not finished yet
self.clearTimeout(this.requestTimeout);
this.requestTimeout = self.setTimeout(this.loadtimeout.bind(this), config.timeout);
}
}
};
_proto.loadtimeout = function loadtimeout() {
_utils_logger__WEBPACK_IMPORTED_MODULE_0__["logger"].warn("timeout while loading " + this.context.url);
var callbacks = this.callbacks;
if (callbacks) {
this.abortInternal();
callbacks.onTimeout(this.stats, this.context, this.loader);
}
};
_proto.loadprogress = function loadprogress(event) {
var stats = this.stats;
stats.loaded = event.loaded;
if (event.lengthComputable) {
stats.total = event.total;
}
};
_proto.getResponseHeader = function getResponseHeader(name) {
if (this.loader) {
try {
return this.loader.getResponseHeader(name);
} catch (error) {
/* Could not get headers */
}
}
return null;
};
return XhrLoader;
}();
/* harmony default export */ __webpack_exports__["default"] = (XhrLoader);
/***/ })
/******/ })["default"];
});
//# sourceMappingURL=hls.js.map |
// GLOBAL VARIABLES
var quizQuestions = []; //populated with JSON object that includes the questions and answers for the qset to be quizzed on
var quizAllIndex = 0; //counts how many questions have been already quizzed and allows modal to close when you reach end of quizQuestions array
function initQsets() {
$('#qsets').on('change', function(event) {
var $selectedOption = $(this.options[this.selectedIndex]);
window.open($selectedOption.data('qset-url'), '_self');
});
$('.modal').on('shown.bs.modal', function (event) {
$(this).find('input:text:visible:first').focus().select();
});
$('#modal-new-qset').on('show.bs.modal', function (event) {
$(this).find('input[name="name"]').val('');
$(this).find('input[value="questions"]').prop('checked', true);
$(this).find('input[value="subsets"]').prop('checked', false);
$(this).find('input[value="mixed"]').prop('checked', false);
});
$('#modal-edit-qset').on('show.bs.modal', function (event) {
$('#delete_confirmation_form_container').hide();
});
// todo: do we need this anymore? can it be a trashcan icon at the main page, and simplify editing?
$('#edit-qset-delete').on('click', function (event) {
$('#delete_confirmation_form_container').show();
});
$('form').on('submit', function (event) {
$('.modal :button').prop('disabled', true);
});
}
function initQuestionDisplayModalForQuizAll() {
// Creates the initial view of the modal.
var $modal = $('#question_display_Modal');
// The submit answer button is shown as well as an empty text input box.
$('.submit-answer').show();
// The answer is initially hidden and so is the response.
$('.answer-text').val('');
$('.response, .answers').hide();
initAnswerButton();
initUserFeedbackQuizAll();
$modal.find('.modal-title').text(quizQuestions[quizAllIndex].text);
$modal.find('.first-answer').text(quizQuestions[quizAllIndex].answers[0].text);
}
function initDataForQuizAll() {
$('.feedback-alert').hide();
var qset_id = $('#qset-show-container').data('qset-id');
questionJSON(qset_id);
}
function initQuestionFilter() {
var noQuestionsMessage = {
'all': 'There are no questions.',
'mine': 'You have not created any questions.',
'other': 'No other users have created any questions.'
};
var qsetId = $('#qset-show-container').data('qset-id');
// recalls preferred filter option
filterBy(Cookies.get('all_mine_other_filter') || 'all');
// changes to filter 1. show filtered set of questions, and 2. are tracked in a user cookie
$('.filter-choice').click(function(){
var filterType = $(this).find('input')[0].getAttribute('name'); // radio button 'name' value
filterBy(filterType);
Cookies.set('all_mine_other_filter', filterType, { expires: 1000 });
});
function anyQuestions(filterType) {
// expecting filterType == 'all', 'mine', or 'other'
switch (filterType) {
case 'mine':
return ($('.my-question').length > 0);
case 'other':
return ($('.other-question').length > 0);
default: // 'all' or invalid filterType
return ($('.my-question, .other-question').length > 0);
}
}
function filterBy(filterType) {
// expecting filterType == 'all', 'mine', or 'other'
var anyQuestionsToDisplay = anyQuestions(filterType);
if (!anyQuestionsToDisplay) showNoQuestionNotification(noQuestionsMessage[filterType]);
$('.quiz-all').attr('disabled', !anyQuestionsToDisplay);
$('.no-questions').toggleClass('hidden', anyQuestionsToDisplay);
$('.my-question').toggleClass('hidden', filterType == 'other' || !anyQuestionsToDisplay);
$('.other-question').toggleClass('hidden', filterType == 'mine' || !anyQuestionsToDisplay);
}
function showNoQuestionNotification(msg) {
var noQuestionsNotification = msg + ' <a href="/questions/new?qset=' + qsetId + '">Create one now!</a>';
$('.no-questions > p').html(noQuestionsNotification);
}
}
function questionJSON(qsetid) {
$.getJSON("/qsets/" + qsetid, {filter: Cookies.get('all_mine_other_filter')}, function(data) {
quizQuestions = data;
initQuestionDisplayModalForQuizAll();
});
}
|
import createSvgIcon from './utils/createSvgIcon';
import { jsx as _jsx } from "react/jsx-runtime";
export default createSvgIcon( /*#__PURE__*/_jsx("path", {
d: "M19.71 9.71 22 12V6h-6l2.29 2.29-4.17 4.17c-.39.39-1.02.39-1.41 0l-1.17-1.17c-1.17-1.17-3.07-1.17-4.24 0L2 16.59 3.41 18l5.29-5.29c.39-.39 1.02-.39 1.41 0l1.17 1.17c1.17 1.17 3.07 1.17 4.24 0l4.19-4.17z"
}), 'Moving'); |
$(document).ready(function () {
// Detect IE (uses jquery.browser plugin), and add a class to the body element so we can write
// IE-specific CSS if needed.
if ($.browser.msie) {
$("body").addClass("ie");
}
// Move sidebar content up when header is scrolled out of view
var updateSidebarTop = function updateSidebarTop () {
var navHeight = $('#nav').height();
if ($(this).scrollTop() > navHeight) {
$('#sidebar').removeClass("top");
} else {
$('#sidebar').addClass('top');
}
};
updateSidebarTop(); // Call it when page gets loaded...
$(document).scroll(updateSidebarTop); // ... and also whenever the window is scrolled.
});
|
if(typeof exports === 'object') {
var assert = require("assert");
var alasql = require('..');
} else {
__dirname = '.';
};
if(typeof exports == 'object') {
describe('Test 262 Leaking of "key" variable to global scope', function() {
it('1. Sqllogic', function(done) {
mytable = [ { name: 'Hello' }, { name: 'Wolrd' } ];
assert(typeof global.key == 'undefined'); // undefined
// To catch
if(false) {
Object.defineProperty(global, 'key', {
get: function(){ assert(false); },
set: function(newValue){ assert(false); }
});
}
alasql('SELECT * FROM ?', [mytable]);
assert(typeof global.key == 'undefined'); // undefined
done();
});
});
}
|
GS.EntityTools = function(mapManager, actionLog, inCanvas) {
GS.LayerObjectTools.call(this, mapManager, actionLog, inCanvas);
this.layer = GS.MapLayers.Entity;
this.mousePressed = false;
this.defaultEntity = Object.keys(GS.MapEntities)[0];
this.entity = this.defaultEntity;
};
GS.EntityTools.prototype = GS.inherit(GS.LayerObjectTools, {
constructor: GS.EntityTools,
init: function() {
},
initMenuControls: function() {
var that = this;
var $nttTypeSelect = $("#ntt-type-select");
Object.keys(GS.MapEntities).forEach(function(key) {
if (key == that.defaultEntity) {
$nttTypeSelect.append("<option value='" + key +"' selected>" + GS.MapEntities[key].name + "</option>");
} else {
$nttTypeSelect.append("<option value='" + key +"'>" + GS.MapEntities[key].name + "</option>");
}
});
$nttTypeSelect.on("change", function() {
that.entity = $(this).find(":selected").val();
});
$("#button-compute-ntt-y").click(function() {
that.mapManager.computeYForEntities(that.selected);
});
this.linkCountChangeToField($("#ntt-count"));
},
update: function() {
if (!GS.InputHelper.leftMouseDown) {
this.mousePressed = false;
}
var mx = GS.InputHelper.mouseX;
var my = GS.InputHelper.mouseY;
switch (this.mode) {
case GS.EditorModes.Selecting:
this.handleSelecting(mx, my);
break;
case GS.EditorModes.Drawing:
this.handleDrawing(mx, my);
break;
}
},
handleDrawing: function(mx, my) {
var v = new THREE.Vector2(mx, my);
this.mapManager.convertToGridCellCoords(v);
this.mapManager.drawEntity({ pos: v, type: this.entity });
if (GS.InputHelper.leftMouseDown && !this.mousePressed) {
if (this.inCanvas(mx, my)) {
var containsEntity = this.mapManager.isEntityAt(v);
if (!containsEntity) {
var ntt = this.mapManager.constructLayerObject(this.layer, { pos: v, type: this.entity, rotation: 0 });
this.mapManager.addLayerObject(this.layer, ntt);
this.actionLog.push(this.getAddAction(ntt.id));
}
this.mousePressed = true;
}
}
this.mapManager.drawCursor(v);
},
selectionChange: function() {
var that = this;
var $detail = $("#ntt-tools-detail");
var count = Object.keys(this.selected).length;
var selected = [];
Object.keys(this.selected).forEach(function(key) {
selected.push(that.mapManager.getLayerObject(GS.MapLayers.Entity, key));
});
if (count > 0) {
var ntt;
var $txtId = $("#ntt-selected-id");
var $txtY = $("#ntt-selected-y");
var $txtRotation = $("#ntt-selected-rotation");
var $chkStatic = $("#chk-ntt-selected-static");
if (count == 1) {
ntt = selected[0];
var isStatic = (ntt.isStatic !== undefined) ? ntt.isStatic : false;
var showRotation = (GS.MapEntities[ntt.type].type === "Monster");
$txtId.text(ntt.id);
$txtY.val(ntt.y || 0);
$txtRotation.val(ntt.rotation || 0);
$txtRotation.prop("disabled", !showRotation);
$chkStatic.prop("checked", isStatic);
} else {
$txtId.text("multiple");
$txtY.val("");
$txtRotation.val("");
$txtRotation.prop("disabled", false);
$chkStatic.prop("checked", false);
}
$txtY.off("change.detail");
$txtY.on("change.detail", function() {
var n = parseInt($(this).val());
for (var i = 0; i < selected.length; i++) {
selected[i].y = isNaN(n) ? 0 : n;
}
});
$txtRotation.off("change.detail");
$txtRotation.on("change.detail", function() {
var n = parseInt($(this).val());
if (isNaN(n)) {
n = 0;
}
n = n % 360;
for (var i = 0; i < selected.length; i++) {
selected[i].rotation = n;
}
$txtRotation.val(n);
});
$chkStatic.off("change.detail");
$chkStatic.on("change.detail", function() {
var value = $(this).is(":checked");
for (var i = 0; i < selected.length; i++) {
selected[i].isStatic = value;
}
});
$detail.show();
} else {
$detail.hide();
}
},
}); |
version https://git-lfs.github.com/spec/v1
oid sha256:6abba8f898329bd32d1741da266f8f6320718dd260dca3a812722c75384d9fdd
size 70945
|
// Generated by CoffeeScript 1.6.2
(function() {
$(function() {
//$('body').chardinJs();
$('a[data-toggle="chardinjs"]').on('click', function(e) {
e.preventDefault();
if ($('.jumbotron img').is(':visible')) {
return ($('body').data('chardinJs')).toggle();
} else {
return $('.jumbotron img').animate({
height: 250
}, 600, function() {
return ($('body').data('chardinJs')).toggle();
});
}
});
return $('body').on('chardinJs:stop', function() {
$('a.btn.primary').off('click').text('See more on Github').attr('href', 'https://github.com/heelhook/chardin.js');
return $('a#opentour').css({
display: 'block'
});
});
});
}).call(this);
|
/* */
exports.name = "tests/home";
|
var should = require('chai').should(); // eslint-disable-line
describe('Excerpt', () => {
var Hexo = require('../../../lib/hexo');
var hexo = new Hexo();
var excerpt = require('../../../lib/plugins/filter/after_post_render/excerpt').bind(hexo);
it('without <!-- more -->', () => {
var content = [
'foo',
'bar',
'baz'
].join('\n');
var data = {
content
};
excerpt(data);
data.content.should.eql(content);
data.excerpt.should.eql('');
data.more.should.eql(content);
});
it('with <!-- more -->', () => {
_moreCases().forEach(_test);
function _moreCases() {
var template = '<!--{{lead}}more{{tail}}-->';
// see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#Special_characters_meaning_in_regular_expressions
var spaces = ' \f\n\r\t\v\u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000\ufeff';
var cases = [];
var more;
var lead;
var tail;
var s;
var e;
for (var i = 0; i < spaces.length; ++i) {
lead = spaces[i];
for (var k = 0; k < spaces.length; ++k) {
tail = spaces[k];
s = '';
for (var m = 0; m < 3; ++m) {
e = '';
for (var n = 0; n < 3; ++n) {
more = template.replace('{{lead}}', s).replace('{{tail}}', e);
cases.push(more);
e += tail;
}
s += lead;
}
}
}
return cases;
}
function _test(more) {
var content = [
'foo',
'bar',
more,
'baz'
].join('\n');
var data = {
content
};
excerpt(data);
data.content.should.eql([
'foo',
'bar',
'<a id="more"></a>',
'baz'
].join('\n'));
data.excerpt.should.eql([
'foo',
'bar'
].join('\n'));
data.more.should.eql([
'baz'
].join('\n'));
}
});
it('multiple <!-- more -->', () => {
var content = [
'foo',
'<!-- more -->',
'bar',
'<!-- more -->',
'baz'
].join('\n');
var data = {
content
};
excerpt(data);
data.content.should.eql([
'foo',
'<a id="more"></a>',
'bar',
'<!-- more -->',
'baz'
].join('\n'));
data.excerpt.should.eql([
'foo'
].join('\n'));
data.more.should.eql([
'bar',
'<!-- more -->',
'baz'
].join('\n'));
});
});
|
const PlotCard = require('../../plotcard.js');
class Confiscation extends PlotCard {
setupCardAbilities() {
this.whenRevealed({
target: {
activePromptTitle: 'Select an attachment',
cardCondition: card => this.cardCondition(card)
},
handler: context => {
var attachment = context.target;
attachment.owner.discardCard(attachment);
this.game.addMessage('{0} uses {1} to discard {2}', context.player, this, attachment);
}
});
}
cardCondition(card) {
return card.location === 'play area' && card.getType() === 'attachment';
}
}
Confiscation.code = '01009';
module.exports = Confiscation;
|
/**
* levels
* ======
*
* Технология переехала в пакет `enb-bem-techs`.
*/
var Level = require('../lib/levels/level');
var Levels = require('../lib/levels/levels');
var Vow = require('vow');
var VowFs = require('../lib/fs/async-fs');
var inherit = require('inherit');
var path = require('path');
module.exports = inherit(require('../lib/tech/base-tech'), {
getName: function () {
return 'levels';
},
init: function () {
this.__base.apply(this, arguments);
this._levelConfig = this.getRequiredOption('levels');
this._sublevelDirectories = this.getOption('sublevelDirectories', ['blocks']);
this._target = this.node.unmaskTargetName(this.getOption('target', '?.levels'));
},
getTargets: function () {
return [this._target];
},
build: function () {
var _this = this;
var target = this._target;
var levelList = [];
var levelsToCache = [];
var levelsIndex = {};
var cache = this.node.getNodeCache(target);
var logger = this.node.getLogger();
logger.logTechIsDeprecated(this._target, this.getName(),
'enb', 'levels', 'enb-bem-techs');
for (var i = 0, l = this._levelConfig.length; i < l; i++) {
var levelInfo = this._levelConfig[i];
levelInfo = typeof levelInfo === 'object' ? levelInfo : {path: levelInfo};
var levelPath = levelInfo.path;
var levelKey = 'level:' + levelPath;
if (levelsIndex[levelPath]) {
continue;
}
levelsIndex[levelPath] = true;
if (!this.node.buildState[levelKey]) {
var level = new Level(levelPath, this.node.getLevelNamingScheme(levelPath));
if (levelInfo.check === false) {
var blocks = cache.get(levelPath);
if (blocks) {
level.loadFromCache(blocks);
} else {
levelsToCache.push(level);
}
}
this.node.buildState[levelKey] = level;
}
levelList.push(this.node.buildState[levelKey]);
}
return VowFs.listDir(path.join(_this.node.getRootDir(), _this.node.getPath()))
.then(function (listDir) {
return _this._sublevelDirectories.filter(function (path) {
return listDir.indexOf(path) !== -1;
});
})
.then(function (sublevels) {
return Vow.all(sublevels.map(function (path) {
var sublevelPath = _this.node.resolvePath(path);
if (!levelsIndex[sublevelPath]) {
levelsIndex[sublevelPath] = true;
levelList.push(new Level(sublevelPath, _this.node.getLevelNamingScheme(sublevelPath)));
}
}));
})
.then(function () {
return Vow.all(levelList.map(function (level) {
return level.load();
}))
.then(function () {
levelsToCache.forEach(function (level) {
cache.set(level.getPath(), level.getBlocks());
});
_this.node.resolveTarget(target, new Levels(levelList));
});
});
},
clean: function () {}
});
|
define(['./_baseFindIndex', './_baseIteratee', './toInteger'], function(baseFindIndex, baseIteratee, toInteger) {
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* This method is like `_.find` except that it returns the index of the first
* element `predicate` returns truthy for instead of the element itself.
*
* @static
* @memberOf _
* @since 1.1.0
* @category Array
* @param {Array} array The array to inspect.
* @param {Function} [predicate=_.identity]
* The function invoked per iteration.
* @param {number} [fromIndex=0] The index to search from.
* @returns {number} Returns the index of the found element, else `-1`.
* @example
*
* var users = [
* { 'user': 'barney', 'active': false },
* { 'user': 'fred', 'active': false },
* { 'user': 'pebbles', 'active': true }
* ];
*
* _.findIndex(users, function(o) { return o.user == 'barney'; });
* // => 0
*
* // The `_.matches` iteratee shorthand.
* _.findIndex(users, { 'user': 'fred', 'active': false });
* // => 1
*
* // The `_.matchesProperty` iteratee shorthand.
* _.findIndex(users, ['active', false]);
* // => 0
*
* // The `_.property` iteratee shorthand.
* _.findIndex(users, 'active');
* // => 2
*/
function findIndex(array, predicate, fromIndex) {
var length = array ? array.length : 0;
if (!length) {
return -1;
}
var index = fromIndex == null ? 0 : toInteger(fromIndex);
if (index < 0) {
index = nativeMax(length + index, 0);
}
return baseFindIndex(array, baseIteratee(predicate, 3), index);
}
return findIndex;
});
|
config = require('./lib/config');
var dashboard = require('./lib/dashboard');
var tracker = require('./lib/tracker');
var demo = require('./lib/demo');
// Setup dashboard port listener
dashboard.listen(config.dashboard_port, config.dashboard_address);
console.log("Dashboard listening on http://" + (config.dashboard_address || "*") + ":" + config.dashboard_port + ".");
// Setup tracker port listener...
if (typeof config.tracking_port != 'number') {
// Tracker should listen on the same port as the dashboard
tracker.listen(dashboard);
} else {
// Tracker should listen on specified port
tracker.listen(config.tracking_port, config.tracking_address);
}
console.log("Tracker listening on http://" + (config.tracking_address || "*") + ":" + (config.tracking_port || config.dashboard_port) + "/tracking_pixel.gif.");
// Setup UDP tracking
if (typeof config.udp_tracking_port == 'number') {
tracker.listenUdp((config.udp_tracking_port || 8000), (config.udp_tracking_address || "0.0.0.0"));
}
// Run in demo mode
if (config.demo_mode) {
demo.run(tracker);
}
|
// Generated by CoffeeScript 1.6.3
(function() {
var attached_live;
attached_live = false;
window.summarize = function(elements, options) {
var handler;
options = $.extend({
summary_length: 150,
more_text: 'more'
}, options);
$(elements).each(function() {
var $el, text;
$el = $(this);
text = $.trim($el.text());
$el.data('full-text', text);
if (text.length > options.summary_length) {
text = text.slice(0, options.summary_length) + '... ';
$el.text(text);
return $el.append(format('(<a href="#read-more" class="read-more">{{ text }}</a>)', {
text: options.more_text
}));
}
});
if (!attached_live) {
handler = function() {
var parent, text;
parent = $(this).parent();
text = parent.data('full-text');
parent.text(text);
return false;
};
$(elements).data('summarize-click-handler', handler);
$('.read-more').live('click', handler);
return attached_live = true;
}
};
}).call(this);
|
import combineReducers from 'redux/lib/combineReducers';
import defaultState from './defaultState';
function deviceSpec(oState = defaultState.deviceSpec, action) {
switch (action.type) {
case 'UPDATE_WINDOW_SIZE':
return action.deviceSpec;
default:
return oState;
}
}
function playerState(oState = defaultState.playerState, action) {
switch (action.type) {
case 'UPDATE_PLAYER_STATE':
return action.playerState;
default:
return oState;
}
}
export default combineReducers({ deviceSpec, playerState });
|
class C {
#x = 1;
#p = ({ #x: x })
}
|
var ProbeManager = require('../server/probe_manager');
var probeManager = new ProbeManager();
var config = {
baudRate: 38400,
mode: 'mitm',
upstream: '/dev/ttyO2',
downstream: '/dev/ttyO1'
}
probeManager.setOptions({
baudRate: config.baudRate,
mode: config.mode
})
probeManager.openProbe(config.upstream, 'upstream', function(err, upstream) {
if (err) throw err;
console.log(upstream.name, 'opened as upstream');
probeManager.openProbe(config.downstream, 'downstream', function(err, downstream) {
if (err) throw err;
console.log(downstream.name, 'opened as downstream');
probeManager.createMitmSession('', function(err, session){
if (err) throw err;
session.start();
console.log('started mitm session');
});
})
})
|
define(["app/app"], function(App) {
"use strict";
App.Attachment = DS.Model.extend({
file: DS.attr('file'), // FormData File object
url: DS.attr('string'),
thumbnailUrl: DS.attr('string'),
fileName: DS.attr('string'),
fileSize: DS.attr('number'),
mediaType: DS.attr('string'),
title: DS.attr('string'),
artist: DS.attr('string'),
createdAt: DS.attr('string'),
updatedAt: DS.attr('string'),
createdBy: DS.belongsTo('user'),
post: DS.belongsTo('post'),
isImage: function() {
return this.get('mediaType') === 'image' ||
Ember.isEmpty(this.get('mediaType'))
}.property('mediaType'),
isGeneral: function() {
return this.get('mediaType') === 'general'
}.property('mediaType'),
isAudio: function() {
return this.get('mediaType') === 'audio'
}.property('mediaType')
})
})
|
/**
* Created by xmc1993 on 2016/12/11.
*
* 云服务模块
*
*/
|
define([
'jquery',
'underscore',
'backbone',
'app',
'simplemde',
'text!templates/projects/projectTemplate.html'
], function($, _, Backbone, app, SimpleMDE, projectTemplate) {
var ProjectView = Backbone.View.extend({
el: $("#page"),
events: {
'click #project-btn': 'save'
},
initialize: function(options) {
_.bindAll(this, 'render', 'save');
this.collection = options.collection;
this.projectId = options.projectId;
},
render: function() {
$('.item').removeClass('active');
$('.item a[href="#/projects"]').parent().addClass('active');
var self = this;
var project = this.collection.get(this.projectId);
var data = {
project: project,
_: _
};
var compiledTemplate = _.template(projectTemplate, data);
self.$el.html(compiledTemplate);
var simplemde = new SimpleMDE({
autoDownloadFontAwesome: true,
autofocus: false,
autosave: {
enabled: false
},
element: $('#project-description-input')[0],
indentWithTabs: false,
spellChecker: false,
tabSize: 4
});
this.delegateEvents();
},
save: function(event) {
if (this.$("#project-form").parsley().validate()) {
var self = this;
var project = this.collection.get(this.projectId);
project.save({
name: this.$("#project-name-input").val(),
description: this.$("#project-description-input").val(),
}, {
success: function(mod, res) {
app.showAlert('Success!', 'Project ' + this.$("#project-name-input").val() + ' updated!', 'success')
Backbone.history.history.back();
},
error: function(model, response, options) {
var message = _.has(response, 'statusText') ? response.statusText : 'Unknown error!';
if (
_.has(response, 'responseJSON') &&
_.has(response.responseJSON, 'name') &&
_.has(response.responseJSON.name, 'length') &&
response.responseJSON.name.length > 0
) {
message = response.responseJSON.name[0];
}
app.showAlert('Failed to update Project', message, 'error');
}
});
} else {
if (typeof DEBUG != 'undefined' && DEBUG) console.log("Did not pass clientside validation");
}
}
});
return ProjectView;
}); |
(function() {
var checkVersion = Dagaz.Model.checkVersion;
Dagaz.Model.checkVersion = function(design, name, value) {
if (name != "chaturaji-promotion") {
checkVersion(design, name, value);
}
}
var getType = function(design, board, player, pos) {
var r = null;
if (design.inZone(3, player, pos)) r = 6;
if (design.inZone(4, player, pos)) r = 7;
if (design.inZone(5, player, pos)) r = 8;
if (design.inZone(6, player, pos)) r = 4;
if (r !== null) {
_.each(design.allPositions(), function(p) {
var piece = board.getPiece(p);
if (piece === null) return;
if (piece.player != player) return;
if (piece.type != r) return;
r = null;
});
}
return r;
}
var CheckInvariants = Dagaz.Model.CheckInvariants;
Dagaz.Model.CheckInvariants = function(board) {
var design = Dagaz.Model.design;
_.each(board.moves, function(move) {
if (move.mode != 5) return;
var pos = move.actions[0][0][0];
var piece = board.getPiece(pos);
if (piece === null) return;
if (piece.type != 5) return;
pos = move.actions[0][1][0];
if (!design.inZone(0, board.player, pos)) return;
var type = getType(design, board, board.player, pos);
if (type === null) return;
move.actions[0][2] = [ piece.promote(type) ];
});
_.each(design.allPositions(), function(pos) {
var piece = board.getPiece(pos);
if (piece === null) return;
if (piece.player != board.player) return;
if (piece.type != 5) return;
if (!design.inZone(0, piece.player, pos)) return;
var type = getType(design, board, board.player, pos);
if (type !== null) {
var move = Dagaz.Model.createMove(5);
// move.mode = 1;
move.movePiece(pos, pos, piece.promote(type));
board.moves.push(move);
}
});
CheckInvariants(board);
}
})();
|
var loaders = require("./loaders");
var BrowserSyncPlugin = require('browser-sync-webpack-plugin');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var webpack = require('webpack');
module.exports = {
entry: ['./src/index.ts'],
output: {
filename: 'build.js',
path: 'dist'
},
resolve: {
root: __dirname,
extensions: ['', '.ts', '.js', '.json']
},
resolveLoader: {
modulesDirectories: ["node_modules"]
},
devtool: "inline-eval-cheap-source-map",
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html',
inject: 'body',
hash: true
}),
new BrowserSyncPlugin({
host: 'localhost',
port: 8080,
server: {
baseDir: 'dist'
},
ui: false,
online: false,
notify: false
}),
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery',
'window.jquery': 'jquery'
})
],
module:{
loaders: loaders
}
};
|
var indexOf = require('./indexOf');
/**
* Remove all instances of an item from array.
*/
/**
* Description
* @method removeAll
* @param {} arr
* @param {} item
* @return
*/
function removeAll(arr, item){
var idx = indexOf(arr, item);
while (idx !== -1) {
arr.splice(idx, 1);
idx = indexOf(arr, item, idx);
}
}
module.exports = removeAll;
|
if (true) {
console.log('work');
} else {
console.log('sleep');
}
|
import initUserPopovers from '~/user_popovers';
import UsersCache from '~/lib/utils/users_cache';
describe('User Popovers', () => {
const fixtureTemplate = 'merge_requests/diff_comment.html';
preloadFixtures(fixtureTemplate);
const selector = '.js-user-link';
const dummyUser = { name: 'root' };
const dummyUserStatus = { message: 'active' };
const triggerEvent = (eventName, el) => {
const event = document.createEvent('MouseEvents');
event.initMouseEvent(eventName, true, true, window);
el.dispatchEvent(event);
};
beforeEach(() => {
loadFixtures(fixtureTemplate);
const usersCacheSpy = () => Promise.resolve(dummyUser);
spyOn(UsersCache, 'retrieveById').and.callFake(userId => usersCacheSpy(userId));
const userStatusCacheSpy = () => Promise.resolve(dummyUserStatus);
spyOn(UsersCache, 'retrieveStatusById').and.callFake(userId => userStatusCacheSpy(userId));
initUserPopovers(document.querySelectorAll('.js-user-link'));
});
it('Should Show+Hide Popover on mouseenter and mouseleave', done => {
const targetLink = document.querySelector(selector);
const { userId } = targetLink.dataset;
triggerEvent('mouseenter', targetLink);
setTimeout(() => {
const shownPopover = document.querySelector('.popover');
expect(shownPopover).not.toBeNull();
expect(shownPopover.innerHTML).toContain(dummyUser.name);
expect(UsersCache.retrieveById).toHaveBeenCalledWith(userId.toString());
triggerEvent('mouseleave', targetLink);
setTimeout(() => {
// After Mouse leave it should be hidden now
expect(document.querySelector('.popover')).toBeNull();
done();
});
}, 210); // We need to wait until the 200ms mouseover delay is over, only then the popover will be visible
});
it('Should Not show a popover on short mouse over', done => {
const targetLink = document.querySelector(selector);
const { userId } = targetLink.dataset;
triggerEvent('mouseenter', targetLink);
setTimeout(() => {
expect(document.querySelector('.popover')).toBeNull();
expect(UsersCache.retrieveById).not.toHaveBeenCalledWith(userId.toString());
triggerEvent('mouseleave', targetLink);
done();
});
});
});
|
// /**
// * Created by Ding-YH on 2015/9/29.
// */
var main = function() {
//$(".log").hide();
$(".shengchan").hide();
$("#tab01").click(function () {
$(".shengchan").hide();
$(".caigou").show();
$("#tab02").removeClass(("active"));
$("#tab01").addClass("active");
});
$("#tab02").click(function () {
$(".caigou").hide();
$(".shengchan").show();
$("#tab01").removeClass(("active"));
$("#tab02").addClass("active");
});
//$(".buyamount").keyup(function(){ #键入采购量后会实时显示总价
// am = $(this).val();
// $(".totalpay").text( {{material_a[game_round]}} );
//});
$(".btn-submit").click(function(){
alert("提交成功");
});
/*
$(".bill").click(function(){
$(".log").toggle();
});*/
};
$(document).ready(main); |
const TimeFormats = {
'ms': {
stringValue: 'ms',
rawValue: 1
},
's': {
stringValue: 's',
rawValue: 1000
},
'm': {
stringValue: 'min',
rawValue: 1000 * 60
},
'H': {
stringValue: 'h',
rawValue: 1000 * Math.pow(60, 2)
}
}
class WatchSet {
constructor (props) {
this.begin = 0
this.end = 0
if (props) {
this.begin = props.begin
this.end = props.end
}
}
diff () {
return this.end - this.begin
}
isEqual (watchSet) {
if (!(watchSet instanceof WatchSet)) {
throw new TypeError(
`watchSet must be a WatchSet. Received: ${typeof watchSet}`
)
}
return this.begin === watchSet.begin && this.end === watchSet.end
}
format (value, format) {
if (typeof value !== 'number') {
throw new TypeError('Value must be number. Received: ' + typeof value)
}
if (typeof format !== 'string') {
format = nearestTimeFormat(value)
}
const timeFormat = TimeFormats[format] || TimeFormats['ms']
const timeDiff = (value / timeFormat.rawValue).toFixed(1)
return `${timeDiff}${timeFormat.stringValue}`
}
toString (format) {
return this.format(this.diff(), format)
}
}
class StopWatch extends WatchSet {
constructor () {
super(null)
this.sets = new Set()
}
start () {
this.begin = +new Date()
}
stop () {
this.end = +new Date()
this.saveSet()
}
restart () {
this.stop()
this.start()
}
reset () {
this.begin = 0
this.end = 0
this.sets = new Set()
}
saveSet () {
this.sets.add( new WatchSet({ begin: this.begin, end: this.end }) )
}
getWatchSet (index) {
return [...this.sets][index]
}
}
module.exports = {
StopWatch,
WatchSet
}
/////////////////////////
function nearestTimeFormat (value) {
const keys = Object.keys(TimeFormats)
for (let i = 0; i < keys.length; i++) {
const next = TimeFormats[keys[i+1]]
const current = TimeFormats[keys[i]]
if (!next) return current.stringValue
if (value > next.rawValue) continue
return current.stringValue
}
return TimeFormats['ms'].stringValue
}
|
import requireAll from 'require-all';
import { getDefault } from '../../shared/util/ModuleUtil';
import BaseFeature from './BaseFeature';
const modules = requireAll({
dirname: `${__dirname}/features`,
filter: /(.+)\.js$/,
recursive: true,
});
const featureClasses: BaseFeature[] = Object.keys(modules)
.map(featureName => {
return getDefault(modules[featureName]);
});
for (const moduleName of Object.keys(modules)) {
modules[moduleName] = getDefault(modules[moduleName]);
}
Object.freeze(featureClasses);
export default featureClasses;
|
// Copyright (c) 2012 Ecma International. All rights reserved.
// Ecma International makes this code available under the terms and conditions set
// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
// "Use Terms"). Any redistribution of this code must retain the above
// copyright and this notice and otherwise comply with the Use Terms.
/*---
es5id: 8.5.1
description: Valid Number ranges
---*/
// Check range support for Number values (IEEE 754 64-bit floats having the form s*m*2**e)
//
// For normalized floats, sign (s) is +1 or -1, m (mantisa) is a positive integer less
// than 2**53 but not less than 2**52 and e (exponent) is an integer ranging from -1074 to 971
//
// For denormalized floats, s is +1 or -1, m is a positive integer less than 2**52, and
// e is -1074
//
// Below 64-bit float values shown for informational purposes. Values may be positive or negative.
// Infinity >= ~1.797693134862315907729305190789e+308 >= 2**1024
// MAX_NORM = ~1.797693134862315708145274237317e+308 = (2**53 - 1) * (2**-52) * (2**1023) = (2**53-1) * (2**971) = (2**1024) - (2**971)
// MIN_NORM = ~2.2250738585072013830902327173324e-308 = 2**-1022
// MAX_DENORM = ~2.2250738585072008890245868760859e-308 = MIN_NORM - MIN_DENORM = (2**-1022) - (2**-1074)
// MIN_DENORM = ~4.9406564584124654417656879286822e-324 = 2**-1074
// Fill an array with 2 to the power of (0 ... -1075)
var value = 1;
var floatValues = new Array(1076);
for(var power = 0; power <= 1075; power++){
floatValues[power] = value;
// Use basic math operations for testing, which are required to support 'gradual underflow' rather
// than Math.pow etc..., which are defined as 'implementation dependent'.
value = value * 0.5;
}
// The last value is below min denorm and should round to 0, everything else should contain a value
if(floatValues[1075] !== 0) {
$ERROR("Value after min denorm should round to 0");
}
// Validate the last actual value is min denorm
if(floatValues[1074] !== 4.9406564584124654417656879286822e-324) {
$ERROR("Min denorm value is incorrect: " + floatValues[1074]);
}
// Validate that every value is half the value before it up to 1
for(var index = 1074; index > 0; index--){
if(floatValues[index] === 0){
$ERROR("2**-" + index + " should not be 0");
}
if(floatValues[index - 1] !== (floatValues[index] * 2)){
$ERROR("Value should be double adjacent value at index " + index);
}
}
// Max norm should be supported and compare less than inifity
if(!(1.797693134862315708145274237317e+308 < Infinity)){
$ERROR("Max Number value 1.797693134862315708145274237317e+308 should not overflow to infinity");
}
// Numbers closer to 2**1024 then max norm should overflow to infinity
if(!(1.797693134862315808e+308 === +Infinity)){
$ERROR("1.797693134862315808e+308 did not resolve to Infinity");
}
|
//>>built
define("dojo/on",["./has!dom-addeventlistener?:./aspect","./_base/kernel","./sniff"],function(v,w,e){function x(a,b,c,d,h){if(d=b.match(/(.*):(.*)/))return b=d[2],d=d[1],f.selector(d,b).call(h,a,c);e("touch")&&(y.test(b)&&(c=m(c)),!e("event-orientationchange")&&"orientationchange"==b&&(b="resize",a=window,c=m(c)));n&&(c=n(c));if(a.addEventListener){var k=b in p,g=k?p[b]:b;a.addEventListener(g,c,k);return{remove:function(){a.removeEventListener(g,c,k)}}}if(q&&a.attachEvent)return q(a,"on"+b,c);throw Error("Target must be an event emitter");
}function z(){this.cancelable=!1;this.defaultPrevented=!0}function A(){this.bubbles=!1}var r=window.ScriptEngineMajorVersion;e.add("jscript",r&&r()+ScriptEngineMinorVersion()/10);e.add("event-orientationchange",e("touch")&&!e("android"));e.add("event-stopimmediatepropagation",window.Event&&!!window.Event.prototype&&!!window.Event.prototype.stopImmediatePropagation);e.add("event-focusin",function(a,b,c){return!!c.attachEvent});var f=function(a,b,c,d){return"function"==typeof a.on&&"function"!=typeof b&&
!a.nodeType?a.on(b,c):f.parse(a,b,c,x,d,this)};f.pausable=function(a,b,c,d){var h;a=f(a,b,function(){if(!h)return c.apply(this,arguments)},d);a.pause=function(){h=!0};a.resume=function(){h=!1};return a};f.once=function(a,b,c,d){var h=f(a,b,function(){h.remove();return c.apply(this,arguments)});return h};f.parse=function(a,b,c,d,h,k){if(b.call)return b.call(k,a,c);if(-1<b.indexOf(",")){b=b.split(/\s*,\s*/);for(var g=[],f=0,e;e=b[f++];)g.push(d(a,e,c,h,k));g.remove=function(){for(var a=0;a<g.length;a++)g[a].remove()};
return g}return d(a,b,c,h,k)};var y=/^touch/;f.selector=function(a,b,c){return function(d,h){function k(b){g=g&&g.matches?g:w.query;1!=b.nodeType&&(b=b.parentNode);for(;!g.matches(b,a,d);)if(b==d||!1===c||!(b=b.parentNode)||1!=b.nodeType)return;return b}var g="function"==typeof a?{matches:a}:this,e=b.bubble;return e?f(d,e(k),h):f(d,b,function(a){var b=k(a.target);return b&&h.call(b,a)})}};var B=[].slice,C=f.emit=function(a,b,c){var d=B.call(arguments,2),h="on"+b;if("parentNode"in a){var e=d[0]={},
g;for(g in c)e[g]=c[g];e.preventDefault=z;e.stopPropagation=A;e.target=a;e.type=b;c=e}do a[h]&&a[h].apply(a,d);while(c&&c.bubbles&&(a=a.parentNode));return c&&c.cancelable&&c},p=e("event-focusin")?{}:{focusin:"focus",focusout:"blur"};if(!e("event-stopimmediatepropagation"))var D=function(){this.modified=this.immediatelyStopped=!0},n=function(a){return function(b){if(!b.immediatelyStopped)return b.stopImmediatePropagation=D,a.apply(this,arguments)}};if(e("dom-addeventlistener"))f.emit=function(a,b,
c){if(a.dispatchEvent&&document.createEvent){var d=a.ownerDocument.createEvent("HTMLEvents");d.initEvent(b,!!c.bubbles,!!c.cancelable);for(var e in c)e in d||(d[e]=c[e]);return a.dispatchEvent(d)&&d}return C.apply(f,arguments)};else{f._fixEvent=function(a,b){a||(a=(b&&(b.ownerDocument||b.document||b).parentWindow||window).event);if(!a)return a;try{l&&(a.type==l.type&&a.srcElement==l.target)&&(a=l)}catch(c){}if(!a.target)switch(a.target=a.srcElement,a.currentTarget=b||a.srcElement,"mouseover"==a.type&&
(a.relatedTarget=a.fromElement),"mouseout"==a.type&&(a.relatedTarget=a.toElement),a.stopPropagation||(a.stopPropagation=E,a.preventDefault=F),a.type){case "keypress":var d="charCode"in a?a.charCode:a.keyCode;10==d?(d=0,a.keyCode=13):13==d||27==d?d=0:3==d&&(d=99);a.charCode=d;d=a;d.keyChar=d.charCode?String.fromCharCode(d.charCode):"";d.charOrCode=d.keyChar||d.keyCode}return a};var l,s=function(a){this.handle=a};s.prototype.remove=function(){delete _dojoIEListeners_[this.handle]};var G=function(a){return function(b){b=
f._fixEvent(b,this);var c=a.call(this,b);b.modified&&(l||setTimeout(function(){l=null}),l=b);return c}},q=function(a,b,c){c=G(c);if(((a.ownerDocument?a.ownerDocument.parentWindow:a.parentWindow||a.window||window)!=top||5.8>e("jscript"))&&!e("config-_allow_leaks")){"undefined"==typeof _dojoIEListeners_&&(_dojoIEListeners_=[]);var d=a[b];if(!d||!d.listeners){var h=d,d=Function("event","var callee \x3d arguments.callee; for(var i \x3d 0; i\x3ccallee.listeners.length; i++){var listener \x3d _dojoIEListeners_[callee.listeners[i]]; if(listener){listener.call(this,event);}}");
d.listeners=[];a[b]=d;d.global=this;h&&d.listeners.push(_dojoIEListeners_.push(h)-1)}d.listeners.push(a=d.global._dojoIEListeners_.push(c)-1);return new s(a)}return v.after(a,b,c,!0)},E=function(){this.cancelBubble=!0},F=f._preventDefault=function(){this.bubbledKeyCode=this.keyCode;if(this.ctrlKey)try{this.keyCode=0}catch(a){}this.defaultPrevented=!0;this.returnValue=!1;this.modified=!0}}if(e("touch"))var t=function(){},u=window.orientation,m=function(a){return function(b){var c=b.corrected;if(!c){var d=
b.type;try{delete b.type}catch(h){}if(b.type){if(e("mozilla")){var c={},f;for(f in b)c[f]=b[f]}else t.prototype=b,c=new t;c.preventDefault=function(){b.preventDefault()};c.stopPropagation=function(){b.stopPropagation()}}else c=b,c.type=d;b.corrected=c;if("resize"==d){if(u==window.orientation)return null;u=window.orientation;c.type="orientationchange";return a.call(this,c)}"rotation"in c||(c.rotation=0,c.scale=1);var d=c.changedTouches[0],g;for(g in d)delete c[g],c[g]=d[g]}return a.call(this,c)}};
return f});
//@ sourceMappingURL=on.js.map |
!function(n){n(document).on("ready",function(){n("nav button").click(function(){n("nav ul").slideToggle()})})}(jQuery); |
if(!dojo._hasResource["dojox.charting.plot2d.Stacked"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
dojo._hasResource["dojox.charting.plot2d.Stacked"] = true;
dojo.provide("dojox.charting.plot2d.Stacked");
dojo.require("dojox.charting.plot2d.common");
dojo.require("dojox.charting.plot2d.Default");
dojo.require("dojox.lang.functional");
dojo.require("dojox.lang.functional.sequence");
dojo.require("dojox.lang.functional.reversed");
(function(){
var df = dojox.lang.functional, dc = dojox.charting.plot2d.common,
purgeGroup = df.lambda("item.purgeGroup()");
dojo.declare("dojox.charting.plot2d.Stacked", dojox.charting.plot2d.Default, {
calculateAxes: function(dim){
var stats = dc.collectStackedStats(this.series);
this._maxRunLength = stats.hmax;
this._calc(dim, stats);
return this;
},
render: function(dim, offsets){
// stack all values
var acc = df.repeat(this._maxRunLength, "-> 0", 0);
for(var i = 0; i < this.series.length; ++i){
var run = this.series[i];
for(var j = 0; j < run.data.length; ++j){
var v = run.data[j];
if(isNaN(v)){ v = 0; }
acc[j] += v;
}
}
// draw runs in backwards
if(this.dirty){
dojo.forEach(this.series, purgeGroup);
this.cleanGroup();
var s = this.group;
df.forEachRev(this.series, function(item){ item.cleanGroup(s); });
}
// inner function for translating polylines to curves with tension
function curve(arr, tension){
var p=dojo.map(arr, function(item, i){
if(i==0){ return "M" + item.x + "," + item.y; }
var dx=item.x-arr[i-1].x, dy=arr[i-1].y;
return "C"+(item.x-(tension-1)*(dx/tension))+","+dy+" "+(item.x-(dx/tension))+","+item.y+" "+item.x+","+item.y;
});
return p.join(" ");
}
var t = this.chart.theme, stroke, outline, color, marker;
for(var i = this.series.length - 1; i >= 0; --i){
var run = this.series[i];
if(!this.dirty && !run.dirty){ continue; }
run.cleanGroup();
var s = run.group,
lpoly = dojo.map(acc, function(v, i){
return {
x: this._hScaler.scale * (i + 1 - this._hScaler.bounds.lower) + offsets.l,
y: dim.height - offsets.b - this._vScaler.scale * (v - this._vScaler.bounds.lower)
};
}, this);
if(!run.fill || !run.stroke){
// need autogenerated color
color = new dojo.Color(t.next("color"));
}
var lpath="";
if(this.opt.tension){
lpath=curve(lpoly, this.opt.tension);
}
if(this.opt.areas){
var apoly = dojo.clone(lpoly);
var fill = run.fill ? run.fill : dc.augmentFill(t.series.fill, color);
if(this.opt.tension){
var p=curve(apoly, this.opt.tension);
p += " L" + lpoly[lpoly.length-1].x + "," + (dim.height - offsets.b) + " "
+ "L" + lpoly[0].x + "," + (dim.height - offsets.b) + " "
+ "L" + lpoly[0].x + "," + lpoly[0].y;
s.createPath(p).setFill(fill);
} else {
apoly.push({x: lpoly[lpoly.length - 1].x, y: dim.height - offsets.b});
apoly.push({x: lpoly[0].x, y: dim.height - offsets.b});
apoly.push(lpoly[0]);
s.createPolyline(apoly).setFill(fill);
}
}
if(this.opt.lines || this.opt.markers){
// need a stroke
stroke = run.stroke ? dc.makeStroke(run.stroke) : dc.augmentStroke(t.series.stroke, color);
if(run.outline || t.series.outline){
outline = dc.makeStroke(run.outline ? run.outline : t.series.outline);
outline.width = 2 * outline.width + stroke.width;
}
}
if(this.opt.markers){
// need a marker
marker = run.marker ? run.marker : t.next("marker");
}
if(this.opt.shadows && stroke){
var sh = this.opt.shadows, shadowColor = new dojo.Color([0, 0, 0, 0.3]),
spoly = dojo.map(lpoly, function(c){
return {x: c.x + sh.dx, y: c.y + sh.dy};
}),
shadowStroke = dojo.clone(outline ? outline : stroke);
shadowStroke.color = shadowColor;
shadowStroke.width += sh.dw ? sh.dw : 0;
if(this.opt.lines){
if(this.opt.tension){
s.createPath(curve(spoly, this.opt.tension)).setStroke(shadowStroke);
} else {
s.createPolyline(spoly).setStroke(shadowStroke);
}
}
if(this.opt.markers){
dojo.forEach(spoly, function(c){
s.createPath("M" + c.x + " " + c.y + " " + marker).setStroke(shadowStroke).setFill(shadowColor);
}, this);
}
}
if(this.opt.lines){
if(outline){
if(this.opt.tension){
s.createPath(lpath).setStroke(outline);
} else {
s.createPolyline(lpoly).setStroke(outline);
}
}
if(this.opt.tension){
s.createPath(lpath).setStroke(stroke);
} else {
s.createPolyline(lpoly).setStroke(stroke);
}
}
if(this.opt.markers){
dojo.forEach(lpoly, function(c){
var path = "M" + c.x + " " + c.y + " " + marker;
if(outline){
s.createPath(path).setStroke(outline);
}
s.createPath(path).setStroke(stroke).setFill(stroke.color);
}, this);
}
run.dirty = false;
// update the accumulator
for(var j = 0; j < run.data.length; ++j){
var v = run.data[j];
if(isNaN(v)){ v = 0; }
acc[j] -= v;
}
}
this.dirty = false;
return this;
}
});
})();
}
|
var Promise = require('bluebird');
var request = Promise.promisify(require("request"));
Promise.promisifyAll(request);
var moment = require('moment');
crawlerUtils = {}
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1'}
// Request url and use the closure to attempt torrent data extraction from it
crawlerUtils.attemptDataExtractionFromUrl = function(url, retrieveDataClosure) {
return Promise.delay(2000).then(function() {
console.log("After 2s --> " + moment().format('HH:mm:ss')) ;
return request({uri: url, headers: headers}).then(function(response) {
console.log("Connecting to URL: " + url + " -- " + moment().format('HH:mm:ss'));
if (response.statusCode == 200) {
return retrieveDataClosure(response.body);
} else {
console.log("Not 200 -- ", response.statusCode);
}
}).catch(function(error) {
console.log('Error connecting to url ' + url, error);
return error;
});
});
}
module.exports = crawlerUtils;
|
System.config({
"transpiler": "babel",
"babelOptions": {
"optional": [
"es7.decorators",
"es7.classProperties",
"runtime"
]
},
"paths": {
"*": "dist/*.js",
"github:*": "jspm_packages/github/*.js",
"npm:*": "jspm_packages/npm/*.js"
}
});
System.config({
"map": {
"aurelia-bootstrapper": "github:aurelia/bootstrapper@0.14.0",
"aurelia-dependency-injection": "github:aurelia/dependency-injection@0.9.0",
"aurelia-framework": "github:aurelia/framework@0.13.2",
"aurelia-http-client": "github:aurelia/http-client@0.10.0",
"aurelia-router": "github:aurelia/router@0.10.1",
"babel": "npm:babel-core@5.6.15",
"babel-runtime": "npm:babel-runtime@5.6.15",
"bootstrap": "github:twbs/bootstrap@3.3.5",
"commonmark": "npm:commonmark@0.18.2",
"core-js": "npm:core-js@0.9.18",
"css": "github:systemjs/plugin-css@0.1.13",
"font-awesome": "npm:font-awesome@4.3.0",
"moment": "github:moment/moment@2.10.3",
"numeral": "npm:numeral@1.5.3",
"github:aurelia/binding@0.8.1": {
"aurelia-dependency-injection": "github:aurelia/dependency-injection@0.9.0",
"aurelia-metadata": "github:aurelia/metadata@0.7.0",
"aurelia-task-queue": "github:aurelia/task-queue@0.6.0",
"core-js": "npm:core-js@0.9.18"
},
"github:aurelia/bootstrapper@0.14.0": {
"aurelia-event-aggregator": "github:aurelia/event-aggregator@0.6.1",
"aurelia-framework": "github:aurelia/framework@0.13.2",
"aurelia-history": "github:aurelia/history@0.6.0",
"aurelia-history-browser": "github:aurelia/history-browser@0.6.1",
"aurelia-loader-default": "github:aurelia/loader-default@0.9.0",
"aurelia-logging-console": "github:aurelia/logging-console@0.6.0",
"aurelia-router": "github:aurelia/router@0.10.1",
"aurelia-templating": "github:aurelia/templating@0.13.2",
"aurelia-templating-binding": "github:aurelia/templating-binding@0.13.0",
"aurelia-templating-resources": "github:aurelia/templating-resources@0.13.0",
"aurelia-templating-router": "github:aurelia/templating-router@0.14.0",
"core-js": "npm:core-js@0.9.18"
},
"github:aurelia/dependency-injection@0.9.0": {
"aurelia-logging": "github:aurelia/logging@0.6.0",
"aurelia-metadata": "github:aurelia/metadata@0.7.0",
"core-js": "npm:core-js@0.9.18"
},
"github:aurelia/event-aggregator@0.6.1": {
"aurelia-logging": "github:aurelia/logging@0.6.0"
},
"github:aurelia/framework@0.13.2": {
"aurelia-binding": "github:aurelia/binding@0.8.1",
"aurelia-dependency-injection": "github:aurelia/dependency-injection@0.9.0",
"aurelia-loader": "github:aurelia/loader@0.8.0",
"aurelia-logging": "github:aurelia/logging@0.6.0",
"aurelia-metadata": "github:aurelia/metadata@0.7.0",
"aurelia-path": "github:aurelia/path@0.8.0",
"aurelia-task-queue": "github:aurelia/task-queue@0.6.0",
"aurelia-templating": "github:aurelia/templating@0.13.2",
"core-js": "npm:core-js@0.9.18"
},
"github:aurelia/history-browser@0.6.1": {
"aurelia-history": "github:aurelia/history@0.6.0",
"core-js": "npm:core-js@0.9.18"
},
"github:aurelia/http-client@0.10.0": {
"aurelia-path": "github:aurelia/path@0.8.0",
"core-js": "npm:core-js@0.9.18"
},
"github:aurelia/loader-default@0.9.0": {
"aurelia-loader": "github:aurelia/loader@0.8.0",
"aurelia-metadata": "github:aurelia/metadata@0.7.0"
},
"github:aurelia/loader@0.8.0": {
"aurelia-html-template-element": "github:aurelia/html-template-element@0.2.0",
"aurelia-path": "github:aurelia/path@0.8.0",
"core-js": "npm:core-js@0.9.18",
"webcomponentsjs": "github:webcomponents/webcomponentsjs@0.6.3"
},
"github:aurelia/metadata@0.7.0": {
"core-js": "npm:core-js@0.9.18"
},
"github:aurelia/route-recognizer@0.6.0": {
"core-js": "npm:core-js@0.9.18"
},
"github:aurelia/router@0.10.1": {
"aurelia-dependency-injection": "github:aurelia/dependency-injection@0.9.0",
"aurelia-event-aggregator": "github:aurelia/event-aggregator@0.6.1",
"aurelia-history": "github:aurelia/history@0.6.0",
"aurelia-logging": "github:aurelia/logging@0.6.0",
"aurelia-path": "github:aurelia/path@0.8.0",
"aurelia-route-recognizer": "github:aurelia/route-recognizer@0.6.0",
"core-js": "npm:core-js@0.9.18"
},
"github:aurelia/templating-binding@0.13.0": {
"aurelia-binding": "github:aurelia/binding@0.8.1",
"aurelia-logging": "github:aurelia/logging@0.6.0",
"aurelia-templating": "github:aurelia/templating@0.13.2"
},
"github:aurelia/templating-resources@0.13.0": {
"aurelia-binding": "github:aurelia/binding@0.8.1",
"aurelia-dependency-injection": "github:aurelia/dependency-injection@0.9.0",
"aurelia-logging": "github:aurelia/logging@0.6.0",
"aurelia-task-queue": "github:aurelia/task-queue@0.6.0",
"aurelia-templating": "github:aurelia/templating@0.13.2",
"core-js": "npm:core-js@0.9.18"
},
"github:aurelia/templating-router@0.14.0": {
"aurelia-dependency-injection": "github:aurelia/dependency-injection@0.9.0",
"aurelia-metadata": "github:aurelia/metadata@0.7.0",
"aurelia-path": "github:aurelia/path@0.8.0",
"aurelia-router": "github:aurelia/router@0.10.1",
"aurelia-templating": "github:aurelia/templating@0.13.2"
},
"github:aurelia/templating@0.13.2": {
"aurelia-binding": "github:aurelia/binding@0.8.1",
"aurelia-dependency-injection": "github:aurelia/dependency-injection@0.9.0",
"aurelia-html-template-element": "github:aurelia/html-template-element@0.2.0",
"aurelia-loader": "github:aurelia/loader@0.8.0",
"aurelia-logging": "github:aurelia/logging@0.6.0",
"aurelia-metadata": "github:aurelia/metadata@0.7.0",
"aurelia-path": "github:aurelia/path@0.8.0",
"aurelia-task-queue": "github:aurelia/task-queue@0.6.0",
"core-js": "npm:core-js@0.9.18"
},
"github:jspm/nodelibs-buffer@0.1.0": {
"buffer": "npm:buffer@3.3.1"
},
"github:jspm/nodelibs-path@0.1.0": {
"path-browserify": "npm:path-browserify@0.0.0"
},
"github:jspm/nodelibs-process@0.1.1": {
"process": "npm:process@0.10.1"
},
"github:jspm/nodelibs-util@0.1.0": {
"util": "npm:util@0.10.3"
},
"github:twbs/bootstrap@3.3.5": {
"jquery": "github:components/jquery@2.1.4"
},
"npm:babel-runtime@5.6.15": {
"process": "github:jspm/nodelibs-process@0.1.1"
},
"npm:buffer@3.3.1": {
"base64-js": "npm:base64-js@0.0.8",
"ieee754": "npm:ieee754@1.1.6",
"is-array": "npm:is-array@1.0.1"
},
"npm:commonmark@0.18.2": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"fs": "github:jspm/nodelibs-fs@0.1.2",
"path": "github:jspm/nodelibs-path@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.1",
"systemjs-json": "github:systemjs/plugin-json@0.1.0",
"util": "github:jspm/nodelibs-util@0.1.0"
},
"npm:core-js@0.9.18": {
"fs": "github:jspm/nodelibs-fs@0.1.2",
"process": "github:jspm/nodelibs-process@0.1.1",
"systemjs-json": "github:systemjs/plugin-json@0.1.0"
},
"npm:font-awesome@4.3.0": {
"css": "github:systemjs/plugin-css@0.1.13"
},
"npm:inherits@2.0.1": {
"util": "github:jspm/nodelibs-util@0.1.0"
},
"npm:numeral@1.5.3": {
"fs": "github:jspm/nodelibs-fs@0.1.2"
},
"npm:path-browserify@0.0.0": {
"process": "github:jspm/nodelibs-process@0.1.1"
},
"npm:util@0.10.3": {
"inherits": "npm:inherits@2.0.1",
"process": "github:jspm/nodelibs-process@0.1.1"
}
}
});
|
"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: "m16.11 7-.59-.65L14.28 5h-4.24L8.81 6.35l-.6.65H4v12h7v-1.09c-2.83-.48-5-2.94-5-5.91h2c0 2.21 1.79 4 4 4s4-1.79 4-4h2c0 2.97-2.17 5.43-5 5.91V19h7V7h-3.89zM14 12c0 1.1-.9 2-2 2s-2-.9-2-2V8c0-1.1.9-2 2-2s2 .9 2 2v4z",
opacity: ".3"
}, "0"), /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M12 6c-1.1 0-2 .9-2 2v4c0 1.1.9 2 2 2s2-.9 2-2V8c0-1.1-.9-2-2-2zm8-1h-3.17l-1.86-2H8.96L7.17 5H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 14h-7v-1.09c2.83-.48 5-2.94 5-5.91h-2c0 2.21-1.79 4-4 4s-4-1.79-4-4H6c0 2.97 2.17 5.43 5 5.91V19H4V7h4.21l.59-.65L10.04 5h4.24l1.24 1.35.59.65H20v12z"
}, "1")], 'PermCameraMicTwoTone');
exports.default = _default; |
version https://git-lfs.github.com/spec/v1
oid sha256:379f77a3ff980fe8ed659e040809623c59f3bce007edc0dce611a276d03aaf4e
size 6535
|
// this is service script that extracts names from names.txt and places them into list.json
/*
const fs = require('fs');
function readTxt(fileName) {
const text = fs.readFileSync(fileName).toString('utf8');
const lines = text.split('\n');
const langs = lines.shift().split('\t').map(l => l.toLowerCase().trim());
const result = {};
lines.forEach(line => {
const words = line.split('\t').map(w => w.trim());
const word = {};
result[words[0]] = word;
langs.forEach((lang, i) => {
word[lang] = words[i];
});
});
return result;
}
function mergeTexts(jsonFileName, words) {
const file = require(jsonFileName);
file.forEach(item => {
if (typeof item.name === 'string' && words[item.name]) {
item.name = words[item.name];
}
});
fs.writeFileSync(jsonFileName, JSON.stringify(file, null, 2));
}
const words = readTxt(__dirname + '/names.txt');
mergeTexts(__dirname + '/list.json', words);
*/ |
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2020 Photon Storm Ltd.
* @license {@link https://opensource.org/licenses/MIT|MIT License}
*/
var renderWebGL = require('../../utils/NOOP');
var renderCanvas = require('../../utils/NOOP');
if (typeof WEBGL_RENDERER)
{
renderWebGL = require('./ExternWebGLRenderer');
}
if (typeof CANVAS_RENDERER)
{
renderCanvas = require('./ExternCanvasRenderer');
}
module.exports = {
renderWebGL: renderWebGL,
renderCanvas: renderCanvas
};
|
(function () {
'use strict';
function responseInterceptor($q, $location, ngToast) {
function successHandler(response) {
console.log('Response from server', response);
// Return a promise
return response || $q.when(response);
}
function errorHandler(rejection) {
console.log('Response rejected', rejection);
var message = rejection.data.error_description ||
rejection.data.message ||
'Oh shoot! Looks like something went wrong!';
ngToast.danger(message);
if (rejection.status === 403) {
ngToast.warning('You can do this, I believe in you');
$location.path('/login');
}
return $q.reject(rejection);
}
return {
response: successHandler,
responseError: errorHandler
};
}
angular
.module('quizProjectApp.services')
.factory('responseInterceptor', ['$q', '$location', 'ngToast', responseInterceptor]);
}()); |
import React, { PropTypes } from 'react';
import ReactDOM from 'react-dom';
import { createPureComponent } from 'utils/createPureComponent';
import World from 'components/World/World';
import EditorTools from 'components/EditorTools/EditorTools';
import EditorTiler from 'components/EditorTiler/EditorTiler';
import 'components/Editor/Editor.scss';
export default createPureComponent({
displayName: 'Editor',
propTypes: {
activeEntity: PropTypes.string,
activeGround: PropTypes.string,
minCol: PropTypes.number.isRequired,
maxCol: PropTypes.number.isRequired,
minRow: PropTypes.number.isRequired,
maxRow: PropTypes.number.isRequired,
onPickTile: PropTypes.func.isRequired,
onPlaceTile: PropTypes.func.isRequired,
onWillMount: PropTypes.func.isRequired,
},
componentWillMount() {
this.props.onWillMount();
},
render() {
return (
<div className="editor">
<EditorTools {...this.props} />
<World row={0} col={0}>
<EditorTiler {...this.props} />
</World>
</div>
);
}
});
|
require(['b'], function(){});
|
/*!
* jQuery JavaScript Library v2.1.4
* http://jquery.com/
*
* Includes Sizzle.js
* http://sizzlejs.com/
*
* Copyright 2005, 2014 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2015-04-28T16:01Z
*/
(function( global, factory ) {
if ( typeof module === "object" && typeof module.exports === "object" ) {
// For CommonJS and CommonJS-like environments where a proper `window`
// is present, execute the factory and get jQuery.
// For environments that do not have a `window` with a `document`
// (such as Node.js), expose a factory as module.exports.
// This accentuates the need for the creation of a real `window`.
// e.g. var jQuery = require("jquery")(window);
// See ticket #14549 for more info.
module.exports = global.document ?
factory( global, true ) :
function( w ) {
if ( !w.document ) {
throw new Error( "jQuery requires a window with a document" );
}
return factory( w );
};
} else {
factory( global );
}
// Pass this if window is not defined yet
}(typeof window !== "undefined" ? window : this, function( window, noGlobal ) {
// Support: Firefox 18+
// Can't be in strict mode, several libs including ASP.NET trace
// the stack via arguments.caller.callee and Firefox dies if
// you try to trace through "use strict" call chains. (#13335)
//
var arr = [];
var slice = arr.slice;
var concat = arr.concat;
var push = arr.push;
var indexOf = arr.indexOf;
var class2type = {};
var toString = class2type.toString;
var hasOwn = class2type.hasOwnProperty;
var support = {};
var
// Use the correct document accordingly with window argument (sandbox)
document = window.document,
version = "2.1.4",
// Define a local copy of jQuery
jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
// Need init if jQuery is called (just allow error to be thrown if not included)
return new jQuery.fn.init( selector, context );
},
// Support: Android<4.1
// Make sure we trim BOM and NBSP
rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
// Matches dashed string for camelizing
rmsPrefix = /^-ms-/,
rdashAlpha = /-([\da-z])/gi,
// Used by jQuery.camelCase as callback to replace()
fcamelCase = function( all, letter ) {
return letter.toUpperCase();
};
jQuery.fn = jQuery.prototype = {
// The current version of jQuery being used
jquery: version,
constructor: jQuery,
// Start with an empty selector
selector: "",
// The default length of a jQuery object is 0
length: 0,
toArray: function() {
return slice.call( this );
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
return num != null ?
// Return just the one element from the set
( num < 0 ? this[ num + this.length ] : this[ num ] ) :
// Return all the elements in a clean array
slice.call( this );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems ) {
// Build a new jQuery matched element set
var ret = jQuery.merge( this.constructor(), elems );
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
map: function( callback ) {
return this.pushStack( jQuery.map(this, function( elem, i ) {
return callback.call( elem, i, elem );
}));
},
slice: function() {
return this.pushStack( slice.apply( this, arguments ) );
},
first: function() {
return this.eq( 0 );
},
last: function() {
return this.eq( -1 );
},
eq: function( i ) {
var len = this.length,
j = +i + ( i < 0 ? len : 0 );
return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] );
},
end: function() {
return this.prevObject || this.constructor(null);
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: push,
sort: arr.sort,
splice: arr.splice
};
jQuery.extend = jQuery.fn.extend = function() {
var options, name, src, copy, copyIsArray, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
// Skip the boolean and the target
target = arguments[ i ] || {};
i++;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
target = {};
}
// Extend jQuery itself if only one argument is passed
if ( i === length ) {
target = this;
i--;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.extend({
// Unique for each copy of jQuery on the page
expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ),
// Assume jQuery is ready without the ready module
isReady: true,
error: function( msg ) {
throw new Error( msg );
},
noop: function() {},
isFunction: function( obj ) {
return jQuery.type(obj) === "function";
},
isArray: Array.isArray,
isWindow: function( obj ) {
return obj != null && obj === obj.window;
},
isNumeric: function( obj ) {
// parseFloat NaNs numeric-cast false positives (null|true|false|"")
// ...but misinterprets leading-number strings, particularly hex literals ("0x...")
// subtraction forces infinities to NaN
// adding 1 corrects loss of precision from parseFloat (#15100)
return !jQuery.isArray( obj ) && (obj - parseFloat( obj ) + 1) >= 0;
},
isPlainObject: function( obj ) {
// Not plain objects:
// - Any object or value whose internal [[Class]] property is not "[object Object]"
// - DOM nodes
// - window
if ( jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
if ( obj.constructor &&
!hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) {
return false;
}
// If the function hasn't returned already, we're confident that
// |obj| is a plain object, created by {} or constructed with new Object
return true;
},
isEmptyObject: function( obj ) {
var name;
for ( name in obj ) {
return false;
}
return true;
},
type: function( obj ) {
if ( obj == null ) {
return obj + "";
}
// Support: Android<4.0, iOS<6 (functionish RegExp)
return typeof obj === "object" || typeof obj === "function" ?
class2type[ toString.call(obj) ] || "object" :
typeof obj;
},
// Evaluates a script in a global context
globalEval: function( code ) {
var script,
indirect = eval;
code = jQuery.trim( code );
if ( code ) {
// If the code includes a valid, prologue position
// strict mode pragma, execute code by injecting a
// script tag into the document.
if ( code.indexOf("use strict") === 1 ) {
script = document.createElement("script");
script.text = code;
document.head.appendChild( script ).parentNode.removeChild( script );
} else {
// Otherwise, avoid the DOM node creation, insertion
// and removal by using an indirect global eval
indirect( code );
}
}
},
// Convert dashed to camelCase; used by the css and data modules
// Support: IE9-11+
// Microsoft forgot to hump their vendor prefix (#9572)
camelCase: function( string ) {
return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
},
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
},
// args is for internal usage only
each: function( obj, callback, args ) {
var value,
i = 0,
length = obj.length,
isArray = isArraylike( obj );
if ( args ) {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
}
}
return obj;
},
// Support: Android<4.1
trim: function( text ) {
return text == null ?
"" :
( text + "" ).replace( rtrim, "" );
},
// results is for internal usage only
makeArray: function( arr, results ) {
var ret = results || [];
if ( arr != null ) {
if ( isArraylike( Object(arr) ) ) {
jQuery.merge( ret,
typeof arr === "string" ?
[ arr ] : arr
);
} else {
push.call( ret, arr );
}
}
return ret;
},
inArray: function( elem, arr, i ) {
return arr == null ? -1 : indexOf.call( arr, elem, i );
},
merge: function( first, second ) {
var len = +second.length,
j = 0,
i = first.length;
for ( ; j < len; j++ ) {
first[ i++ ] = second[ j ];
}
first.length = i;
return first;
},
grep: function( elems, callback, invert ) {
var callbackInverse,
matches = [],
i = 0,
length = elems.length,
callbackExpect = !invert;
// Go through the array, only saving the items
// that pass the validator function
for ( ; i < length; i++ ) {
callbackInverse = !callback( elems[ i ], i );
if ( callbackInverse !== callbackExpect ) {
matches.push( elems[ i ] );
}
}
return matches;
},
// arg is for internal usage only
map: function( elems, callback, arg ) {
var value,
i = 0,
length = elems.length,
isArray = isArraylike( elems ),
ret = [];
// Go through the array, translating each of the items to their new values
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret.push( value );
}
}
// Go through every key on the object,
} else {
for ( i in elems ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret.push( value );
}
}
}
// Flatten any nested arrays
return concat.apply( [], ret );
},
// A global GUID counter for objects
guid: 1,
// Bind a function to a context, optionally partially applying any
// arguments.
proxy: function( fn, context ) {
var tmp, args, proxy;
if ( typeof context === "string" ) {
tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if ( !jQuery.isFunction( fn ) ) {
return undefined;
}
// Simulated bind
args = slice.call( arguments, 2 );
proxy = function() {
return fn.apply( context || this, args.concat( slice.call( arguments ) ) );
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || jQuery.guid++;
return proxy;
},
now: Date.now,
// jQuery.support is not used in Core but other projects attach their
// properties to it so it needs to exist.
support: support
});
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
function isArraylike( obj ) {
// Support: iOS 8.2 (not reproducible in simulator)
// `in` check used to prevent JIT error (gh-2145)
// hasOwn isn't used here due to false negatives
// regarding Nodelist length in IE
var length = "length" in obj && obj.length,
type = jQuery.type( obj );
if ( type === "function" || jQuery.isWindow( obj ) ) {
return false;
}
if ( obj.nodeType === 1 && length ) {
return true;
}
return type === "array" || length === 0 ||
typeof length === "number" && length > 0 && ( length - 1 ) in obj;
}
var Sizzle =
/*!
* Sizzle CSS Selector Engine v2.2.0-pre
* http://sizzlejs.com/
*
* Copyright 2008, 2014 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2014-12-16
*/
(function( window ) {
var i,
support,
Expr,
getText,
isXML,
tokenize,
compile,
select,
outermostContext,
sortInput,
hasDuplicate,
// Local document vars
setDocument,
document,
docElem,
documentIsHTML,
rbuggyQSA,
rbuggyMatches,
matches,
contains,
// Instance-specific data
expando = "sizzle" + 1 * new Date(),
preferredDoc = window.document,
dirruns = 0,
done = 0,
classCache = createCache(),
tokenCache = createCache(),
compilerCache = createCache(),
sortOrder = function( a, b ) {
if ( a === b ) {
hasDuplicate = true;
}
return 0;
},
// General-purpose constants
MAX_NEGATIVE = 1 << 31,
// Instance methods
hasOwn = ({}).hasOwnProperty,
arr = [],
pop = arr.pop,
push_native = arr.push,
push = arr.push,
slice = arr.slice,
// Use a stripped-down indexOf as it's faster than native
// http://jsperf.com/thor-indexof-vs-for/5
indexOf = function( list, elem ) {
var i = 0,
len = list.length;
for ( ; i < len; i++ ) {
if ( list[i] === elem ) {
return i;
}
}
return -1;
},
booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",
// Regular expressions
// Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace
whitespace = "[\\x20\\t\\r\\n\\f]",
// http://www.w3.org/TR/css3-syntax/#characters
characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",
// Loosely modeled on CSS identifier characters
// An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors
// Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
identifier = characterEncoding.replace( "w", "w#" ),
// Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors
attributes = "\\[" + whitespace + "*(" + characterEncoding + ")(?:" + whitespace +
// Operator (capture 2)
"*([*^$|!~]?=)" + whitespace +
// "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]"
"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace +
"*\\]",
pseudos = ":(" + characterEncoding + ")(?:\\((" +
// To reduce the number of selectors needing tokenize in the preFilter, prefer arguments:
// 1. quoted (capture 3; capture 4 or capture 5)
"('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" +
// 2. simple (capture 6)
"((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" +
// 3. anything else (capture 2)
".*" +
")\\)|)",
// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
rwhitespace = new RegExp( whitespace + "+", "g" ),
rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),
rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ),
rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ),
rpseudo = new RegExp( pseudos ),
ridentifier = new RegExp( "^" + identifier + "$" ),
matchExpr = {
"ID": new RegExp( "^#(" + characterEncoding + ")" ),
"CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ),
"TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ),
"ATTR": new RegExp( "^" + attributes ),
"PSEUDO": new RegExp( "^" + pseudos ),
"CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace +
"*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +
"*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
"bool": new RegExp( "^(?:" + booleans + ")$", "i" ),
// For use in libraries implementing .is()
// We use this for POS matching in `select`
"needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" +
whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" )
},
rinputs = /^(?:input|select|textarea|button)$/i,
rheader = /^h\d$/i,
rnative = /^[^{]+\{\s*\[native \w/,
// Easily-parseable/retrievable ID or TAG or CLASS selectors
rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
rsibling = /[+~]/,
rescape = /'|\\/g,
// CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ),
funescape = function( _, escaped, escapedWhitespace ) {
var high = "0x" + escaped - 0x10000;
// NaN means non-codepoint
// Support: Firefox<24
// Workaround erroneous numeric interpretation of +"0x"
return high !== high || escapedWhitespace ?
escaped :
high < 0 ?
// BMP codepoint
String.fromCharCode( high + 0x10000 ) :
// Supplemental Plane codepoint (surrogate pair)
String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 );
},
// Used for iframes
// See setDocument()
// Removing the function wrapper causes a "Permission Denied"
// error in IE
unloadHandler = function() {
setDocument();
};
// Optimize for push.apply( _, NodeList )
try {
push.apply(
(arr = slice.call( preferredDoc.childNodes )),
preferredDoc.childNodes
);
// Support: Android<4.0
// Detect silently failing push.apply
arr[ preferredDoc.childNodes.length ].nodeType;
} catch ( e ) {
push = { apply: arr.length ?
// Leverage slice if possible
function( target, els ) {
push_native.apply( target, slice.call(els) );
} :
// Support: IE<9
// Otherwise append directly
function( target, els ) {
var j = target.length,
i = 0;
// Can't trust NodeList.length
while ( (target[j++] = els[i++]) ) {}
target.length = j - 1;
}
};
}
function Sizzle( selector, context, results, seed ) {
var match, elem, m, nodeType,
// QSA vars
i, groups, old, nid, newContext, newSelector;
if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) {
setDocument( context );
}
context = context || document;
results = results || [];
nodeType = context.nodeType;
if ( typeof selector !== "string" || !selector ||
nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) {
return results;
}
if ( !seed && documentIsHTML ) {
// Try to shortcut find operations when possible (e.g., not under DocumentFragment)
if ( nodeType !== 11 && (match = rquickExpr.exec( selector )) ) {
// Speed-up: Sizzle("#ID")
if ( (m = match[1]) ) {
if ( nodeType === 9 ) {
elem = context.getElementById( m );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document (jQuery #6963)
if ( elem && elem.parentNode ) {
// Handle the case where IE, Opera, and Webkit return items
// by name instead of ID
if ( elem.id === m ) {
results.push( elem );
return results;
}
} else {
return results;
}
} else {
// Context is not a document
if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) &&
contains( context, elem ) && elem.id === m ) {
results.push( elem );
return results;
}
}
// Speed-up: Sizzle("TAG")
} else if ( match[2] ) {
push.apply( results, context.getElementsByTagName( selector ) );
return results;
// Speed-up: Sizzle(".CLASS")
} else if ( (m = match[3]) && support.getElementsByClassName ) {
push.apply( results, context.getElementsByClassName( m ) );
return results;
}
}
// QSA path
if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) {
nid = old = expando;
newContext = context;
newSelector = nodeType !== 1 && selector;
// qSA works strangely on Element-rooted queries
// We can work around this by specifying an extra ID on the root
// and working up from there (Thanks to Andrew Dupont for the technique)
// IE 8 doesn't work on object elements
if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
groups = tokenize( selector );
if ( (old = context.getAttribute("id")) ) {
nid = old.replace( rescape, "\\$&" );
} else {
context.setAttribute( "id", nid );
}
nid = "[id='" + nid + "'] ";
i = groups.length;
while ( i-- ) {
groups[i] = nid + toSelector( groups[i] );
}
newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context;
newSelector = groups.join(",");
}
if ( newSelector ) {
try {
push.apply( results,
newContext.querySelectorAll( newSelector )
);
return results;
} catch(qsaError) {
} finally {
if ( !old ) {
context.removeAttribute("id");
}
}
}
}
}
// All others
return select( selector.replace( rtrim, "$1" ), context, results, seed );
}
/**
* Create key-value caches of limited size
* @returns {Function(string, Object)} Returns the Object data after storing it on itself with
* property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
* deleting the oldest entry
*/
function createCache() {
var keys = [];
function cache( key, value ) {
// Use (key + " ") to avoid collision with native prototype properties (see Issue #157)
if ( keys.push( key + " " ) > Expr.cacheLength ) {
// Only keep the most recent entries
delete cache[ keys.shift() ];
}
return (cache[ key + " " ] = value);
}
return cache;
}
/**
* Mark a function for special use by Sizzle
* @param {Function} fn The function to mark
*/
function markFunction( fn ) {
fn[ expando ] = true;
return fn;
}
/**
* Support testing using an element
* @param {Function} fn Passed the created div and expects a boolean result
*/
function assert( fn ) {
var div = document.createElement("div");
try {
return !!fn( div );
} catch (e) {
return false;
} finally {
// Remove from its parent by default
if ( div.parentNode ) {
div.parentNode.removeChild( div );
}
// release memory in IE
div = null;
}
}
/**
* Adds the same handler for all of the specified attrs
* @param {String} attrs Pipe-separated list of attributes
* @param {Function} handler The method that will be applied
*/
function addHandle( attrs, handler ) {
var arr = attrs.split("|"),
i = attrs.length;
while ( i-- ) {
Expr.attrHandle[ arr[i] ] = handler;
}
}
/**
* Checks document order of two siblings
* @param {Element} a
* @param {Element} b
* @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b
*/
function siblingCheck( a, b ) {
var cur = b && a,
diff = cur && a.nodeType === 1 && b.nodeType === 1 &&
( ~b.sourceIndex || MAX_NEGATIVE ) -
( ~a.sourceIndex || MAX_NEGATIVE );
// Use IE sourceIndex if available on both nodes
if ( diff ) {
return diff;
}
// Check if b follows a
if ( cur ) {
while ( (cur = cur.nextSibling) ) {
if ( cur === b ) {
return -1;
}
}
}
return a ? 1 : -1;
}
/**
* Returns a function to use in pseudos for input types
* @param {String} type
*/
function createInputPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === type;
};
}
/**
* Returns a function to use in pseudos for buttons
* @param {String} type
*/
function createButtonPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && elem.type === type;
};
}
/**
* Returns a function to use in pseudos for positionals
* @param {Function} fn
*/
function createPositionalPseudo( fn ) {
return markFunction(function( argument ) {
argument = +argument;
return markFunction(function( seed, matches ) {
var j,
matchIndexes = fn( [], seed.length, argument ),
i = matchIndexes.length;
// Match elements found at the specified indexes
while ( i-- ) {
if ( seed[ (j = matchIndexes[i]) ] ) {
seed[j] = !(matches[j] = seed[j]);
}
}
});
});
}
/**
* Checks a node for validity as a Sizzle context
* @param {Element|Object=} context
* @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value
*/
function testContext( context ) {
return context && typeof context.getElementsByTagName !== "undefined" && context;
}
// Expose support vars for convenience
support = Sizzle.support = {};
/**
* Detects XML nodes
* @param {Element|Object} elem An element or a document
* @returns {Boolean} True iff elem is a non-HTML XML node
*/
isXML = Sizzle.isXML = function( elem ) {
// documentElement is verified for cases where it doesn't yet exist
// (such as loading iframes in IE - #4833)
var documentElement = elem && (elem.ownerDocument || elem).documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
/**
* Sets document-related variables once based on the current document
* @param {Element|Object} [doc] An element or document object to use to set the document
* @returns {Object} Returns the current document
*/
setDocument = Sizzle.setDocument = function( node ) {
var hasCompare, parent,
doc = node ? node.ownerDocument || node : preferredDoc;
// If no document and documentElement is available, return
if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) {
return document;
}
// Set our document
document = doc;
docElem = doc.documentElement;
parent = doc.defaultView;
// Support: IE>8
// If iframe document is assigned to "document" variable and if iframe has been reloaded,
// IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936
// IE6-8 do not support the defaultView property so parent will be undefined
if ( parent && parent !== parent.top ) {
// IE11 does not have attachEvent, so all must suffer
if ( parent.addEventListener ) {
parent.addEventListener( "unload", unloadHandler, false );
} else if ( parent.attachEvent ) {
parent.attachEvent( "onunload", unloadHandler );
}
}
/* Support tests
---------------------------------------------------------------------- */
documentIsHTML = !isXML( doc );
/* Attributes
---------------------------------------------------------------------- */
// Support: IE<8
// Verify that getAttribute really returns attributes and not properties
// (excepting IE8 booleans)
support.attributes = assert(function( div ) {
div.className = "i";
return !div.getAttribute("className");
});
/* getElement(s)By*
---------------------------------------------------------------------- */
// Check if getElementsByTagName("*") returns only elements
support.getElementsByTagName = assert(function( div ) {
div.appendChild( doc.createComment("") );
return !div.getElementsByTagName("*").length;
});
// Support: IE<9
support.getElementsByClassName = rnative.test( doc.getElementsByClassName );
// Support: IE<10
// Check if getElementById returns elements by name
// The broken getElementById methods don't pick up programatically-set names,
// so use a roundabout getElementsByName test
support.getById = assert(function( div ) {
docElem.appendChild( div ).id = expando;
return !doc.getElementsByName || !doc.getElementsByName( expando ).length;
});
// ID find and filter
if ( support.getById ) {
Expr.find["ID"] = function( id, context ) {
if ( typeof context.getElementById !== "undefined" && documentIsHTML ) {
var m = context.getElementById( id );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
return m && m.parentNode ? [ m ] : [];
}
};
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
return elem.getAttribute("id") === attrId;
};
};
} else {
// Support: IE6/7
// getElementById is not reliable as a find shortcut
delete Expr.find["ID"];
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id");
return node && node.value === attrId;
};
};
}
// Tag
Expr.find["TAG"] = support.getElementsByTagName ?
function( tag, context ) {
if ( typeof context.getElementsByTagName !== "undefined" ) {
return context.getElementsByTagName( tag );
// DocumentFragment nodes don't have gEBTN
} else if ( support.qsa ) {
return context.querySelectorAll( tag );
}
} :
function( tag, context ) {
var elem,
tmp = [],
i = 0,
// By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too
results = context.getElementsByTagName( tag );
// Filter out possible comments
if ( tag === "*" ) {
while ( (elem = results[i++]) ) {
if ( elem.nodeType === 1 ) {
tmp.push( elem );
}
}
return tmp;
}
return results;
};
// Class
Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) {
if ( documentIsHTML ) {
return context.getElementsByClassName( className );
}
};
/* QSA/matchesSelector
---------------------------------------------------------------------- */
// QSA and matchesSelector support
// matchesSelector(:active) reports false when true (IE9/Opera 11.5)
rbuggyMatches = [];
// qSa(:focus) reports false when true (Chrome 21)
// We allow this because of a bug in IE8/9 that throws an error
// whenever `document.activeElement` is accessed on an iframe
// So, we allow :focus to pass through QSA all the time to avoid the IE error
// See http://bugs.jquery.com/ticket/13378
rbuggyQSA = [];
if ( (support.qsa = rnative.test( doc.querySelectorAll )) ) {
// Build QSA regex
// Regex strategy adopted from Diego Perini
assert(function( div ) {
// Select is set to empty string on purpose
// This is to test IE's treatment of not explicitly
// setting a boolean content attribute,
// since its presence should be enough
// http://bugs.jquery.com/ticket/12359
docElem.appendChild( div ).innerHTML = "<a id='" + expando + "'></a>" +
"<select id='" + expando + "-\f]' msallowcapture=''>" +
"<option selected=''></option></select>";
// Support: IE8, Opera 11-12.16
// Nothing should be selected when empty strings follow ^= or $= or *=
// The test attribute must be unknown in Opera but "safe" for WinRT
// http://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section
if ( div.querySelectorAll("[msallowcapture^='']").length ) {
rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" );
}
// Support: IE8
// Boolean attributes and "value" are not treated correctly
if ( !div.querySelectorAll("[selected]").length ) {
rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" );
}
// Support: Chrome<29, Android<4.2+, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.7+
if ( !div.querySelectorAll( "[id~=" + expando + "-]" ).length ) {
rbuggyQSA.push("~=");
}
// Webkit/Opera - :checked should return selected option elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
// IE8 throws error here and will not see later tests
if ( !div.querySelectorAll(":checked").length ) {
rbuggyQSA.push(":checked");
}
// Support: Safari 8+, iOS 8+
// https://bugs.webkit.org/show_bug.cgi?id=136851
// In-page `selector#id sibing-combinator selector` fails
if ( !div.querySelectorAll( "a#" + expando + "+*" ).length ) {
rbuggyQSA.push(".#.+[+~]");
}
});
assert(function( div ) {
// Support: Windows 8 Native Apps
// The type and name attributes are restricted during .innerHTML assignment
var input = doc.createElement("input");
input.setAttribute( "type", "hidden" );
div.appendChild( input ).setAttribute( "name", "D" );
// Support: IE8
// Enforce case-sensitivity of name attribute
if ( div.querySelectorAll("[name=d]").length ) {
rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" );
}
// FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
// IE8 throws error here and will not see later tests
if ( !div.querySelectorAll(":enabled").length ) {
rbuggyQSA.push( ":enabled", ":disabled" );
}
// Opera 10-11 does not throw on post-comma invalid pseudos
div.querySelectorAll("*,:x");
rbuggyQSA.push(",.*:");
});
}
if ( (support.matchesSelector = rnative.test( (matches = docElem.matches ||
docElem.webkitMatchesSelector ||
docElem.mozMatchesSelector ||
docElem.oMatchesSelector ||
docElem.msMatchesSelector) )) ) {
assert(function( div ) {
// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9)
support.disconnectedMatch = matches.call( div, "div" );
// This should fail with an exception
// Gecko does not error, returns false instead
matches.call( div, "[s!='']:x" );
rbuggyMatches.push( "!=", pseudos );
});
}
rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") );
rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") );
/* Contains
---------------------------------------------------------------------- */
hasCompare = rnative.test( docElem.compareDocumentPosition );
// Element contains another
// Purposefully does not implement inclusive descendent
// As in, an element does not contain itself
contains = hasCompare || rnative.test( docElem.contains ) ?
function( a, b ) {
var adown = a.nodeType === 9 ? a.documentElement : a,
bup = b && b.parentNode;
return a === bup || !!( bup && bup.nodeType === 1 && (
adown.contains ?
adown.contains( bup ) :
a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
));
} :
function( a, b ) {
if ( b ) {
while ( (b = b.parentNode) ) {
if ( b === a ) {
return true;
}
}
}
return false;
};
/* Sorting
---------------------------------------------------------------------- */
// Document order sorting
sortOrder = hasCompare ?
function( a, b ) {
// Flag for duplicate removal
if ( a === b ) {
hasDuplicate = true;
return 0;
}
// Sort on method existence if only one input has compareDocumentPosition
var compare = !a.compareDocumentPosition - !b.compareDocumentPosition;
if ( compare ) {
return compare;
}
// Calculate position if both inputs belong to the same document
compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ?
a.compareDocumentPosition( b ) :
// Otherwise we know they are disconnected
1;
// Disconnected nodes
if ( compare & 1 ||
(!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) {
// Choose the first element that is related to our preferred document
if ( a === doc || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) {
return -1;
}
if ( b === doc || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) {
return 1;
}
// Maintain original order
return sortInput ?
( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) :
0;
}
return compare & 4 ? -1 : 1;
} :
function( a, b ) {
// Exit early if the nodes are identical
if ( a === b ) {
hasDuplicate = true;
return 0;
}
var cur,
i = 0,
aup = a.parentNode,
bup = b.parentNode,
ap = [ a ],
bp = [ b ];
// Parentless nodes are either documents or disconnected
if ( !aup || !bup ) {
return a === doc ? -1 :
b === doc ? 1 :
aup ? -1 :
bup ? 1 :
sortInput ?
( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) :
0;
// If the nodes are siblings, we can do a quick check
} else if ( aup === bup ) {
return siblingCheck( a, b );
}
// Otherwise we need full lists of their ancestors for comparison
cur = a;
while ( (cur = cur.parentNode) ) {
ap.unshift( cur );
}
cur = b;
while ( (cur = cur.parentNode) ) {
bp.unshift( cur );
}
// Walk down the tree looking for a discrepancy
while ( ap[i] === bp[i] ) {
i++;
}
return i ?
// Do a sibling check if the nodes have a common ancestor
siblingCheck( ap[i], bp[i] ) :
// Otherwise nodes in our document sort first
ap[i] === preferredDoc ? -1 :
bp[i] === preferredDoc ? 1 :
0;
};
return doc;
};
Sizzle.matches = function( expr, elements ) {
return Sizzle( expr, null, null, elements );
};
Sizzle.matchesSelector = function( elem, expr ) {
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
// Make sure that attribute selectors are quoted
expr = expr.replace( rattributeQuotes, "='$1']" );
if ( support.matchesSelector && documentIsHTML &&
( !rbuggyMatches || !rbuggyMatches.test( expr ) ) &&
( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) {
try {
var ret = matches.call( elem, expr );
// IE 9's matchesSelector returns false on disconnected nodes
if ( ret || support.disconnectedMatch ||
// As well, disconnected nodes are said to be in a document
// fragment in IE 9
elem.document && elem.document.nodeType !== 11 ) {
return ret;
}
} catch (e) {}
}
return Sizzle( expr, document, null, [ elem ] ).length > 0;
};
Sizzle.contains = function( context, elem ) {
// Set document vars if needed
if ( ( context.ownerDocument || context ) !== document ) {
setDocument( context );
}
return contains( context, elem );
};
Sizzle.attr = function( elem, name ) {
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
var fn = Expr.attrHandle[ name.toLowerCase() ],
// Don't get fooled by Object.prototype properties (jQuery #13807)
val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ?
fn( elem, name, !documentIsHTML ) :
undefined;
return val !== undefined ?
val :
support.attributes || !documentIsHTML ?
elem.getAttribute( name ) :
(val = elem.getAttributeNode(name)) && val.specified ?
val.value :
null;
};
Sizzle.error = function( msg ) {
throw new Error( "Syntax error, unrecognized expression: " + msg );
};
/**
* Document sorting and removing duplicates
* @param {ArrayLike} results
*/
Sizzle.uniqueSort = function( results ) {
var elem,
duplicates = [],
j = 0,
i = 0;
// Unless we *know* we can detect duplicates, assume their presence
hasDuplicate = !support.detectDuplicates;
sortInput = !support.sortStable && results.slice( 0 );
results.sort( sortOrder );
if ( hasDuplicate ) {
while ( (elem = results[i++]) ) {
if ( elem === results[ i ] ) {
j = duplicates.push( i );
}
}
while ( j-- ) {
results.splice( duplicates[ j ], 1 );
}
}
// Clear input after sorting to release objects
// See https://github.com/jquery/sizzle/pull/225
sortInput = null;
return results;
};
/**
* Utility function for retrieving the text value of an array of DOM nodes
* @param {Array|Element} elem
*/
getText = Sizzle.getText = function( elem ) {
var node,
ret = "",
i = 0,
nodeType = elem.nodeType;
if ( !nodeType ) {
// If no nodeType, this is expected to be an array
while ( (node = elem[i++]) ) {
// Do not traverse comment nodes
ret += getText( node );
}
} else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
// Use textContent for elements
// innerText usage removed for consistency of new lines (jQuery #11153)
if ( typeof elem.textContent === "string" ) {
return elem.textContent;
} else {
// Traverse its children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
ret += getText( elem );
}
}
} else if ( nodeType === 3 || nodeType === 4 ) {
return elem.nodeValue;
}
// Do not include comment or processing instruction nodes
return ret;
};
Expr = Sizzle.selectors = {
// Can be adjusted by the user
cacheLength: 50,
createPseudo: markFunction,
match: matchExpr,
attrHandle: {},
find: {},
relative: {
">": { dir: "parentNode", first: true },
" ": { dir: "parentNode" },
"+": { dir: "previousSibling", first: true },
"~": { dir: "previousSibling" }
},
preFilter: {
"ATTR": function( match ) {
match[1] = match[1].replace( runescape, funescape );
// Move the given value to match[3] whether quoted or unquoted
match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape );
if ( match[2] === "~=" ) {
match[3] = " " + match[3] + " ";
}
return match.slice( 0, 4 );
},
"CHILD": function( match ) {
/* matches from matchExpr["CHILD"]
1 type (only|nth|...)
2 what (child|of-type)
3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
4 xn-component of xn+y argument ([+-]?\d*n|)
5 sign of xn-component
6 x of xn-component
7 sign of y-component
8 y of y-component
*/
match[1] = match[1].toLowerCase();
if ( match[1].slice( 0, 3 ) === "nth" ) {
// nth-* requires argument
if ( !match[3] ) {
Sizzle.error( match[0] );
}
// numeric x and y parameters for Expr.filter.CHILD
// remember that false/true cast respectively to 0/1
match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) );
match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" );
// other types prohibit arguments
} else if ( match[3] ) {
Sizzle.error( match[0] );
}
return match;
},
"PSEUDO": function( match ) {
var excess,
unquoted = !match[6] && match[2];
if ( matchExpr["CHILD"].test( match[0] ) ) {
return null;
}
// Accept quoted arguments as-is
if ( match[3] ) {
match[2] = match[4] || match[5] || "";
// Strip excess characters from unquoted arguments
} else if ( unquoted && rpseudo.test( unquoted ) &&
// Get excess from tokenize (recursively)
(excess = tokenize( unquoted, true )) &&
// advance to the next closing parenthesis
(excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) {
// excess is a negative index
match[0] = match[0].slice( 0, excess );
match[2] = unquoted.slice( 0, excess );
}
// Return only captures needed by the pseudo filter method (type and argument)
return match.slice( 0, 3 );
}
},
filter: {
"TAG": function( nodeNameSelector ) {
var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase();
return nodeNameSelector === "*" ?
function() { return true; } :
function( elem ) {
return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
};
},
"CLASS": function( className ) {
var pattern = classCache[ className + " " ];
return pattern ||
(pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) &&
classCache( className, function( elem ) {
return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== "undefined" && elem.getAttribute("class") || "" );
});
},
"ATTR": function( name, operator, check ) {
return function( elem ) {
var result = Sizzle.attr( elem, name );
if ( result == null ) {
return operator === "!=";
}
if ( !operator ) {
return true;
}
result += "";
return operator === "=" ? result === check :
operator === "!=" ? result !== check :
operator === "^=" ? check && result.indexOf( check ) === 0 :
operator === "*=" ? check && result.indexOf( check ) > -1 :
operator === "$=" ? check && result.slice( -check.length ) === check :
operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 :
operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" :
false;
};
},
"CHILD": function( type, what, argument, first, last ) {
var simple = type.slice( 0, 3 ) !== "nth",
forward = type.slice( -4 ) !== "last",
ofType = what === "of-type";
return first === 1 && last === 0 ?
// Shortcut for :nth-*(n)
function( elem ) {
return !!elem.parentNode;
} :
function( elem, context, xml ) {
var cache, outerCache, node, diff, nodeIndex, start,
dir = simple !== forward ? "nextSibling" : "previousSibling",
parent = elem.parentNode,
name = ofType && elem.nodeName.toLowerCase(),
useCache = !xml && !ofType;
if ( parent ) {
// :(first|last|only)-(child|of-type)
if ( simple ) {
while ( dir ) {
node = elem;
while ( (node = node[ dir ]) ) {
if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) {
return false;
}
}
// Reverse direction for :only-* (if we haven't yet done so)
start = dir = type === "only" && !start && "nextSibling";
}
return true;
}
start = [ forward ? parent.firstChild : parent.lastChild ];
// non-xml :nth-child(...) stores cache data on `parent`
if ( forward && useCache ) {
// Seek `elem` from a previously-cached index
outerCache = parent[ expando ] || (parent[ expando ] = {});
cache = outerCache[ type ] || [];
nodeIndex = cache[0] === dirruns && cache[1];
diff = cache[0] === dirruns && cache[2];
node = nodeIndex && parent.childNodes[ nodeIndex ];
while ( (node = ++nodeIndex && node && node[ dir ] ||
// Fallback to seeking `elem` from the start
(diff = nodeIndex = 0) || start.pop()) ) {
// When found, cache indexes on `parent` and break
if ( node.nodeType === 1 && ++diff && node === elem ) {
outerCache[ type ] = [ dirruns, nodeIndex, diff ];
break;
}
}
// Use previously-cached element index if available
} else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) {
diff = cache[1];
// xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...)
} else {
// Use the same loop as above to seek `elem` from the start
while ( (node = ++nodeIndex && node && node[ dir ] ||
(diff = nodeIndex = 0) || start.pop()) ) {
if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) {
// Cache the index of each encountered element
if ( useCache ) {
(node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ];
}
if ( node === elem ) {
break;
}
}
}
}
// Incorporate the offset, then check against cycle size
diff -= last;
return diff === first || ( diff % first === 0 && diff / first >= 0 );
}
};
},
"PSEUDO": function( pseudo, argument ) {
// pseudo-class names are case-insensitive
// http://www.w3.org/TR/selectors/#pseudo-classes
// Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
// Remember that setFilters inherits from pseudos
var args,
fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
Sizzle.error( "unsupported pseudo: " + pseudo );
// The user may use createPseudo to indicate that
// arguments are needed to create the filter function
// just as Sizzle does
if ( fn[ expando ] ) {
return fn( argument );
}
// But maintain support for old signatures
if ( fn.length > 1 ) {
args = [ pseudo, pseudo, "", argument ];
return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?
markFunction(function( seed, matches ) {
var idx,
matched = fn( seed, argument ),
i = matched.length;
while ( i-- ) {
idx = indexOf( seed, matched[i] );
seed[ idx ] = !( matches[ idx ] = matched[i] );
}
}) :
function( elem ) {
return fn( elem, 0, args );
};
}
return fn;
}
},
pseudos: {
// Potentially complex pseudos
"not": markFunction(function( selector ) {
// Trim the selector passed to compile
// to avoid treating leading and trailing
// spaces as combinators
var input = [],
results = [],
matcher = compile( selector.replace( rtrim, "$1" ) );
return matcher[ expando ] ?
markFunction(function( seed, matches, context, xml ) {
var elem,
unmatched = matcher( seed, null, xml, [] ),
i = seed.length;
// Match elements unmatched by `matcher`
while ( i-- ) {
if ( (elem = unmatched[i]) ) {
seed[i] = !(matches[i] = elem);
}
}
}) :
function( elem, context, xml ) {
input[0] = elem;
matcher( input, null, xml, results );
// Don't keep the element (issue #299)
input[0] = null;
return !results.pop();
};
}),
"has": markFunction(function( selector ) {
return function( elem ) {
return Sizzle( selector, elem ).length > 0;
};
}),
"contains": markFunction(function( text ) {
text = text.replace( runescape, funescape );
return function( elem ) {
return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1;
};
}),
// "Whether an element is represented by a :lang() selector
// is based solely on the element's language value
// being equal to the identifier C,
// or beginning with the identifier C immediately followed by "-".
// The matching of C against the element's language value is performed case-insensitively.
// The identifier C does not have to be a valid language name."
// http://www.w3.org/TR/selectors/#lang-pseudo
"lang": markFunction( function( lang ) {
// lang value must be a valid identifier
if ( !ridentifier.test(lang || "") ) {
Sizzle.error( "unsupported lang: " + lang );
}
lang = lang.replace( runescape, funescape ).toLowerCase();
return function( elem ) {
var elemLang;
do {
if ( (elemLang = documentIsHTML ?
elem.lang :
elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) {
elemLang = elemLang.toLowerCase();
return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0;
}
} while ( (elem = elem.parentNode) && elem.nodeType === 1 );
return false;
};
}),
// Miscellaneous
"target": function( elem ) {
var hash = window.location && window.location.hash;
return hash && hash.slice( 1 ) === elem.id;
},
"root": function( elem ) {
return elem === docElem;
},
"focus": function( elem ) {
return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
},
// Boolean properties
"enabled": function( elem ) {
return elem.disabled === false;
},
"disabled": function( elem ) {
return elem.disabled === true;
},
"checked": function( elem ) {
// In CSS3, :checked should return both checked and selected elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
var nodeName = elem.nodeName.toLowerCase();
return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
},
"selected": function( elem ) {
// Accessing this property makes selected-by-default
// options in Safari work properly
if ( elem.parentNode ) {
elem.parentNode.selectedIndex;
}
return elem.selected === true;
},
// Contents
"empty": function( elem ) {
// http://www.w3.org/TR/selectors/#empty-pseudo
// :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5),
// but not by others (comment: 8; processing instruction: 7; etc.)
// nodeType < 6 works because attributes (2) do not appear as children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
if ( elem.nodeType < 6 ) {
return false;
}
}
return true;
},
"parent": function( elem ) {
return !Expr.pseudos["empty"]( elem );
},
// Element/input types
"header": function( elem ) {
return rheader.test( elem.nodeName );
},
"input": function( elem ) {
return rinputs.test( elem.nodeName );
},
"button": function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === "button" || name === "button";
},
"text": function( elem ) {
var attr;
return elem.nodeName.toLowerCase() === "input" &&
elem.type === "text" &&
// Support: IE<8
// New HTML5 attribute values (e.g., "search") appear with elem.type === "text"
( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" );
},
// Position-in-collection
"first": createPositionalPseudo(function() {
return [ 0 ];
}),
"last": createPositionalPseudo(function( matchIndexes, length ) {
return [ length - 1 ];
}),
"eq": createPositionalPseudo(function( matchIndexes, length, argument ) {
return [ argument < 0 ? argument + length : argument ];
}),
"even": createPositionalPseudo(function( matchIndexes, length ) {
var i = 0;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"odd": createPositionalPseudo(function( matchIndexes, length ) {
var i = 1;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"lt": createPositionalPseudo(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; --i >= 0; ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"gt": createPositionalPseudo(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; ++i < length; ) {
matchIndexes.push( i );
}
return matchIndexes;
})
}
};
Expr.pseudos["nth"] = Expr.pseudos["eq"];
// Add button/input type pseudos
for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) {
Expr.pseudos[ i ] = createInputPseudo( i );
}
for ( i in { submit: true, reset: true } ) {
Expr.pseudos[ i ] = createButtonPseudo( i );
}
// Easy API for creating new setFilters
function setFilters() {}
setFilters.prototype = Expr.filters = Expr.pseudos;
Expr.setFilters = new setFilters();
tokenize = Sizzle.tokenize = function( selector, parseOnly ) {
var matched, match, tokens, type,
soFar, groups, preFilters,
cached = tokenCache[ selector + " " ];
if ( cached ) {
return parseOnly ? 0 : cached.slice( 0 );
}
soFar = selector;
groups = [];
preFilters = Expr.preFilter;
while ( soFar ) {
// Comma and first run
if ( !matched || (match = rcomma.exec( soFar )) ) {
if ( match ) {
// Don't consume trailing commas as valid
soFar = soFar.slice( match[0].length ) || soFar;
}
groups.push( (tokens = []) );
}
matched = false;
// Combinators
if ( (match = rcombinators.exec( soFar )) ) {
matched = match.shift();
tokens.push({
value: matched,
// Cast descendant combinators to space
type: match[0].replace( rtrim, " " )
});
soFar = soFar.slice( matched.length );
}
// Filters
for ( type in Expr.filter ) {
if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
(match = preFilters[ type ]( match ))) ) {
matched = match.shift();
tokens.push({
value: matched,
type: type,
matches: match
});
soFar = soFar.slice( matched.length );
}
}
if ( !matched ) {
break;
}
}
// Return the length of the invalid excess
// if we're just parsing
// Otherwise, throw an error or return tokens
return parseOnly ?
soFar.length :
soFar ?
Sizzle.error( selector ) :
// Cache the tokens
tokenCache( selector, groups ).slice( 0 );
};
function toSelector( tokens ) {
var i = 0,
len = tokens.length,
selector = "";
for ( ; i < len; i++ ) {
selector += tokens[i].value;
}
return selector;
}
function addCombinator( matcher, combinator, base ) {
var dir = combinator.dir,
checkNonElements = base && dir === "parentNode",
doneName = done++;
return combinator.first ?
// Check against closest ancestor/preceding element
function( elem, context, xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
return matcher( elem, context, xml );
}
}
} :
// Check against all ancestor/preceding elements
function( elem, context, xml ) {
var oldCache, outerCache,
newCache = [ dirruns, doneName ];
// We can't set arbitrary data on XML nodes, so they don't benefit from dir caching
if ( xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
if ( matcher( elem, context, xml ) ) {
return true;
}
}
}
} else {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
outerCache = elem[ expando ] || (elem[ expando ] = {});
if ( (oldCache = outerCache[ dir ]) &&
oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) {
// Assign to newCache so results back-propagate to previous elements
return (newCache[ 2 ] = oldCache[ 2 ]);
} else {
// Reuse newcache so results back-propagate to previous elements
outerCache[ dir ] = newCache;
// A match means we're done; a fail means we have to keep checking
if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) {
return true;
}
}
}
}
}
};
}
function elementMatcher( matchers ) {
return matchers.length > 1 ?
function( elem, context, xml ) {
var i = matchers.length;
while ( i-- ) {
if ( !matchers[i]( elem, context, xml ) ) {
return false;
}
}
return true;
} :
matchers[0];
}
function multipleContexts( selector, contexts, results ) {
var i = 0,
len = contexts.length;
for ( ; i < len; i++ ) {
Sizzle( selector, contexts[i], results );
}
return results;
}
function condense( unmatched, map, filter, context, xml ) {
var elem,
newUnmatched = [],
i = 0,
len = unmatched.length,
mapped = map != null;
for ( ; i < len; i++ ) {
if ( (elem = unmatched[i]) ) {
if ( !filter || filter( elem, context, xml ) ) {
newUnmatched.push( elem );
if ( mapped ) {
map.push( i );
}
}
}
}
return newUnmatched;
}
function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
if ( postFilter && !postFilter[ expando ] ) {
postFilter = setMatcher( postFilter );
}
if ( postFinder && !postFinder[ expando ] ) {
postFinder = setMatcher( postFinder, postSelector );
}
return markFunction(function( seed, results, context, xml ) {
var temp, i, elem,
preMap = [],
postMap = [],
preexisting = results.length,
// Get initial elements from seed or context
elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ),
// Prefilter to get matcher input, preserving a map for seed-results synchronization
matcherIn = preFilter && ( seed || !selector ) ?
condense( elems, preMap, preFilter, context, xml ) :
elems,
matcherOut = matcher ?
// If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
postFinder || ( seed ? preFilter : preexisting || postFilter ) ?
// ...intermediate processing is necessary
[] :
// ...otherwise use results directly
results :
matcherIn;
// Find primary matches
if ( matcher ) {
matcher( matcherIn, matcherOut, context, xml );
}
// Apply postFilter
if ( postFilter ) {
temp = condense( matcherOut, postMap );
postFilter( temp, [], context, xml );
// Un-match failing elements by moving them back to matcherIn
i = temp.length;
while ( i-- ) {
if ( (elem = temp[i]) ) {
matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem);
}
}
}
if ( seed ) {
if ( postFinder || preFilter ) {
if ( postFinder ) {
// Get the final matcherOut by condensing this intermediate into postFinder contexts
temp = [];
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) ) {
// Restore matcherIn since elem is not yet a final match
temp.push( (matcherIn[i] = elem) );
}
}
postFinder( null, (matcherOut = []), temp, xml );
}
// Move matched elements from seed to results to keep them synchronized
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) &&
(temp = postFinder ? indexOf( seed, elem ) : preMap[i]) > -1 ) {
seed[temp] = !(results[temp] = elem);
}
}
}
// Add elements to results, through postFinder if defined
} else {
matcherOut = condense(
matcherOut === results ?
matcherOut.splice( preexisting, matcherOut.length ) :
matcherOut
);
if ( postFinder ) {
postFinder( null, results, matcherOut, xml );
} else {
push.apply( results, matcherOut );
}
}
});
}
function matcherFromTokens( tokens ) {
var checkContext, matcher, j,
len = tokens.length,
leadingRelative = Expr.relative[ tokens[0].type ],
implicitRelative = leadingRelative || Expr.relative[" "],
i = leadingRelative ? 1 : 0,
// The foundational matcher ensures that elements are reachable from top-level context(s)
matchContext = addCombinator( function( elem ) {
return elem === checkContext;
}, implicitRelative, true ),
matchAnyContext = addCombinator( function( elem ) {
return indexOf( checkContext, elem ) > -1;
}, implicitRelative, true ),
matchers = [ function( elem, context, xml ) {
var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
(checkContext = context).nodeType ?
matchContext( elem, context, xml ) :
matchAnyContext( elem, context, xml ) );
// Avoid hanging onto element (issue #299)
checkContext = null;
return ret;
} ];
for ( ; i < len; i++ ) {
if ( (matcher = Expr.relative[ tokens[i].type ]) ) {
matchers = [ addCombinator(elementMatcher( matchers ), matcher) ];
} else {
matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches );
// Return special upon seeing a positional matcher
if ( matcher[ expando ] ) {
// Find the next relative operator (if any) for proper handling
j = ++i;
for ( ; j < len; j++ ) {
if ( Expr.relative[ tokens[j].type ] ) {
break;
}
}
return setMatcher(
i > 1 && elementMatcher( matchers ),
i > 1 && toSelector(
// If the preceding token was a descendant combinator, insert an implicit any-element `*`
tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" })
).replace( rtrim, "$1" ),
matcher,
i < j && matcherFromTokens( tokens.slice( i, j ) ),
j < len && matcherFromTokens( (tokens = tokens.slice( j )) ),
j < len && toSelector( tokens )
);
}
matchers.push( matcher );
}
}
return elementMatcher( matchers );
}
function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
var bySet = setMatchers.length > 0,
byElement = elementMatchers.length > 0,
superMatcher = function( seed, context, xml, results, outermost ) {
var elem, j, matcher,
matchedCount = 0,
i = "0",
unmatched = seed && [],
setMatched = [],
contextBackup = outermostContext,
// We must always have either seed elements or outermost context
elems = seed || byElement && Expr.find["TAG"]( "*", outermost ),
// Use integer dirruns iff this is the outermost matcher
dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1),
len = elems.length;
if ( outermost ) {
outermostContext = context !== document && context;
}
// Add elements passing elementMatchers directly to results
// Keep `i` a string if there are no elements so `matchedCount` will be "00" below
// Support: IE<9, Safari
// Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id
for ( ; i !== len && (elem = elems[i]) != null; i++ ) {
if ( byElement && elem ) {
j = 0;
while ( (matcher = elementMatchers[j++]) ) {
if ( matcher( elem, context, xml ) ) {
results.push( elem );
break;
}
}
if ( outermost ) {
dirruns = dirrunsUnique;
}
}
// Track unmatched elements for set filters
if ( bySet ) {
// They will have gone through all possible matchers
if ( (elem = !matcher && elem) ) {
matchedCount--;
}
// Lengthen the array for every element, matched or not
if ( seed ) {
unmatched.push( elem );
}
}
}
// Apply set filters to unmatched elements
matchedCount += i;
if ( bySet && i !== matchedCount ) {
j = 0;
while ( (matcher = setMatchers[j++]) ) {
matcher( unmatched, setMatched, context, xml );
}
if ( seed ) {
// Reintegrate element matches to eliminate the need for sorting
if ( matchedCount > 0 ) {
while ( i-- ) {
if ( !(unmatched[i] || setMatched[i]) ) {
setMatched[i] = pop.call( results );
}
}
}
// Discard index placeholder values to get only actual matches
setMatched = condense( setMatched );
}
// Add matches to results
push.apply( results, setMatched );
// Seedless set matches succeeding multiple successful matchers stipulate sorting
if ( outermost && !seed && setMatched.length > 0 &&
( matchedCount + setMatchers.length ) > 1 ) {
Sizzle.uniqueSort( results );
}
}
// Override manipulation of globals by nested matchers
if ( outermost ) {
dirruns = dirrunsUnique;
outermostContext = contextBackup;
}
return unmatched;
};
return bySet ?
markFunction( superMatcher ) :
superMatcher;
}
compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) {
var i,
setMatchers = [],
elementMatchers = [],
cached = compilerCache[ selector + " " ];
if ( !cached ) {
// Generate a function of recursive functions that can be used to check each element
if ( !match ) {
match = tokenize( selector );
}
i = match.length;
while ( i-- ) {
cached = matcherFromTokens( match[i] );
if ( cached[ expando ] ) {
setMatchers.push( cached );
} else {
elementMatchers.push( cached );
}
}
// Cache the compiled function
cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );
// Save selector and tokenization
cached.selector = selector;
}
return cached;
};
/**
* A low-level selection function that works with Sizzle's compiled
* selector functions
* @param {String|Function} selector A selector or a pre-compiled
* selector function built with Sizzle.compile
* @param {Element} context
* @param {Array} [results]
* @param {Array} [seed] A set of elements to match against
*/
select = Sizzle.select = function( selector, context, results, seed ) {
var i, tokens, token, type, find,
compiled = typeof selector === "function" && selector,
match = !seed && tokenize( (selector = compiled.selector || selector) );
results = results || [];
// Try to minimize operations if there is no seed and only one group
if ( match.length === 1 ) {
// Take a shortcut and set the context if the root selector is an ID
tokens = match[0] = match[0].slice( 0 );
if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
support.getById && context.nodeType === 9 && documentIsHTML &&
Expr.relative[ tokens[1].type ] ) {
context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0];
if ( !context ) {
return results;
// Precompiled matchers will still doLogin ancestry, so step up a level
} else if ( compiled ) {
context = context.parentNode;
}
selector = selector.slice( tokens.shift().value.length );
}
// Fetch a seed set for right-to-left matching
i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length;
while ( i-- ) {
token = tokens[i];
// Abort if we hit a combinator
if ( Expr.relative[ (type = token.type) ] ) {
break;
}
if ( (find = Expr.find[ type ]) ) {
// Search, expanding context for leading sibling combinators
if ( (seed = find(
token.matches[0].replace( runescape, funescape ),
rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context
)) ) {
// If seed is empty or no tokens remain, we can return early
tokens.splice( i, 1 );
selector = seed.length && toSelector( tokens );
if ( !selector ) {
push.apply( results, seed );
return results;
}
break;
}
}
}
}
// Compile and execute a filtering function if one is not provided
// Provide `match` to avoid retokenization if we modified the selector above
( compiled || compile( selector, match ) )(
seed,
context,
!documentIsHTML,
results,
rsibling.test( selector ) && testContext( context.parentNode ) || context
);
return results;
};
// One-time assignments
// Sort stability
support.sortStable = expando.split("").sort( sortOrder ).join("") === expando;
// Support: Chrome 14-35+
// Always assume duplicates if they aren't passed to the comparison function
support.detectDuplicates = !!hasDuplicate;
// Initialize against the default document
setDocument();
// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27)
// Detached nodes confoundingly follow *each other*
support.sortDetached = assert(function( div1 ) {
// Should return 1, but returns 4 (following)
return div1.compareDocumentPosition( document.createElement("div") ) & 1;
});
// Support: IE<8
// Prevent attribute/property "interpolation"
// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
if ( !assert(function( div ) {
div.innerHTML = "<a href='#'></a>";
return div.firstChild.getAttribute("href") === "#" ;
}) ) {
addHandle( "type|href|height|width", function( elem, name, isXML ) {
if ( !isXML ) {
return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 );
}
});
}
// Support: IE<9
// Use defaultValue in place of getAttribute("value")
if ( !support.attributes || !assert(function( div ) {
div.innerHTML = "<input/>";
div.firstChild.setAttribute( "value", "" );
return div.firstChild.getAttribute( "value" ) === "";
}) ) {
addHandle( "value", function( elem, name, isXML ) {
if ( !isXML && elem.nodeName.toLowerCase() === "input" ) {
return elem.defaultValue;
}
});
}
// Support: IE<9
// Use getAttributeNode to fetch booleans when getAttribute lies
if ( !assert(function( div ) {
return div.getAttribute("disabled") == null;
}) ) {
addHandle( booleans, function( elem, name, isXML ) {
var val;
if ( !isXML ) {
return elem[ name ] === true ? name.toLowerCase() :
(val = elem.getAttributeNode( name )) && val.specified ?
val.value :
null;
}
});
}
return Sizzle;
})( window );
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.pseudos;
jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
var rneedsContext = jQuery.expr.match.needsContext;
var rsingleTag = (/^<(\w+)\s*\/?>(?:<\/\1>|)$/);
var risSimple = /^.[^:#\[\.,]*$/;
// Implement the identical functionality for filter and not
function winnow( elements, qualifier, not ) {
if ( jQuery.isFunction( qualifier ) ) {
return jQuery.grep( elements, function( elem, i ) {
/* jshint -W018 */
return !!qualifier.call( elem, i, elem ) !== not;
});
}
if ( qualifier.nodeType ) {
return jQuery.grep( elements, function( elem ) {
return ( elem === qualifier ) !== not;
});
}
if ( typeof qualifier === "string" ) {
if ( risSimple.test( qualifier ) ) {
return jQuery.filter( qualifier, elements, not );
}
qualifier = jQuery.filter( qualifier, elements );
}
return jQuery.grep( elements, function( elem ) {
return ( indexOf.call( qualifier, elem ) >= 0 ) !== not;
});
}
jQuery.filter = function( expr, elems, not ) {
var elem = elems[ 0 ];
if ( not ) {
expr = ":not(" + expr + ")";
}
return elems.length === 1 && elem.nodeType === 1 ?
jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] :
jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) {
return elem.nodeType === 1;
}));
};
jQuery.fn.extend({
find: function( selector ) {
var i,
len = this.length,
ret = [],
self = this;
if ( typeof selector !== "string" ) {
return this.pushStack( jQuery( selector ).filter(function() {
for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( self[ i ], this ) ) {
return true;
}
}
}) );
}
for ( i = 0; i < len; i++ ) {
jQuery.find( selector, self[ i ], ret );
}
// Needed because $( selector, context ) becomes $( context ).find( selector )
ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret );
ret.selector = this.selector ? this.selector + " " + selector : selector;
return ret;
},
filter: function( selector ) {
return this.pushStack( winnow(this, selector || [], false) );
},
not: function( selector ) {
return this.pushStack( winnow(this, selector || [], true) );
},
is: function( selector ) {
return !!winnow(
this,
// If this is a positional/relative selector, check membership in the returned set
// so $("p:first").is("p:last") won't return true for a doc with two "p".
typeof selector === "string" && rneedsContext.test( selector ) ?
jQuery( selector ) :
selector || [],
false
).length;
}
});
// Initialize a jQuery object
// A central reference to the root jQuery(document)
var rootjQuery,
// A simple way to check for HTML strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
// Strict HTML recognition (#11290: must start with <)
rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,
init = jQuery.fn.init = function( selector, context ) {
var match, elem;
// HANDLE: $(""), $(null), $(undefined), $(false)
if ( !selector ) {
return this;
}
// Handle HTML strings
if ( typeof selector === "string" ) {
if ( selector[0] === "<" && selector[ selector.length - 1 ] === ">" && selector.length >= 3 ) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [ null, selector, null ];
} else {
match = rquickExpr.exec( selector );
}
// Match html or make sure no context is specified for #id
if ( match && (match[1] || !context) ) {
// HANDLE: $(html) -> $(array)
if ( match[1] ) {
context = context instanceof jQuery ? context[0] : context;
// Option to run scripts is true for back-compat
// Intentionally let the error be thrown if parseHTML is not present
jQuery.merge( this, jQuery.parseHTML(
match[1],
context && context.nodeType ? context.ownerDocument || context : document,
true
) );
// HANDLE: $(html, props)
if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) {
for ( match in context ) {
// Properties of context are called as methods if possible
if ( jQuery.isFunction( this[ match ] ) ) {
this[ match ]( context[ match ] );
// ...and otherwise set as attributes
} else {
this.attr( match, context[ match ] );
}
}
}
return this;
// HANDLE: $(#id)
} else {
elem = document.getElementById( match[2] );
// Support: Blackberry 4.6
// gEBID returns nodes no longer in the document (#6963)
if ( elem && elem.parentNode ) {
// Inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return ( context || rootjQuery ).find( selector );
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return this.constructor( context ).find( selector );
}
// HANDLE: $(DOMElement)
} else if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return typeof rootjQuery.ready !== "undefined" ?
rootjQuery.ready( selector ) :
// Execute immediately if ready is not present
selector( jQuery );
}
if ( selector.selector !== undefined ) {
this.selector = selector.selector;
this.context = selector.context;
}
return jQuery.makeArray( selector, this );
};
// Give the init function the jQuery prototype for later instantiation
init.prototype = jQuery.fn;
// Initialize central reference
rootjQuery = jQuery( document );
var rparentsprev = /^(?:parents|prev(?:Until|All))/,
// Methods guaranteed to produce a unique set when starting from a unique set
guaranteedUnique = {
children: true,
contents: true,
next: true,
prev: true
};
jQuery.extend({
dir: function( elem, dir, until ) {
var matched = [],
truncate = until !== undefined;
while ( (elem = elem[ dir ]) && elem.nodeType !== 9 ) {
if ( elem.nodeType === 1 ) {
if ( truncate && jQuery( elem ).is( until ) ) {
break;
}
matched.push( elem );
}
}
return matched;
},
sibling: function( n, elem ) {
var matched = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
matched.push( n );
}
}
return matched;
}
});
jQuery.fn.extend({
has: function( target ) {
var targets = jQuery( target, this ),
l = targets.length;
return this.filter(function() {
var i = 0;
for ( ; i < l; i++ ) {
if ( jQuery.contains( this, targets[i] ) ) {
return true;
}
}
});
},
closest: function( selectors, context ) {
var cur,
i = 0,
l = this.length,
matched = [],
pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ?
jQuery( selectors, context || this.context ) :
0;
for ( ; i < l; i++ ) {
for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) {
// Always skip document fragments
if ( cur.nodeType < 11 && (pos ?
pos.index(cur) > -1 :
// Don't pass non-elements to Sizzle
cur.nodeType === 1 &&
jQuery.find.matchesSelector(cur, selectors)) ) {
matched.push( cur );
break;
}
}
}
return this.pushStack( matched.length > 1 ? jQuery.unique( matched ) : matched );
},
// Determine the position of an element within the set
index: function( elem ) {
// No argument, return index in parent
if ( !elem ) {
return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1;
}
// Index in selector
if ( typeof elem === "string" ) {
return indexOf.call( jQuery( elem ), this[ 0 ] );
}
// Locate the position of the desired element
return indexOf.call( this,
// If it receives a jQuery object, the first element is used
elem.jquery ? elem[ 0 ] : elem
);
},
add: function( selector, context ) {
return this.pushStack(
jQuery.unique(
jQuery.merge( this.get(), jQuery( selector, context ) )
)
);
},
addBack: function( selector ) {
return this.add( selector == null ?
this.prevObject : this.prevObject.filter(selector)
);
}
});
function sibling( cur, dir ) {
while ( (cur = cur[dir]) && cur.nodeType !== 1 ) {}
return cur;
}
jQuery.each({
parent: function( elem ) {
var parent = elem.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
parents: function( elem ) {
return jQuery.dir( elem, "parentNode" );
},
parentsUntil: function( elem, i, until ) {
return jQuery.dir( elem, "parentNode", until );
},
next: function( elem ) {
return sibling( elem, "nextSibling" );
},
prev: function( elem ) {
return sibling( elem, "previousSibling" );
},
nextAll: function( elem ) {
return jQuery.dir( elem, "nextSibling" );
},
prevAll: function( elem ) {
return jQuery.dir( elem, "previousSibling" );
},
nextUntil: function( elem, i, until ) {
return jQuery.dir( elem, "nextSibling", until );
},
prevUntil: function( elem, i, until ) {
return jQuery.dir( elem, "previousSibling", until );
},
siblings: function( elem ) {
return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem );
},
children: function( elem ) {
return jQuery.sibling( elem.firstChild );
},
contents: function( elem ) {
return elem.contentDocument || jQuery.merge( [], elem.childNodes );
}
}, function( name, fn ) {
jQuery.fn[ name ] = function( until, selector ) {
var matched = jQuery.map( this, fn, until );
if ( name.slice( -5 ) !== "Until" ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
matched = jQuery.filter( selector, matched );
}
if ( this.length > 1 ) {
// Remove duplicates
if ( !guaranteedUnique[ name ] ) {
jQuery.unique( matched );
}
// Reverse order for parents* and prev-derivatives
if ( rparentsprev.test( name ) ) {
matched.reverse();
}
}
return this.pushStack( matched );
};
});
var rnotwhite = (/\S+/g);
// String to Object options format cache
var optionsCache = {};
// Convert String-formatted options into Object-formatted ones and store in cache
function createOptions( options ) {
var object = optionsCache[ options ] = {};
jQuery.each( options.match( rnotwhite ) || [], function( _, flag ) {
object[ flag ] = true;
});
return object;
}
/*
* Create a callback list using the following parameters:
*
* options: an optional list of space-separated options that will change how
* the callback list behaves or a more traditional option object
*
* By default a callback list will act like an event callback list and can be
* "fired" multiple times.
*
* Possible options:
*
* once: will ensure the callback list can only be fired once (like a Deferred)
*
* memory: will keep track of previous values and will call any callback added
* after the list has been fired right away with the latest "memorized"
* values (like a Deferred)
*
* unique: will ensure a callback can only be added once (no duplicate in the list)
*
* stopOnFalse: interrupt callings when a callback returns false
*
*/
jQuery.Callbacks = function( options ) {
// Convert options from String-formatted to Object-formatted if needed
// (we check in cache first)
options = typeof options === "string" ?
( optionsCache[ options ] || createOptions( options ) ) :
jQuery.extend( {}, options );
var // Last fire value (for non-forgettable lists)
memory,
// Flag to know if list was already fired
fired,
// Flag to know if list is currently firing
firing,
// First callback to fire (used internally by add and fireWith)
firingStart,
// End of the loop when firing
firingLength,
// Index of currently firing callback (modified by remove if needed)
firingIndex,
// Actual callback list
list = [],
// Stack of fire calls for repeatable lists
stack = !options.once && [],
// Fire callbacks
fire = function( data ) {
memory = options.memory && data;
fired = true;
firingIndex = firingStart || 0;
firingStart = 0;
firingLength = list.length;
firing = true;
for ( ; list && firingIndex < firingLength; firingIndex++ ) {
if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) {
memory = false; // To prevent further calls using add
break;
}
}
firing = false;
if ( list ) {
if ( stack ) {
if ( stack.length ) {
fire( stack.shift() );
}
} else if ( memory ) {
list = [];
} else {
self.disable();
}
}
},
// Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add: function() {
if ( list ) {
// First, we save the current length
var start = list.length;
(function add( args ) {
jQuery.each( args, function( _, arg ) {
var type = jQuery.type( arg );
if ( type === "function" ) {
if ( !options.unique || !self.has( arg ) ) {
list.push( arg );
}
} else if ( arg && arg.length && type !== "string" ) {
// Inspect recursively
add( arg );
}
});
})( arguments );
// Do we need to add the callbacks to the
// current firing batch?
if ( firing ) {
firingLength = list.length;
// With memory, if we're not firing then
// we should call right away
} else if ( memory ) {
firingStart = start;
fire( memory );
}
}
return this;
},
// Remove a callback from the list
remove: function() {
if ( list ) {
jQuery.each( arguments, function( _, arg ) {
var index;
while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
list.splice( index, 1 );
// Handle firing indexes
if ( firing ) {
if ( index <= firingLength ) {
firingLength--;
}
if ( index <= firingIndex ) {
firingIndex--;
}
}
}
});
}
return this;
},
// Check if a given callback is in the list.
// If no argument is given, return whether or not list has callbacks attached.
has: function( fn ) {
return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length );
},
// Remove all callbacks from the list
empty: function() {
list = [];
firingLength = 0;
return this;
},
// Have the list do nothing anymore
disable: function() {
list = stack = memory = undefined;
return this;
},
// Is it disabled?
disabled: function() {
return !list;
},
// Lock the list in its current state
lock: function() {
stack = undefined;
if ( !memory ) {
self.disable();
}
return this;
},
// Is it locked?
locked: function() {
return !stack;
},
// Call all callbacks with the given context and arguments
fireWith: function( context, args ) {
if ( list && ( !fired || stack ) ) {
args = args || [];
args = [ context, args.slice ? args.slice() : args ];
if ( firing ) {
stack.push( args );
} else {
fire( args );
}
}
return this;
},
// Call all the callbacks with the given arguments
fire: function() {
self.fireWith( this, arguments );
return this;
},
// To know if the callbacks have already been called at least once
fired: function() {
return !!fired;
}
};
return self;
};
jQuery.extend({
Deferred: function( func ) {
var tuples = [
// action, add listener, listener list, final state
[ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ],
[ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ],
[ "notify", "progress", jQuery.Callbacks("memory") ]
],
state = "pending",
promise = {
state: function() {
return state;
},
always: function() {
deferred.done( arguments ).fail( arguments );
return this;
},
then: function( /* fnDone, fnFail, fnProgress */ ) {
var fns = arguments;
return jQuery.Deferred(function( newDefer ) {
jQuery.each( tuples, function( i, tuple ) {
var fn = jQuery.isFunction( fns[ i ] ) && fns[ i ];
// deferred[ done | fail | progress ] for forwarding actions to newDefer
deferred[ tuple[1] ](function() {
var returned = fn && fn.apply( this, arguments );
if ( returned && jQuery.isFunction( returned.promise ) ) {
returned.promise()
.done( newDefer.resolve )
.fail( newDefer.reject )
.progress( newDefer.notify );
} else {
newDefer[ tuple[ 0 ] + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments );
}
});
});
fns = null;
}).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function( obj ) {
return obj != null ? jQuery.extend( obj, promise ) : promise;
}
},
deferred = {};
// Keep pipe for back-compat
promise.pipe = promise.then;
// Add list-specific methods
jQuery.each( tuples, function( i, tuple ) {
var list = tuple[ 2 ],
stateString = tuple[ 3 ];
// promise[ done | fail | progress ] = list.add
promise[ tuple[1] ] = list.add;
// Handle state
if ( stateString ) {
list.add(function() {
// state = [ resolved | rejected ]
state = stateString;
// [ reject_list | resolve_list ].disable; progress_list.lock
}, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock );
}
// deferred[ resolve | reject | notify ]
deferred[ tuple[0] ] = function() {
deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments );
return this;
};
deferred[ tuple[0] + "With" ] = list.fireWith;
});
// Make the deferred a promise
promise.promise( deferred );
// Call given func if any
if ( func ) {
func.call( deferred, deferred );
}
// All done!
return deferred;
},
// Deferred helper
when: function( subordinate /* , ..., subordinateN */ ) {
var i = 0,
resolveValues = slice.call( arguments ),
length = resolveValues.length,
// the count of uncompleted subordinates
remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0,
// the master Deferred. If resolveValues consist of only a single Deferred, just use that.
deferred = remaining === 1 ? subordinate : jQuery.Deferred(),
// Update function for both resolve and progress values
updateFunc = function( i, contexts, values ) {
return function( value ) {
contexts[ i ] = this;
values[ i ] = arguments.length > 1 ? slice.call( arguments ) : value;
if ( values === progressValues ) {
deferred.notifyWith( contexts, values );
} else if ( !( --remaining ) ) {
deferred.resolveWith( contexts, values );
}
};
},
progressValues, progressContexts, resolveContexts;
// Add listeners to Deferred subordinates; treat others as resolved
if ( length > 1 ) {
progressValues = new Array( length );
progressContexts = new Array( length );
resolveContexts = new Array( length );
for ( ; i < length; i++ ) {
if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) {
resolveValues[ i ].promise()
.done( updateFunc( i, resolveContexts, resolveValues ) )
.fail( deferred.reject )
.progress( updateFunc( i, progressContexts, progressValues ) );
} else {
--remaining;
}
}
}
// If we're not waiting on anything, resolve the master
if ( !remaining ) {
deferred.resolveWith( resolveContexts, resolveValues );
}
return deferred.promise();
}
});
// The deferred used on DOM ready
var readyList;
jQuery.fn.ready = function( fn ) {
// Add the callback
jQuery.ready.promise().done( fn );
return this;
};
jQuery.extend({
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Hold (or release) the ready event
holdReady: function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
},
// Handle when the DOM is ready
ready: function( wait ) {
// Abort if there are pending holds or we're already ready
if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
return;
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.resolveWith( document, [ jQuery ] );
// Trigger any bound ready events
if ( jQuery.fn.triggerHandler ) {
jQuery( document ).triggerHandler( "ready" );
jQuery( document ).off( "ready" );
}
}
});
/**
* The ready event handler and self cleanup method
*/
function completed() {
document.removeEventListener( "DOMContentLoaded", completed, false );
window.removeEventListener( "load", completed, false );
jQuery.ready();
}
jQuery.ready.promise = function( obj ) {
if ( !readyList ) {
readyList = jQuery.Deferred();
// Catch cases where $(document).ready() is called after the browser event has already occurred.
// We once tried to use readyState "interactive" here, but it caused issues like the one
// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
setTimeout( jQuery.ready );
} else {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", completed, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", completed, false );
}
}
return readyList.promise( obj );
};
// Kick off the DOM ready check even if the user does not
jQuery.ready.promise();
// Multifunctional method to get and set values of a collection
// The value/s can optionally be executed if it's a function
var access = jQuery.access = function( elems, fn, key, value, chainable, emptyGet, raw ) {
var i = 0,
len = elems.length,
bulk = key == null;
// Sets many values
if ( jQuery.type( key ) === "object" ) {
chainable = true;
for ( i in key ) {
jQuery.access( elems, fn, i, key[i], true, emptyGet, raw );
}
// Sets one value
} else if ( value !== undefined ) {
chainable = true;
if ( !jQuery.isFunction( value ) ) {
raw = true;
}
if ( bulk ) {
// Bulk operations run against the entire set
if ( raw ) {
fn.call( elems, value );
fn = null;
// ...except when executing function values
} else {
bulk = fn;
fn = function( elem, key, value ) {
return bulk.call( jQuery( elem ), value );
};
}
}
if ( fn ) {
for ( ; i < len; i++ ) {
fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) );
}
}
}
return chainable ?
elems :
// Gets
bulk ?
fn.call( elems ) :
len ? fn( elems[0], key ) : emptyGet;
};
/**
* Determines whether an object can have data
*/
jQuery.acceptData = function( owner ) {
// Accepts only:
// - Node
// - Node.ELEMENT_NODE
// - Node.DOCUMENT_NODE
// - Object
// - Any
/* jshint -W018 */
return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType );
};
function Data() {
// Support: Android<4,
// Old WebKit does not have Object.preventExtensions/freeze method,
// return new empty object instead with no [[set]] accessor
Object.defineProperty( this.cache = {}, 0, {
get: function() {
return {};
}
});
this.expando = jQuery.expando + Data.uid++;
}
Data.uid = 1;
Data.accepts = jQuery.acceptData;
Data.prototype = {
key: function( owner ) {
// We can accept data for non-element nodes in modern browsers,
// but we should not, see #8335.
// Always return the key for a frozen object.
if ( !Data.accepts( owner ) ) {
return 0;
}
var descriptor = {},
// Check if the owner object already has a cache key
unlock = owner[ this.expando ];
// If not, create one
if ( !unlock ) {
unlock = Data.uid++;
// Secure it in a non-enumerable, non-writable property
try {
descriptor[ this.expando ] = { value: unlock };
Object.defineProperties( owner, descriptor );
// Support: Android<4
// Fallback to a less secure definition
} catch ( e ) {
descriptor[ this.expando ] = unlock;
jQuery.extend( owner, descriptor );
}
}
// Ensure the cache object
if ( !this.cache[ unlock ] ) {
this.cache[ unlock ] = {};
}
return unlock;
},
set: function( owner, data, value ) {
var prop,
// There may be an unlock assigned to this node,
// if there is no entry for this "owner", create one inline
// and set the unlock as though an owner entry had always existed
unlock = this.key( owner ),
cache = this.cache[ unlock ];
// Handle: [ owner, key, value ] args
if ( typeof data === "string" ) {
cache[ data ] = value;
// Handle: [ owner, { properties } ] args
} else {
// Fresh assignments by object are shallow copied
if ( jQuery.isEmptyObject( cache ) ) {
jQuery.extend( this.cache[ unlock ], data );
// Otherwise, copy the properties one-by-one to the cache object
} else {
for ( prop in data ) {
cache[ prop ] = data[ prop ];
}
}
}
return cache;
},
get: function( owner, key ) {
// Either a valid cache is found, or will be created.
// New caches will be created and the unlock returned,
// allowing direct access to the newly created
// empty data object. A valid owner object must be provided.
var cache = this.cache[ this.key( owner ) ];
return key === undefined ?
cache : cache[ key ];
},
access: function( owner, key, value ) {
var stored;
// In cases where either:
//
// 1. No key was specified
// 2. A string key was specified, but no value provided
//
// Take the "read" path and allow the get method to determine
// which value to return, respectively either:
//
// 1. The entire cache object
// 2. The data stored at the key
//
if ( key === undefined ||
((key && typeof key === "string") && value === undefined) ) {
stored = this.get( owner, key );
return stored !== undefined ?
stored : this.get( owner, jQuery.camelCase(key) );
}
// [*]When the key is not a string, or both a key and value
// are specified, set or extend (existing objects) with either:
//
// 1. An object of properties
// 2. A key and value
//
this.set( owner, key, value );
// Since the "set" path can have two possible entry points
// return the expected data based on which path was taken[*]
return value !== undefined ? value : key;
},
remove: function( owner, key ) {
var i, name, camel,
unlock = this.key( owner ),
cache = this.cache[ unlock ];
if ( key === undefined ) {
this.cache[ unlock ] = {};
} else {
// Support array or space separated string of keys
if ( jQuery.isArray( key ) ) {
// If "name" is an array of keys...
// When data is initially created, via ("key", "val") signature,
// keys will be converted to camelCase.
// Since there is no way to tell _how_ a key was added, remove
// both plain key and camelCase key. #12786
// This will only penalize the array argument path.
name = key.concat( key.map( jQuery.camelCase ) );
} else {
camel = jQuery.camelCase( key );
// Try the string as a key before any manipulation
if ( key in cache ) {
name = [ key, camel ];
} else {
// If a key with the spaces exists, use it.
// Otherwise, create an array by matching non-whitespace
name = camel;
name = name in cache ?
[ name ] : ( name.match( rnotwhite ) || [] );
}
}
i = name.length;
while ( i-- ) {
delete cache[ name[ i ] ];
}
}
},
hasData: function( owner ) {
return !jQuery.isEmptyObject(
this.cache[ owner[ this.expando ] ] || {}
);
},
discard: function( owner ) {
if ( owner[ this.expando ] ) {
delete this.cache[ owner[ this.expando ] ];
}
}
};
var data_priv = new Data();
var data_user = new Data();
// Implementation Summary
//
// 1. Enforce API surface and semantic compatibility with 1.9.x branch
// 2. Improve the module's maintainability by reducing the storage
// paths to a single mechanism.
// 3. Use the same single mechanism to support "private" and "user" data.
// 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData)
// 5. Avoid exposing implementation details on user objects (eg. expando properties)
// 6. Provide a clear path for implementation upgrade to WeakMap in 2014
var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,
rmultiDash = /([A-Z])/g;
function dataAttr( elem, key, data ) {
var name;
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();
data = elem.getAttribute( name );
if ( typeof data === "string" ) {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
// Only convert to a number if it doesn't change the string
+data + "" === data ? +data :
rbrace.test( data ) ? jQuery.parseJSON( data ) :
data;
} catch( e ) {}
// Make sure we set the data so it isn't changed later
data_user.set( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
jQuery.extend({
hasData: function( elem ) {
return data_user.hasData( elem ) || data_priv.hasData( elem );
},
data: function( elem, name, data ) {
return data_user.access( elem, name, data );
},
removeData: function( elem, name ) {
data_user.remove( elem, name );
},
// TODO: Now that all calls to _data and _removeData have been replaced
// with direct calls to data_priv methods, these can be deprecated.
_data: function( elem, name, data ) {
return data_priv.access( elem, name, data );
},
_removeData: function( elem, name ) {
data_priv.remove( elem, name );
}
});
jQuery.fn.extend({
data: function( key, value ) {
var i, name, data,
elem = this[ 0 ],
attrs = elem && elem.attributes;
// Gets all values
if ( key === undefined ) {
if ( this.length ) {
data = data_user.get( elem );
if ( elem.nodeType === 1 && !data_priv.get( elem, "hasDataAttrs" ) ) {
i = attrs.length;
while ( i-- ) {
// Support: IE11+
// The attrs elements can be null (#14894)
if ( attrs[ i ] ) {
name = attrs[ i ].name;
if ( name.indexOf( "data-" ) === 0 ) {
name = jQuery.camelCase( name.slice(5) );
dataAttr( elem, name, data[ name ] );
}
}
}
data_priv.set( elem, "hasDataAttrs", true );
}
}
return data;
}
// Sets multiple values
if ( typeof key === "object" ) {
return this.each(function() {
data_user.set( this, key );
});
}
return access( this, function( value ) {
var data,
camelKey = jQuery.camelCase( key );
// The calling jQuery object (element matches) is not empty
// (and therefore has an element appears at this[ 0 ]) and the
// `value` parameter was not undefined. An empty jQuery object
// will result in `undefined` for elem = this[ 0 ] which will
// throw an exception if an attempt to read a data cache is made.
if ( elem && value === undefined ) {
// Attempt to get data from the cache
// with the key as-is
data = data_user.get( elem, key );
if ( data !== undefined ) {
return data;
}
// Attempt to get data from the cache
// with the key camelized
data = data_user.get( elem, camelKey );
if ( data !== undefined ) {
return data;
}
// Attempt to "discover" the data in
// HTML5 custom data-* attrs
data = dataAttr( elem, camelKey, undefined );
if ( data !== undefined ) {
return data;
}
// We tried really hard, but the data doesn't exist.
return;
}
// Set the data...
this.each(function() {
// First, attempt to store a copy or reference of any
// data that might've been store with a camelCased key.
var data = data_user.get( this, camelKey );
// For HTML5 data-* attribute interop, we have to
// store property names with dashes in a camelCase form.
// This might not apply to all properties...*
data_user.set( this, camelKey, value );
// *... In the case of properties that might _actually_
// have dashes, we need to also store a copy of that
// unchanged property.
if ( key.indexOf("-") !== -1 && data !== undefined ) {
data_user.set( this, key, value );
}
});
}, null, value, arguments.length > 1, null, true );
},
removeData: function( key ) {
return this.each(function() {
data_user.remove( this, key );
});
}
});
jQuery.extend({
queue: function( elem, type, data ) {
var queue;
if ( elem ) {
type = ( type || "fx" ) + "queue";
queue = data_priv.get( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
if ( !queue || jQuery.isArray( data ) ) {
queue = data_priv.access( elem, type, jQuery.makeArray(data) );
} else {
queue.push( data );
}
}
return queue || [];
}
},
dequeue: function( elem, type ) {
type = type || "fx";
var queue = jQuery.queue( elem, type ),
startLength = queue.length,
fn = queue.shift(),
hooks = jQuery._queueHooks( elem, type ),
next = function() {
jQuery.dequeue( elem, type );
};
// If the fx queue is dequeued, always remove the progress sentinel
if ( fn === "inprogress" ) {
fn = queue.shift();
startLength--;
}
if ( fn ) {
// Add a progress sentinel to prevent the fx queue from being
// automatically dequeued
if ( type === "fx" ) {
queue.unshift( "inprogress" );
}
// Clear up the last queue stop function
delete hooks.stop;
fn.call( elem, next, hooks );
}
if ( !startLength && hooks ) {
hooks.empty.fire();
}
},
// Not public - generate a queueHooks object, or return the current one
_queueHooks: function( elem, type ) {
var key = type + "queueHooks";
return data_priv.get( elem, key ) || data_priv.access( elem, key, {
empty: jQuery.Callbacks("once memory").add(function() {
data_priv.remove( elem, [ type + "queue", key ] );
})
});
}
});
jQuery.fn.extend({
queue: function( type, data ) {
var setter = 2;
if ( typeof type !== "string" ) {
data = type;
type = "fx";
setter--;
}
if ( arguments.length < setter ) {
return jQuery.queue( this[0], type );
}
return data === undefined ?
this :
this.each(function() {
var queue = jQuery.queue( this, type, data );
// Ensure a hooks for this queue
jQuery._queueHooks( this, type );
if ( type === "fx" && queue[0] !== "inprogress" ) {
jQuery.dequeue( this, type );
}
});
},
dequeue: function( type ) {
return this.each(function() {
jQuery.dequeue( this, type );
});
},
clearQueue: function( type ) {
return this.queue( type || "fx", [] );
},
// Get a promise resolved when queues of a certain type
// are emptied (fx is the type by default)
promise: function( type, obj ) {
var tmp,
count = 1,
defer = jQuery.Deferred(),
elements = this,
i = this.length,
resolve = function() {
if ( !( --count ) ) {
defer.resolveWith( elements, [ elements ] );
}
};
if ( typeof type !== "string" ) {
obj = type;
type = undefined;
}
type = type || "fx";
while ( i-- ) {
tmp = data_priv.get( elements[ i ], type + "queueHooks" );
if ( tmp && tmp.empty ) {
count++;
tmp.empty.add( resolve );
}
}
resolve();
return defer.promise( obj );
}
});
var pnum = (/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/).source;
var cssExpand = [ "Top", "Right", "Bottom", "Left" ];
var isHidden = function( elem, el ) {
// isHidden might be called from jQuery#filter function;
// in that case, element will be second argument
elem = el || elem;
return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem );
};
var rcheckableType = (/^(?:checkbox|radio)$/i);
(function() {
var fragment = document.createDocumentFragment(),
div = fragment.appendChild( document.createElement( "div" ) ),
input = document.createElement( "input" );
// Support: Safari<=5.1
// Check state lost if the name is set (#11217)
// Support: Windows Web Apps (WWA)
// `name` and `type` must use .setAttribute for WWA (#14901)
input.setAttribute( "type", "radio" );
input.setAttribute( "checked", "checked" );
input.setAttribute( "name", "t" );
div.appendChild( input );
// Support: Safari<=5.1, Android<4.2
// Older WebKit doesn't clone checked state correctly in fragments
support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked;
// Support: IE<=11+
// Make sure textarea (and checkbox) defaultValue is properly cloned
div.innerHTML = "<textarea>x</textarea>";
support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue;
})();
var strundefined = typeof undefined;
support.focusinBubbles = "onfocusin" in window;
var
rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|pointer|contextmenu)|click/,
rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
rtypenamespace = /^([^.]*)(?:\.(.+)|)$/;
function returnTrue() {
return true;
}
function returnFalse() {
return false;
}
function safeActiveElement() {
try {
return document.activeElement;
} catch ( err ) { }
}
/*
* Helper functions for managing events -- not part of the public interface.
* Props to Dean Edwards' addEvent library for many of the ideas.
*/
jQuery.event = {
global: {},
add: function( elem, types, handler, data, selector ) {
var handleObjIn, eventHandle, tmp,
events, t, handleObj,
special, handlers, type, namespaces, origType,
elemData = data_priv.get( elem );
// Don't attach events to noData or text/comment nodes (but allow plain objects)
if ( !elemData ) {
return;
}
// Caller can pass in an object of custom data in lieu of the handler
if ( handler.handler ) {
handleObjIn = handler;
handler = handleObjIn.handler;
selector = handleObjIn.selector;
}
// Make sure that the handler has a unique ID, used to find/remove it later
if ( !handler.guid ) {
handler.guid = jQuery.guid++;
}
// Init the element's event structure and main handler, if this is the first
if ( !(events = elemData.events) ) {
events = elemData.events = {};
}
if ( !(eventHandle = elemData.handle) ) {
eventHandle = elemData.handle = function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== strundefined && jQuery.event.triggered !== e.type ?
jQuery.event.dispatch.apply( elem, arguments ) : undefined;
};
}
// Handle multiple events separated by a space
types = ( types || "" ).match( rnotwhite ) || [ "" ];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[t] ) || [];
type = origType = tmp[1];
namespaces = ( tmp[2] || "" ).split( "." ).sort();
// There *must* be a type, no attaching namespace-only handlers
if ( !type ) {
continue;
}
// If event changes its type, use the special event handlers for the changed type
special = jQuery.event.special[ type ] || {};
// If selector defined, determine special event api type, otherwise given type
type = ( selector ? special.delegateType : special.bindType ) || type;
// Update special based on newly reset type
special = jQuery.event.special[ type ] || {};
// handleObj is passed to all event handlers
handleObj = jQuery.extend({
type: type,
origType: origType,
data: data,
handler: handler,
guid: handler.guid,
selector: selector,
needsContext: selector && jQuery.expr.match.needsContext.test( selector ),
namespace: namespaces.join(".")
}, handleObjIn );
// Init the event handler queue if we're the first
if ( !(handlers = events[ type ]) ) {
handlers = events[ type ] = [];
handlers.delegateCount = 0;
// Only use addEventListener if the special events handler returns false
if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle, false );
}
}
}
if ( special.add ) {
special.add.call( elem, handleObj );
if ( !handleObj.handler.guid ) {
handleObj.handler.guid = handler.guid;
}
}
// Add to the element's handler list, delegates in front
if ( selector ) {
handlers.splice( handlers.delegateCount++, 0, handleObj );
} else {
handlers.push( handleObj );
}
// Keep track of which events have ever been used, for event optimization
jQuery.event.global[ type ] = true;
}
},
// Detach an event or set of events from an element
remove: function( elem, types, handler, selector, mappedTypes ) {
var j, origCount, tmp,
events, t, handleObj,
special, handlers, type, namespaces, origType,
elemData = data_priv.hasData( elem ) && data_priv.get( elem );
if ( !elemData || !(events = elemData.events) ) {
return;
}
// Once for each type.namespace in types; type may be omitted
types = ( types || "" ).match( rnotwhite ) || [ "" ];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[t] ) || [];
type = origType = tmp[1];
namespaces = ( tmp[2] || "" ).split( "." ).sort();
// Unbind all events (on this namespace, if provided) for the element
if ( !type ) {
for ( type in events ) {
jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
}
continue;
}
special = jQuery.event.special[ type ] || {};
type = ( selector ? special.delegateType : special.bindType ) || type;
handlers = events[ type ] || [];
tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" );
// Remove matching events
origCount = j = handlers.length;
while ( j-- ) {
handleObj = handlers[ j ];
if ( ( mappedTypes || origType === handleObj.origType ) &&
( !handler || handler.guid === handleObj.guid ) &&
( !tmp || tmp.test( handleObj.namespace ) ) &&
( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) {
handlers.splice( j, 1 );
if ( handleObj.selector ) {
handlers.delegateCount--;
}
if ( special.remove ) {
special.remove.call( elem, handleObj );
}
}
}
// Remove generic event handler if we removed something and no more handlers exist
// (avoids potential for endless recursion during removal of special event handlers)
if ( origCount && !handlers.length ) {
if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) {
jQuery.removeEvent( elem, type, elemData.handle );
}
delete events[ type ];
}
}
// Remove the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
delete elemData.handle;
data_priv.remove( elem, "events" );
}
},
trigger: function( event, data, elem, onlyHandlers ) {
var i, cur, tmp, bubbleType, ontype, handle, special,
eventPath = [ elem || document ],
type = hasOwn.call( event, "type" ) ? event.type : event,
namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : [];
cur = tmp = elem = elem || document;
// Don't do events on text and comment nodes
if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
return;
}
// focus/blur morphs to focusin/out; ensure we're not firing them right now
if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
return;
}
if ( type.indexOf(".") >= 0 ) {
// Namespaced trigger; create a regexp to match event type in handle()
namespaces = type.split(".");
type = namespaces.shift();
namespaces.sort();
}
ontype = type.indexOf(":") < 0 && "on" + type;
// Caller can pass in a jQuery.Event object, Object, or just an event type string
event = event[ jQuery.expando ] ?
event :
new jQuery.Event( type, typeof event === "object" && event );
// Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true)
event.isTrigger = onlyHandlers ? 2 : 3;
event.namespace = namespaces.join(".");
event.namespace_re = event.namespace ?
new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) :
null;
// Clean up the event in case it is being reused
event.result = undefined;
if ( !event.target ) {
event.target = elem;
}
// Clone any incoming data and prepend the event, creating the handler arg list
data = data == null ?
[ event ] :
jQuery.makeArray( data, [ event ] );
// Allow special events to draw outside the lines
special = jQuery.event.special[ type ] || {};
if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) {
return;
}
// Determine event propagation path in advance, per W3C events spec (#9951)
// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {
bubbleType = special.delegateType || type;
if ( !rfocusMorph.test( bubbleType + type ) ) {
cur = cur.parentNode;
}
for ( ; cur; cur = cur.parentNode ) {
eventPath.push( cur );
tmp = cur;
}
// Only add window if we got to document (e.g., not plain obj or detached DOM)
if ( tmp === (elem.ownerDocument || document) ) {
eventPath.push( tmp.defaultView || tmp.parentWindow || window );
}
}
// Fire handlers on the event path
i = 0;
while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) {
event.type = i > 1 ?
bubbleType :
special.bindType || type;
// jQuery handler
handle = ( data_priv.get( cur, "events" ) || {} )[ event.type ] && data_priv.get( cur, "handle" );
if ( handle ) {
handle.apply( cur, data );
}
// Native handler
handle = ontype && cur[ ontype ];
if ( handle && handle.apply && jQuery.acceptData( cur ) ) {
event.result = handle.apply( cur, data );
if ( event.result === false ) {
event.preventDefault();
}
}
}
event.type = type;
// If nobody prevented the default action, do it now
if ( !onlyHandlers && !event.isDefaultPrevented() ) {
if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) &&
jQuery.acceptData( elem ) ) {
// Call a native DOM method on the target with the same name name as the event.
// Don't do default actions on window, that's where global variables be (#6170)
if ( ontype && jQuery.isFunction( elem[ type ] ) && !jQuery.isWindow( elem ) ) {
// Don't re-trigger an onFOO event when we call its FOO() method
tmp = elem[ ontype ];
if ( tmp ) {
elem[ ontype ] = null;
}
// Prevent re-triggering of the same event, since we already bubbled it above
jQuery.event.triggered = type;
elem[ type ]();
jQuery.event.triggered = undefined;
if ( tmp ) {
elem[ ontype ] = tmp;
}
}
}
}
return event.result;
},
dispatch: function( event ) {
// Make a writable jQuery.Event from the native event object
event = jQuery.event.fix( event );
var i, j, ret, matched, handleObj,
handlerQueue = [],
args = slice.call( arguments ),
handlers = ( data_priv.get( this, "events" ) || {} )[ event.type ] || [],
special = jQuery.event.special[ event.type ] || {};
// Use the fix-ed jQuery.Event rather than the (read-only) native event
args[0] = event;
event.delegateTarget = this;
// Call the preDispatch hook for the mapped type, and let it bail if desired
if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
return;
}
// Determine handlers
handlerQueue = jQuery.event.handlers.call( this, event, handlers );
// Run delegates first; they may want to stop propagation beneath us
i = 0;
while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) {
event.currentTarget = matched.elem;
j = 0;
while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) {
// Triggered event must either 1) have no namespace, or 2) have namespace(s)
// a subset or equal to those in the bound event (both can have no namespace).
if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) {
event.handleObj = handleObj;
event.data = handleObj.data;
ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )
.apply( matched.elem, args );
if ( ret !== undefined ) {
if ( (event.result = ret) === false ) {
event.preventDefault();
event.stopPropagation();
}
}
}
}
}
// Call the postDispatch hook for the mapped type
if ( special.postDispatch ) {
special.postDispatch.call( this, event );
}
return event.result;
},
handlers: function( event, handlers ) {
var i, matches, sel, handleObj,
handlerQueue = [],
delegateCount = handlers.delegateCount,
cur = event.target;
// Find delegate handlers
// Black-hole SVG <use> instance trees (#13180)
// Avoid non-left-click bubbling in Firefox (#3861)
if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) {
for ( ; cur !== this; cur = cur.parentNode || this ) {
// Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
if ( cur.disabled !== true || event.type !== "click" ) {
matches = [];
for ( i = 0; i < delegateCount; i++ ) {
handleObj = handlers[ i ];
// Don't conflict with Object.prototype properties (#13203)
sel = handleObj.selector + " ";
if ( matches[ sel ] === undefined ) {
matches[ sel ] = handleObj.needsContext ?
jQuery( sel, this ).index( cur ) >= 0 :
jQuery.find( sel, this, null, [ cur ] ).length;
}
if ( matches[ sel ] ) {
matches.push( handleObj );
}
}
if ( matches.length ) {
handlerQueue.push({ elem: cur, handlers: matches });
}
}
}
}
// Add the remaining (directly-bound) handlers
if ( delegateCount < handlers.length ) {
handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) });
}
return handlerQueue;
},
// Includes some event props shared by KeyEvent and MouseEvent
props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),
fixHooks: {},
keyHooks: {
props: "char charCode key keyCode".split(" "),
filter: function( event, original ) {
// Add which for key events
if ( event.which == null ) {
event.which = original.charCode != null ? original.charCode : original.keyCode;
}
return event;
}
},
mouseHooks: {
props: "button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
filter: function( event, original ) {
var eventDoc, doc, body,
button = original.button;
// Calculate pageX/Y if missing and clientX/Y available
if ( event.pageX == null && original.clientX != null ) {
eventDoc = event.target.ownerDocument || document;
doc = eventDoc.documentElement;
body = eventDoc.body;
event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 );
event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 );
}
// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if ( !event.which && button !== undefined ) {
event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
}
return event;
}
},
fix: function( event ) {
if ( event[ jQuery.expando ] ) {
return event;
}
// Create a writable copy of the event object and normalize some properties
var i, prop, copy,
type = event.type,
originalEvent = event,
fixHook = this.fixHooks[ type ];
if ( !fixHook ) {
this.fixHooks[ type ] = fixHook =
rmouseEvent.test( type ) ? this.mouseHooks :
rkeyEvent.test( type ) ? this.keyHooks :
{};
}
copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props;
event = new jQuery.Event( originalEvent );
i = copy.length;
while ( i-- ) {
prop = copy[ i ];
event[ prop ] = originalEvent[ prop ];
}
// Support: Cordova 2.5 (WebKit) (#13255)
// All events should have a target; Cordova deviceready doesn't
if ( !event.target ) {
event.target = document;
}
// Support: Safari 6.0+, Chrome<28
// Target should not be a text node (#504, #13143)
if ( event.target.nodeType === 3 ) {
event.target = event.target.parentNode;
}
return fixHook.filter ? fixHook.filter( event, originalEvent ) : event;
},
special: {
load: {
// Prevent triggered image.load events from bubbling to window.load
noBubble: true
},
focus: {
// Fire native event if possible so blur/focus sequence is correct
trigger: function() {
if ( this !== safeActiveElement() && this.focus ) {
this.focus();
return false;
}
},
delegateType: "focusin"
},
blur: {
trigger: function() {
if ( this === safeActiveElement() && this.blur ) {
this.blur();
return false;
}
},
delegateType: "focusout"
},
click: {
// For checkbox, fire native event so checked state will be right
trigger: function() {
if ( this.type === "checkbox" && this.click && jQuery.nodeName( this, "input" ) ) {
this.click();
return false;
}
},
// For cross-browser consistency, don't fire native .click() on links
_default: function( event ) {
return jQuery.nodeName( event.target, "a" );
}
},
beforeunload: {
postDispatch: function( event ) {
// Support: Firefox 20+
// Firefox doesn't alert if the returnValue field is not set.
if ( event.result !== undefined && event.originalEvent ) {
event.originalEvent.returnValue = event.result;
}
}
}
},
simulate: function( type, elem, event, bubble ) {
// Piggyback on a donor event to simulate a different one.
// Fake originalEvent to avoid donor's stopPropagation, but if the
// simulated event prevents default then we do the same on the donor.
var e = jQuery.extend(
new jQuery.Event(),
event,
{
type: type,
isSimulated: true,
originalEvent: {}
}
);
if ( bubble ) {
jQuery.event.trigger( e, null, elem );
} else {
jQuery.event.dispatch.call( elem, e );
}
if ( e.isDefaultPrevented() ) {
event.preventDefault();
}
}
};
jQuery.removeEvent = function( elem, type, handle ) {
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle, false );
}
};
jQuery.Event = function( src, props ) {
// Allow instantiation without the 'new' keyword
if ( !(this instanceof jQuery.Event) ) {
return new jQuery.Event( src, props );
}
// Event object
if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type;
// Events bubbling up the document may have been marked as prevented
// by a handler lower down the tree; reflect the correct value.
this.isDefaultPrevented = src.defaultPrevented ||
src.defaultPrevented === undefined &&
// Support: Android<4.0
src.returnValue === false ?
returnTrue :
returnFalse;
// Event type
} else {
this.type = src;
}
// Put explicitly provided properties onto the event object
if ( props ) {
jQuery.extend( this, props );
}
// Create a timestamp if incoming event doesn't have one
this.timeStamp = src && src.timeStamp || jQuery.now();
// Mark it as fixed
this[ jQuery.expando ] = true;
};
// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse,
preventDefault: function() {
var e = this.originalEvent;
this.isDefaultPrevented = returnTrue;
if ( e && e.preventDefault ) {
e.preventDefault();
}
},
stopPropagation: function() {
var e = this.originalEvent;
this.isPropagationStopped = returnTrue;
if ( e && e.stopPropagation ) {
e.stopPropagation();
}
},
stopImmediatePropagation: function() {
var e = this.originalEvent;
this.isImmediatePropagationStopped = returnTrue;
if ( e && e.stopImmediatePropagation ) {
e.stopImmediatePropagation();
}
this.stopPropagation();
}
};
// Create mouseenter/leave events using mouseover/out and event-time checks
// Support: Chrome 15+
jQuery.each({
mouseenter: "mouseover",
mouseleave: "mouseout",
pointerenter: "pointerover",
pointerleave: "pointerout"
}, function( orig, fix ) {
jQuery.event.special[ orig ] = {
delegateType: fix,
bindType: fix,
handle: function( event ) {
var ret,
target = this,
related = event.relatedTarget,
handleObj = event.handleObj;
// For mousenter/leave call the handler if related is outside the target.
// NB: No relatedTarget if the mouse left/entered the browser window
if ( !related || (related !== target && !jQuery.contains( target, related )) ) {
event.type = handleObj.origType;
ret = handleObj.handler.apply( this, arguments );
event.type = fix;
}
return ret;
}
};
});
// Support: Firefox, Chrome, Safari
// Create "bubbling" focus and blur events
if ( !support.focusinBubbles ) {
jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
// Attach a single capturing handler on the document while someone wants focusin/focusout
var handler = function( event ) {
jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true );
};
jQuery.event.special[ fix ] = {
setup: function() {
var doc = this.ownerDocument || this,
attaches = data_priv.access( doc, fix );
if ( !attaches ) {
doc.addEventListener( orig, handler, true );
}
data_priv.access( doc, fix, ( attaches || 0 ) + 1 );
},
teardown: function() {
var doc = this.ownerDocument || this,
attaches = data_priv.access( doc, fix ) - 1;
if ( !attaches ) {
doc.removeEventListener( orig, handler, true );
data_priv.remove( doc, fix );
} else {
data_priv.access( doc, fix, attaches );
}
}
};
});
}
jQuery.fn.extend({
on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
var origFn, type;
// Types can be a map of types/handlers
if ( typeof types === "object" ) {
// ( types-Object, selector, data )
if ( typeof selector !== "string" ) {
// ( types-Object, data )
data = data || selector;
selector = undefined;
}
for ( type in types ) {
this.on( type, selector, data, types[ type ], one );
}
return this;
}
if ( data == null && fn == null ) {
// ( types, fn )
fn = selector;
data = selector = undefined;
} else if ( fn == null ) {
if ( typeof selector === "string" ) {
// ( types, selector, fn )
fn = data;
data = undefined;
} else {
// ( types, data, fn )
fn = data;
data = selector;
selector = undefined;
}
}
if ( fn === false ) {
fn = returnFalse;
} else if ( !fn ) {
return this;
}
if ( one === 1 ) {
origFn = fn;
fn = function( event ) {
// Can use an empty set, since event contains the info
jQuery().off( event );
return origFn.apply( this, arguments );
};
// Use same guid so caller can remove using origFn
fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
}
return this.each( function() {
jQuery.event.add( this, types, fn, data, selector );
});
},
one: function( types, selector, data, fn ) {
return this.on( types, selector, data, fn, 1 );
},
off: function( types, selector, fn ) {
var handleObj, type;
if ( types && types.preventDefault && types.handleObj ) {
// ( event ) dispatched jQuery.Event
handleObj = types.handleObj;
jQuery( types.delegateTarget ).off(
handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType,
handleObj.selector,
handleObj.handler
);
return this;
}
if ( typeof types === "object" ) {
// ( types-object [, selector] )
for ( type in types ) {
this.off( type, selector, types[ type ] );
}
return this;
}
if ( selector === false || typeof selector === "function" ) {
// ( types [, fn] )
fn = selector;
selector = undefined;
}
if ( fn === false ) {
fn = returnFalse;
}
return this.each(function() {
jQuery.event.remove( this, types, fn, selector );
});
},
trigger: function( type, data ) {
return this.each(function() {
jQuery.event.trigger( type, data, this );
});
},
triggerHandler: function( type, data ) {
var elem = this[0];
if ( elem ) {
return jQuery.event.trigger( type, data, elem, true );
}
}
});
var
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,
rtagName = /<([\w:]+)/,
rhtml = /<|&#?\w+;/,
rnoInnerhtml = /<(?:script|style|link)/i,
// checked="checked" or checked
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
rscriptType = /^$|\/(?:java|ecma)script/i,
rscriptTypeMasked = /^true\/(.*)/,
rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,
// We have to close these tags to support XHTML (#13200)
wrapMap = {
// Support: IE9
option: [ 1, "<select multiple='multiple'>", "</select>" ],
thead: [ 1, "<table>", "</table>" ],
col: [ 2, "<table><colgroup>", "</colgroup></table>" ],
tr: [ 2, "<table><tbody>", "</tbody></table>" ],
td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
_default: [ 0, "", "" ]
};
// Support: IE9
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
// Support: 1.x compatibility
// Manipulating tables requires a tbody
function manipulationTarget( elem, content ) {
return jQuery.nodeName( elem, "table" ) &&
jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ?
elem.getElementsByTagName("tbody")[0] ||
elem.appendChild( elem.ownerDocument.createElement("tbody") ) :
elem;
}
// Replace/restore the type attribute of script elements for safe DOM manipulation
function disableScript( elem ) {
elem.type = (elem.getAttribute("type") !== null) + "/" + elem.type;
return elem;
}
function restoreScript( elem ) {
var match = rscriptTypeMasked.exec( elem.type );
if ( match ) {
elem.type = match[ 1 ];
} else {
elem.removeAttribute("type");
}
return elem;
}
// Mark scripts as having already been evaluated
function setGlobalEval( elems, refElements ) {
var i = 0,
l = elems.length;
for ( ; i < l; i++ ) {
data_priv.set(
elems[ i ], "globalEval", !refElements || data_priv.get( refElements[ i ], "globalEval" )
);
}
}
function cloneCopyEvent( src, dest ) {
var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events;
if ( dest.nodeType !== 1 ) {
return;
}
// 1. Copy private data: events, handlers, etc.
if ( data_priv.hasData( src ) ) {
pdataOld = data_priv.access( src );
pdataCur = data_priv.set( dest, pdataOld );
events = pdataOld.events;
if ( events ) {
delete pdataCur.handle;
pdataCur.events = {};
for ( type in events ) {
for ( i = 0, l = events[ type ].length; i < l; i++ ) {
jQuery.event.add( dest, type, events[ type ][ i ] );
}
}
}
}
// 2. Copy user data
if ( data_user.hasData( src ) ) {
udataOld = data_user.access( src );
udataCur = jQuery.extend( {}, udataOld );
data_user.set( dest, udataCur );
}
}
function getAll( context, tag ) {
var ret = context.getElementsByTagName ? context.getElementsByTagName( tag || "*" ) :
context.querySelectorAll ? context.querySelectorAll( tag || "*" ) :
[];
return tag === undefined || tag && jQuery.nodeName( context, tag ) ?
jQuery.merge( [ context ], ret ) :
ret;
}
// Fix IE bugs, see support tests
function fixInput( src, dest ) {
var nodeName = dest.nodeName.toLowerCase();
// Fails to persist the checked state of a cloned checkbox or radio button.
if ( nodeName === "input" && rcheckableType.test( src.type ) ) {
dest.checked = src.checked;
// Fails to return the selected option to the default selected state when cloning options
} else if ( nodeName === "input" || nodeName === "textarea" ) {
dest.defaultValue = src.defaultValue;
}
}
jQuery.extend({
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var i, l, srcElements, destElements,
clone = elem.cloneNode( true ),
inPage = jQuery.contains( elem.ownerDocument, elem );
// Fix IE cloning issues
if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) &&
!jQuery.isXMLDoc( elem ) ) {
// We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2
destElements = getAll( clone );
srcElements = getAll( elem );
for ( i = 0, l = srcElements.length; i < l; i++ ) {
fixInput( srcElements[ i ], destElements[ i ] );
}
}
// Copy the events from the original to the clone
if ( dataAndEvents ) {
if ( deepDataAndEvents ) {
srcElements = srcElements || getAll( elem );
destElements = destElements || getAll( clone );
for ( i = 0, l = srcElements.length; i < l; i++ ) {
cloneCopyEvent( srcElements[ i ], destElements[ i ] );
}
} else {
cloneCopyEvent( elem, clone );
}
}
// Preserve script evaluation history
destElements = getAll( clone, "script" );
if ( destElements.length > 0 ) {
setGlobalEval( destElements, !inPage && getAll( elem, "script" ) );
}
// Return the cloned set
return clone;
},
buildFragment: function( elems, context, scripts, selection ) {
var elem, tmp, tag, wrap, contains, j,
fragment = context.createDocumentFragment(),
nodes = [],
i = 0,
l = elems.length;
for ( ; i < l; i++ ) {
elem = elems[ i ];
if ( elem || elem === 0 ) {
// Add nodes directly
if ( jQuery.type( elem ) === "object" ) {
// Support: QtWebKit, PhantomJS
// push.apply(_, arraylike) throws on ancient WebKit
jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem );
// Convert non-html into a text node
} else if ( !rhtml.test( elem ) ) {
nodes.push( context.createTextNode( elem ) );
// Convert html into DOM nodes
} else {
tmp = tmp || fragment.appendChild( context.createElement("div") );
// Deserialize a standard representation
tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase();
wrap = wrapMap[ tag ] || wrapMap._default;
tmp.innerHTML = wrap[ 1 ] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[ 2 ];
// Descend through wrappers to the right content
j = wrap[ 0 ];
while ( j-- ) {
tmp = tmp.lastChild;
}
// Support: QtWebKit, PhantomJS
// push.apply(_, arraylike) throws on ancient WebKit
jQuery.merge( nodes, tmp.childNodes );
// Remember the top-level container
tmp = fragment.firstChild;
// Ensure the created nodes are orphaned (#12392)
tmp.textContent = "";
}
}
}
// Remove wrapper from fragment
fragment.textContent = "";
i = 0;
while ( (elem = nodes[ i++ ]) ) {
// #4087 - If origin and destination elements are the same, and this is
// that element, do not do anything
if ( selection && jQuery.inArray( elem, selection ) !== -1 ) {
continue;
}
contains = jQuery.contains( elem.ownerDocument, elem );
// Append to fragment
tmp = getAll( fragment.appendChild( elem ), "script" );
// Preserve script evaluation history
if ( contains ) {
setGlobalEval( tmp );
}
// Capture executables
if ( scripts ) {
j = 0;
while ( (elem = tmp[ j++ ]) ) {
if ( rscriptType.test( elem.type || "" ) ) {
scripts.push( elem );
}
}
}
}
return fragment;
},
cleanData: function( elems ) {
var data, elem, type, key,
special = jQuery.event.special,
i = 0;
for ( ; (elem = elems[ i ]) !== undefined; i++ ) {
if ( jQuery.acceptData( elem ) ) {
key = elem[ data_priv.expando ];
if ( key && (data = data_priv.cache[ key ]) ) {
if ( data.events ) {
for ( type in data.events ) {
if ( special[ type ] ) {
jQuery.event.remove( elem, type );
// This is a shortcut to avoid jQuery.event.remove's overhead
} else {
jQuery.removeEvent( elem, type, data.handle );
}
}
}
if ( data_priv.cache[ key ] ) {
// Discard any remaining `private` data
delete data_priv.cache[ key ];
}
}
}
// Discard any remaining `user` data
delete data_user.cache[ elem[ data_user.expando ] ];
}
}
});
jQuery.fn.extend({
text: function( value ) {
return access( this, function( value ) {
return value === undefined ?
jQuery.text( this ) :
this.empty().each(function() {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
this.textContent = value;
}
});
}, null, value, arguments.length );
},
append: function() {
return this.domManip( arguments, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
var target = manipulationTarget( this, elem );
target.appendChild( elem );
}
});
},
prepend: function() {
return this.domManip( arguments, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
var target = manipulationTarget( this, elem );
target.insertBefore( elem, target.firstChild );
}
});
},
before: function() {
return this.domManip( arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this );
}
});
},
after: function() {
return this.domManip( arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this.nextSibling );
}
});
},
remove: function( selector, keepData /* Internal Use Only */ ) {
var elem,
elems = selector ? jQuery.filter( selector, this ) : this,
i = 0;
for ( ; (elem = elems[i]) != null; i++ ) {
if ( !keepData && elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem ) );
}
if ( elem.parentNode ) {
if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) {
setGlobalEval( getAll( elem, "script" ) );
}
elem.parentNode.removeChild( elem );
}
}
return this;
},
empty: function() {
var elem,
i = 0;
for ( ; (elem = this[i]) != null; i++ ) {
if ( elem.nodeType === 1 ) {
// Prevent memory leaks
jQuery.cleanData( getAll( elem, false ) );
// Remove any remaining nodes
elem.textContent = "";
}
}
return this;
},
clone: function( dataAndEvents, deepDataAndEvents ) {
dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
return this.map(function() {
return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
});
},
html: function( value ) {
return access( this, function( value ) {
var elem = this[ 0 ] || {},
i = 0,
l = this.length;
if ( value === undefined && elem.nodeType === 1 ) {
return elem.innerHTML;
}
// See if we can take a shortcut and just use innerHTML
if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
!wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) {
value = value.replace( rxhtmlTag, "<$1></$2>" );
try {
for ( ; i < l; i++ ) {
elem = this[ i ] || {};
// Remove element nodes and prevent memory leaks
if ( elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem, false ) );
elem.innerHTML = value;
}
}
elem = 0;
// If using innerHTML throws an exception, use the fallback method
} catch( e ) {}
}
if ( elem ) {
this.empty().append( value );
}
}, null, value, arguments.length );
},
replaceWith: function() {
var arg = arguments[ 0 ];
// Make the changes, replacing each context element with the new content
this.domManip( arguments, function( elem ) {
arg = this.parentNode;
jQuery.cleanData( getAll( this ) );
if ( arg ) {
arg.replaceChild( elem, this );
}
});
// Force removal if there was no new content (e.g., from empty arguments)
return arg && (arg.length || arg.nodeType) ? this : this.remove();
},
detach: function( selector ) {
return this.remove( selector, true );
},
domManip: function( args, callback ) {
// Flatten any nested arrays
args = concat.apply( [], args );
var fragment, first, scripts, hasScripts, node, doc,
i = 0,
l = this.length,
set = this,
iNoClone = l - 1,
value = args[ 0 ],
isFunction = jQuery.isFunction( value );
// We can't cloneNode fragments that contain checked, in WebKit
if ( isFunction ||
( l > 1 && typeof value === "string" &&
!support.checkClone && rchecked.test( value ) ) ) {
return this.each(function( index ) {
var self = set.eq( index );
if ( isFunction ) {
args[ 0 ] = value.call( this, index, self.html() );
}
self.domManip( args, callback );
});
}
if ( l ) {
fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this );
first = fragment.firstChild;
if ( fragment.childNodes.length === 1 ) {
fragment = first;
}
if ( first ) {
scripts = jQuery.map( getAll( fragment, "script" ), disableScript );
hasScripts = scripts.length;
// Use the original fragment for the last item instead of the first because it can end up
// being emptied incorrectly in certain situations (#8070).
for ( ; i < l; i++ ) {
node = fragment;
if ( i !== iNoClone ) {
node = jQuery.clone( node, true, true );
// Keep references to cloned scripts for later restoration
if ( hasScripts ) {
// Support: QtWebKit
// jQuery.merge because push.apply(_, arraylike) throws
jQuery.merge( scripts, getAll( node, "script" ) );
}
}
callback.call( this[ i ], node, i );
}
if ( hasScripts ) {
doc = scripts[ scripts.length - 1 ].ownerDocument;
// Reenable scripts
jQuery.map( scripts, restoreScript );
// Evaluate executable scripts on first document insertion
for ( i = 0; i < hasScripts; i++ ) {
node = scripts[ i ];
if ( rscriptType.test( node.type || "" ) &&
!data_priv.access( node, "globalEval" ) && jQuery.contains( doc, node ) ) {
if ( node.src ) {
// Optional AJAX dependency, but won't run scripts if not present
if ( jQuery._evalUrl ) {
jQuery._evalUrl( node.src );
}
} else {
jQuery.globalEval( node.textContent.replace( rcleanScript, "" ) );
}
}
}
}
}
}
return this;
}
});
jQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function( name, original ) {
jQuery.fn[ name ] = function( selector ) {
var elems,
ret = [],
insert = jQuery( selector ),
last = insert.length - 1,
i = 0;
for ( ; i <= last; i++ ) {
elems = i === last ? this : this.clone( true );
jQuery( insert[ i ] )[ original ]( elems );
// Support: QtWebKit
// .get() because push.apply(_, arraylike) throws
push.apply( ret, elems.get() );
}
return this.pushStack( ret );
};
});
var iframe,
elemdisplay = {};
/**
* Retrieve the actual display of a element
* @param {String} name nodeName of the element
* @param {Object} doc Document object
*/
// Called only from within defaultDisplay
function actualDisplay( name, doc ) {
var style,
elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ),
// getDefaultComputedStyle might be reliably used only on attached element
display = window.getDefaultComputedStyle && ( style = window.getDefaultComputedStyle( elem[ 0 ] ) ) ?
// Use of this method is a temporary fix (more like optimization) until something better comes along,
// since it was removed from specification and supported only in FF
style.display : jQuery.css( elem[ 0 ], "display" );
// We don't have any data stored on the element,
// so use "detach" method as fast way to get rid of the element
elem.detach();
return display;
}
/**
* Try to determine the default display value of an element
* @param {String} nodeName
*/
function defaultDisplay( nodeName ) {
var doc = document,
display = elemdisplay[ nodeName ];
if ( !display ) {
display = actualDisplay( nodeName, doc );
// If the simple way fails, read from inside an iframe
if ( display === "none" || !display ) {
// Use the already-created iframe if possible
iframe = (iframe || jQuery( "<iframe frameborder='0' width='0' height='0'/>" )).appendTo( doc.documentElement );
// Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse
doc = iframe[ 0 ].contentDocument;
// Support: IE
doc.write();
doc.close();
display = actualDisplay( nodeName, doc );
iframe.detach();
}
// Store the correct default display
elemdisplay[ nodeName ] = display;
}
return display;
}
var rmargin = (/^margin/);
var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" );
var getStyles = function( elem ) {
// Support: IE<=11+, Firefox<=30+ (#15098, #14150)
// IE throws on elements created in popups
// FF meanwhile throws on frame elements through "defaultView.getComputedStyle"
if ( elem.ownerDocument.defaultView.opener ) {
return elem.ownerDocument.defaultView.getComputedStyle( elem, null );
}
return window.getComputedStyle( elem, null );
};
function curCSS( elem, name, computed ) {
var width, minWidth, maxWidth, ret,
style = elem.style;
computed = computed || getStyles( elem );
// Support: IE9
// getPropertyValue is only needed for .css('filter') (#12537)
if ( computed ) {
ret = computed.getPropertyValue( name ) || computed[ name ];
}
if ( computed ) {
if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) {
ret = jQuery.style( elem, name );
}
// Support: iOS < 6
// A tribute to the "awesome hack by Dean Edwards"
// iOS < 6 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels
// this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values
if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) {
// Remember the original values
width = style.width;
minWidth = style.minWidth;
maxWidth = style.maxWidth;
// Put in the new values to get a computed value out
style.minWidth = style.maxWidth = style.width = ret;
ret = computed.width;
// Revert the changed values
style.width = width;
style.minWidth = minWidth;
style.maxWidth = maxWidth;
}
}
return ret !== undefined ?
// Support: IE
// IE returns zIndex value as an integer.
ret + "" :
ret;
}
function addGetHookIf( conditionFn, hookFn ) {
// Define the hook, we'll check on the first run if it's really needed.
return {
get: function() {
if ( conditionFn() ) {
// Hook not needed (or it's not possible to use it due
// to missing dependency), remove it.
delete this.get;
return;
}
// Hook needed; redefine it so that the support test is not executed again.
return (this.get = hookFn).apply( this, arguments );
}
};
}
(function() {
var pixelPositionVal, boxSizingReliableVal,
docElem = document.documentElement,
container = document.createElement( "div" ),
div = document.createElement( "div" );
if ( !div.style ) {
return;
}
// Support: IE9-11+
// Style of cloned element affects source element cloned (#8908)
div.style.backgroundClip = "content-box";
div.cloneNode( true ).style.backgroundClip = "";
support.clearCloneStyle = div.style.backgroundClip === "content-box";
container.style.cssText = "border:0;width:0;height:0;top:0;left:-9999px;margin-top:1px;" +
"position:absolute";
container.appendChild( div );
// Executing both pixelPosition & boxSizingReliable tests require only one layout
// so they're executed at the same time to save the second computation.
function computePixelPositionAndBoxSizingReliable() {
div.style.cssText =
// Support: Firefox<29, Android 2.3
// Vendor-prefix box-sizing
"-webkit-box-sizing:border-box;-moz-box-sizing:border-box;" +
"box-sizing:border-box;display:block;margin-top:1%;top:1%;" +
"border:1px;padding:1px;width:4px;position:absolute";
div.innerHTML = "";
docElem.appendChild( container );
var divStyle = window.getComputedStyle( div, null );
pixelPositionVal = divStyle.top !== "1%";
boxSizingReliableVal = divStyle.width === "4px";
docElem.removeChild( container );
}
// Support: node.js jsdom
// Don't assume that getComputedStyle is a property of the global object
if ( window.getComputedStyle ) {
jQuery.extend( support, {
pixelPosition: function() {
// This test is executed only once but we still do memoizing
// since we can use the boxSizingReliable pre-computing.
// No need to check if the test was already performed, though.
computePixelPositionAndBoxSizingReliable();
return pixelPositionVal;
},
boxSizingReliable: function() {
if ( boxSizingReliableVal == null ) {
computePixelPositionAndBoxSizingReliable();
}
return boxSizingReliableVal;
},
reliableMarginRight: function() {
// Support: Android 2.3
// Check if div with explicit width and no margin-right incorrectly
// gets computed margin-right based on width of container. (#3333)
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
// This support function is only executed once so no memoizing is needed.
var ret,
marginDiv = div.appendChild( document.createElement( "div" ) );
// Reset CSS: box-sizing; display; margin; border; padding
marginDiv.style.cssText = div.style.cssText =
// Support: Firefox<29, Android 2.3
// Vendor-prefix box-sizing
"-webkit-box-sizing:content-box;-moz-box-sizing:content-box;" +
"box-sizing:content-box;display:block;margin:0;border:0;padding:0";
marginDiv.style.marginRight = marginDiv.style.width = "0";
div.style.width = "1px";
docElem.appendChild( container );
ret = !parseFloat( window.getComputedStyle( marginDiv, null ).marginRight );
docElem.removeChild( container );
div.removeChild( marginDiv );
return ret;
}
});
}
})();
// A method for quickly swapping in/out CSS properties to get correct calculations.
jQuery.swap = function( elem, options, callback, args ) {
var ret, name,
old = {};
// Remember the old values, and insert the new ones
for ( name in options ) {
old[ name ] = elem.style[ name ];
elem.style[ name ] = options[ name ];
}
ret = callback.apply( elem, args || [] );
// Revert the old values
for ( name in options ) {
elem.style[ name ] = old[ name ];
}
return ret;
};
var
// Swappable if display is none or starts with table except "table", "table-cell", or "table-caption"
// See here for display values: https://developer.mozilla.org/en-US/docs/CSS/display
rdisplayswap = /^(none|table(?!-c[ea]).+)/,
rnumsplit = new RegExp( "^(" + pnum + ")(.*)$", "i" ),
rrelNum = new RegExp( "^([+-])=(" + pnum + ")", "i" ),
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
cssNormalTransform = {
letterSpacing: "0",
fontWeight: "400"
},
cssPrefixes = [ "Webkit", "O", "Moz", "ms" ];
// Return a css property mapped to a potentially vendor prefixed property
function vendorPropName( style, name ) {
// Shortcut for names that are not vendor prefixed
if ( name in style ) {
return name;
}
// Check for vendor prefixed names
var capName = name[0].toUpperCase() + name.slice(1),
origName = name,
i = cssPrefixes.length;
while ( i-- ) {
name = cssPrefixes[ i ] + capName;
if ( name in style ) {
return name;
}
}
return origName;
}
function setPositiveNumber( elem, value, subtract ) {
var matches = rnumsplit.exec( value );
return matches ?
// Guard against undefined "subtract", e.g., when used as in cssHooks
Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) :
value;
}
function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) {
var i = extra === ( isBorderBox ? "border" : "content" ) ?
// If we already have the right measurement, avoid augmentation
4 :
// Otherwise initialize for horizontal or vertical properties
name === "width" ? 1 : 0,
val = 0;
for ( ; i < 4; i += 2 ) {
// Both box models exclude margin, so add it if we want it
if ( extra === "margin" ) {
val += jQuery.css( elem, extra + cssExpand[ i ], true, styles );
}
if ( isBorderBox ) {
// border-box includes padding, so remove it if we want content
if ( extra === "content" ) {
val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
}
// At this point, extra isn't border nor margin, so remove border
if ( extra !== "margin" ) {
val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
}
} else {
// At this point, extra isn't content, so add padding
val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
// At this point, extra isn't content nor padding, so add border
if ( extra !== "padding" ) {
val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
}
}
}
return val;
}
function getWidthOrHeight( elem, name, extra ) {
// Start with offset property, which is equivalent to the border-box value
var valueIsBorderBox = true,
val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
styles = getStyles( elem ),
isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box";
// Some non-html elements return undefined for offsetWidth, so check for null/undefined
// svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285
// MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668
if ( val <= 0 || val == null ) {
// Fall back to computed then uncomputed css if necessary
val = curCSS( elem, name, styles );
if ( val < 0 || val == null ) {
val = elem.style[ name ];
}
// Computed unit is not pixels. Stop here and return.
if ( rnumnonpx.test(val) ) {
return val;
}
// Check for style in case a browser which returns unreliable values
// for getComputedStyle silently falls back to the reliable elem.style
valueIsBorderBox = isBorderBox &&
( support.boxSizingReliable() || val === elem.style[ name ] );
// Normalize "", auto, and prepare for extra
val = parseFloat( val ) || 0;
}
// Use the active box-sizing model to add/subtract irrelevant styles
return ( val +
augmentWidthOrHeight(
elem,
name,
extra || ( isBorderBox ? "border" : "content" ),
valueIsBorderBox,
styles
)
) + "px";
}
function showHide( elements, show ) {
var display, elem, hidden,
values = [],
index = 0,
length = elements.length;
for ( ; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
values[ index ] = data_priv.get( elem, "olddisplay" );
display = elem.style.display;
if ( show ) {
// Reset the inline display of this element to learn if it is
// being hidden by cascaded rules or not
if ( !values[ index ] && display === "none" ) {
elem.style.display = "";
}
// Set elements which have been overridden with display: none
// in a stylesheet to whatever the default browser style is
// for such an element
if ( elem.style.display === "" && isHidden( elem ) ) {
values[ index ] = data_priv.access( elem, "olddisplay", defaultDisplay(elem.nodeName) );
}
} else {
hidden = isHidden( elem );
if ( display !== "none" || !hidden ) {
data_priv.set( elem, "olddisplay", hidden ? display : jQuery.css( elem, "display" ) );
}
}
}
// Set the display of most of the elements in a second loop
// to avoid the constant reflow
for ( index = 0; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
if ( !show || elem.style.display === "none" || elem.style.display === "" ) {
elem.style.display = show ? values[ index ] || "" : "none";
}
}
return elements;
}
jQuery.extend({
// Add in style property hooks for overriding the default
// behavior of getting and setting a style property
cssHooks: {
opacity: {
get: function( elem, computed ) {
if ( computed ) {
// We should always get a number back from opacity
var ret = curCSS( elem, "opacity" );
return ret === "" ? "1" : ret;
}
}
}
},
// Don't automatically add "px" to these possibly-unitless properties
cssNumber: {
"columnCount": true,
"fillOpacity": true,
"flexGrow": true,
"flexShrink": true,
"fontWeight": true,
"lineHeight": true,
"opacity": true,
"order": true,
"orphans": true,
"widows": true,
"zIndex": true,
"zoom": true
},
// Add in properties whose names you wish to fix before
// setting or getting the value
cssProps: {
"float": "cssFloat"
},
// Get and set the style property on a DOM Node
style: function( elem, name, value, extra ) {
// Don't set styles on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
return;
}
// Make sure that we're working with the right name
var ret, type, hooks,
origName = jQuery.camelCase( name ),
style = elem.style;
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) );
// Gets hook for the prefixed version, then unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// Check if we're setting a value
if ( value !== undefined ) {
type = typeof value;
// Convert "+=" or "-=" to relative numbers (#7345)
if ( type === "string" && (ret = rrelNum.exec( value )) ) {
value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) );
// Fixes bug #9237
type = "number";
}
// Make sure that null and NaN values aren't set (#7116)
if ( value == null || value !== value ) {
return;
}
// If a number, add 'px' to the (except for certain CSS properties)
if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
value += "px";
}
// Support: IE9-11+
// background-* props affect original clone's values
if ( !support.clearCloneStyle && value === "" && name.indexOf( "background" ) === 0 ) {
style[ name ] = "inherit";
}
// If a hook was provided, use that value, otherwise just set the specified value
if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) {
style[ name ] = value;
}
} else {
// If a hook was provided get the non-computed value from there
if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) {
return ret;
}
// Otherwise just get the value from the style object
return style[ name ];
}
},
css: function( elem, name, extra, styles ) {
var val, num, hooks,
origName = jQuery.camelCase( name );
// Make sure that we're working with the right name
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) );
// Try prefixed name followed by the unprefixed name
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// If a hook was provided get the computed value from there
if ( hooks && "get" in hooks ) {
val = hooks.get( elem, true, extra );
}
// Otherwise, if a way to get the computed value exists, use that
if ( val === undefined ) {
val = curCSS( elem, name, styles );
}
// Convert "normal" to computed value
if ( val === "normal" && name in cssNormalTransform ) {
val = cssNormalTransform[ name ];
}
// Make numeric if forced or a qualifier was provided and val looks numeric
if ( extra === "" || extra ) {
num = parseFloat( val );
return extra === true || jQuery.isNumeric( num ) ? num || 0 : val;
}
return val;
}
});
jQuery.each([ "height", "width" ], function( i, name ) {
jQuery.cssHooks[ name ] = {
get: function( elem, computed, extra ) {
if ( computed ) {
// Certain elements can have dimension info if we invisibly show them
// but it must have a current display style that would benefit
return rdisplayswap.test( jQuery.css( elem, "display" ) ) && elem.offsetWidth === 0 ?
jQuery.swap( elem, cssShow, function() {
return getWidthOrHeight( elem, name, extra );
}) :
getWidthOrHeight( elem, name, extra );
}
},
set: function( elem, value, extra ) {
var styles = extra && getStyles( elem );
return setPositiveNumber( elem, value, extra ?
augmentWidthOrHeight(
elem,
name,
extra,
jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
styles
) : 0
);
}
};
});
// Support: Android 2.3
jQuery.cssHooks.marginRight = addGetHookIf( support.reliableMarginRight,
function( elem, computed ) {
if ( computed ) {
return jQuery.swap( elem, { "display": "inline-block" },
curCSS, [ elem, "marginRight" ] );
}
}
);
// These hooks are used by animate to expand properties
jQuery.each({
margin: "",
padding: "",
border: "Width"
}, function( prefix, suffix ) {
jQuery.cssHooks[ prefix + suffix ] = {
expand: function( value ) {
var i = 0,
expanded = {},
// Assumes a single number if not a string
parts = typeof value === "string" ? value.split(" ") : [ value ];
for ( ; i < 4; i++ ) {
expanded[ prefix + cssExpand[ i ] + suffix ] =
parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
}
return expanded;
}
};
if ( !rmargin.test( prefix ) ) {
jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber;
}
});
jQuery.fn.extend({
css: function( name, value ) {
return access( this, function( elem, name, value ) {
var styles, len,
map = {},
i = 0;
if ( jQuery.isArray( name ) ) {
styles = getStyles( elem );
len = name.length;
for ( ; i < len; i++ ) {
map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles );
}
return map;
}
return value !== undefined ?
jQuery.style( elem, name, value ) :
jQuery.css( elem, name );
}, name, value, arguments.length > 1 );
},
show: function() {
return showHide( this, true );
},
hide: function() {
return showHide( this );
},
toggle: function( state ) {
if ( typeof state === "boolean" ) {
return state ? this.show() : this.hide();
}
return this.each(function() {
if ( isHidden( this ) ) {
jQuery( this ).show();
} else {
jQuery( this ).hide();
}
});
}
});
function Tween( elem, options, prop, end, easing ) {
return new Tween.prototype.init( elem, options, prop, end, easing );
}
jQuery.Tween = Tween;
Tween.prototype = {
constructor: Tween,
init: function( elem, options, prop, end, easing, unit ) {
this.elem = elem;
this.prop = prop;
this.easing = easing || "swing";
this.options = options;
this.start = this.now = this.cur();
this.end = end;
this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" );
},
cur: function() {
var hooks = Tween.propHooks[ this.prop ];
return hooks && hooks.get ?
hooks.get( this ) :
Tween.propHooks._default.get( this );
},
run: function( percent ) {
var eased,
hooks = Tween.propHooks[ this.prop ];
if ( this.options.duration ) {
this.pos = eased = jQuery.easing[ this.easing ](
percent, this.options.duration * percent, 0, 1, this.options.duration
);
} else {
this.pos = eased = percent;
}
this.now = ( this.end - this.start ) * eased + this.start;
if ( this.options.step ) {
this.options.step.call( this.elem, this.now, this );
}
if ( hooks && hooks.set ) {
hooks.set( this );
} else {
Tween.propHooks._default.set( this );
}
return this;
}
};
Tween.prototype.init.prototype = Tween.prototype;
Tween.propHooks = {
_default: {
get: function( tween ) {
var result;
if ( tween.elem[ tween.prop ] != null &&
(!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) {
return tween.elem[ tween.prop ];
}
// Passing an empty string as a 3rd parameter to .css will automatically
// attempt a parseFloat and fallback to a string if the parse fails.
// Simple values such as "10px" are parsed to Float;
// complex values such as "rotate(1rad)" are returned as-is.
result = jQuery.css( tween.elem, tween.prop, "" );
// Empty strings, null, undefined and "auto" are converted to 0.
return !result || result === "auto" ? 0 : result;
},
set: function( tween ) {
// Use step hook for back compat.
// Use cssHook if its there.
// Use .style if available and use plain properties where available.
if ( jQuery.fx.step[ tween.prop ] ) {
jQuery.fx.step[ tween.prop ]( tween );
} else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) {
jQuery.style( tween.elem, tween.prop, tween.now + tween.unit );
} else {
tween.elem[ tween.prop ] = tween.now;
}
}
}
};
// Support: IE9
// Panic based approach to setting things on disconnected nodes
Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = {
set: function( tween ) {
if ( tween.elem.nodeType && tween.elem.parentNode ) {
tween.elem[ tween.prop ] = tween.now;
}
}
};
jQuery.easing = {
linear: function( p ) {
return p;
},
swing: function( p ) {
return 0.5 - Math.cos( p * Math.PI ) / 2;
}
};
jQuery.fx = Tween.prototype.init;
// Back Compat <1.8 extension point
jQuery.fx.step = {};
var
fxNow, timerId,
rfxtypes = /^(?:toggle|show|hide)$/,
rfxnum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ),
rrun = /queueHooks$/,
animationPrefilters = [ defaultPrefilter ],
tweeners = {
"*": [ function( prop, value ) {
var tween = this.createTween( prop, value ),
target = tween.cur(),
parts = rfxnum.exec( value ),
unit = parts && parts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ),
// Starting value computation is required for potential unit mismatches
start = ( jQuery.cssNumber[ prop ] || unit !== "px" && +target ) &&
rfxnum.exec( jQuery.css( tween.elem, prop ) ),
scale = 1,
maxIterations = 20;
if ( start && start[ 3 ] !== unit ) {
// Trust units reported by jQuery.css
unit = unit || start[ 3 ];
// Make sure we update the tween properties later on
parts = parts || [];
// Iteratively approximate from a nonzero starting point
start = +target || 1;
do {
// If previous iteration zeroed out, double until we get *something*.
// Use string for doubling so we don't accidentally see scale as unchanged below
scale = scale || ".5";
// Adjust and apply
start = start / scale;
jQuery.style( tween.elem, prop, start + unit );
// Update scale, tolerating zero or NaN from tween.cur(),
// break the loop if scale is unchanged or perfect, or if we've just had enough
} while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations );
}
// Update tween properties
if ( parts ) {
start = tween.start = +start || +target || 0;
tween.unit = unit;
// If a +=/-= token was provided, we're doing a relative animation
tween.end = parts[ 1 ] ?
start + ( parts[ 1 ] + 1 ) * parts[ 2 ] :
+parts[ 2 ];
}
return tween;
} ]
};
// Animations created synchronously will run synchronously
function createFxNow() {
setTimeout(function() {
fxNow = undefined;
});
return ( fxNow = jQuery.now() );
}
// Generate parameters to create a standard animation
function genFx( type, includeWidth ) {
var which,
i = 0,
attrs = { height: type };
// If we include width, step value is 1 to do all cssExpand values,
// otherwise step value is 2 to skip over Left and Right
includeWidth = includeWidth ? 1 : 0;
for ( ; i < 4 ; i += 2 - includeWidth ) {
which = cssExpand[ i ];
attrs[ "margin" + which ] = attrs[ "padding" + which ] = type;
}
if ( includeWidth ) {
attrs.opacity = attrs.width = type;
}
return attrs;
}
function createTween( value, prop, animation ) {
var tween,
collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ),
index = 0,
length = collection.length;
for ( ; index < length; index++ ) {
if ( (tween = collection[ index ].call( animation, prop, value )) ) {
// We're done with this property
return tween;
}
}
}
function defaultPrefilter( elem, props, opts ) {
/* jshint validthis: true */
var prop, value, toggle, tween, hooks, oldfire, display, checkDisplay,
anim = this,
orig = {},
style = elem.style,
hidden = elem.nodeType && isHidden( elem ),
dataShow = data_priv.get( elem, "fxshow" );
// Handle queue: false promises
if ( !opts.queue ) {
hooks = jQuery._queueHooks( elem, "fx" );
if ( hooks.unqueued == null ) {
hooks.unqueued = 0;
oldfire = hooks.empty.fire;
hooks.empty.fire = function() {
if ( !hooks.unqueued ) {
oldfire();
}
};
}
hooks.unqueued++;
anim.always(function() {
// Ensure the complete handler is called before this completes
anim.always(function() {
hooks.unqueued--;
if ( !jQuery.queue( elem, "fx" ).length ) {
hooks.empty.fire();
}
});
});
}
// Height/width overflow pass
if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) {
// Make sure that nothing sneaks out
// Record all 3 overflow attributes because IE9-10 do not
// change the overflow attribute when overflowX and
// overflowY are set to the same value
opts.overflow = [ style.overflow, style.overflowX, style.overflowY ];
// Set display property to inline-block for height/width
// animations on inline elements that are having width/height animated
display = jQuery.css( elem, "display" );
// Test default display if display is currently "none"
checkDisplay = display === "none" ?
data_priv.get( elem, "olddisplay" ) || defaultDisplay( elem.nodeName ) : display;
if ( checkDisplay === "inline" && jQuery.css( elem, "float" ) === "none" ) {
style.display = "inline-block";
}
}
if ( opts.overflow ) {
style.overflow = "hidden";
anim.always(function() {
style.overflow = opts.overflow[ 0 ];
style.overflowX = opts.overflow[ 1 ];
style.overflowY = opts.overflow[ 2 ];
});
}
// show/hide pass
for ( prop in props ) {
value = props[ prop ];
if ( rfxtypes.exec( value ) ) {
delete props[ prop ];
toggle = toggle || value === "toggle";
if ( value === ( hidden ? "hide" : "show" ) ) {
// If there is dataShow left over from a stopped hide or show and we are going to proceed with show, we should pretend to be hidden
if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) {
hidden = true;
} else {
continue;
}
}
orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop );
// Any non-fx value stops us from restoring the original display value
} else {
display = undefined;
}
}
if ( !jQuery.isEmptyObject( orig ) ) {
if ( dataShow ) {
if ( "hidden" in dataShow ) {
hidden = dataShow.hidden;
}
} else {
dataShow = data_priv.access( elem, "fxshow", {} );
}
// Store state if its toggle - enables .stop().toggle() to "reverse"
if ( toggle ) {
dataShow.hidden = !hidden;
}
if ( hidden ) {
jQuery( elem ).show();
} else {
anim.done(function() {
jQuery( elem ).hide();
});
}
anim.done(function() {
var prop;
data_priv.remove( elem, "fxshow" );
for ( prop in orig ) {
jQuery.style( elem, prop, orig[ prop ] );
}
});
for ( prop in orig ) {
tween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim );
if ( !( prop in dataShow ) ) {
dataShow[ prop ] = tween.start;
if ( hidden ) {
tween.end = tween.start;
tween.start = prop === "width" || prop === "height" ? 1 : 0;
}
}
}
// If this is a noop like .hide().hide(), restore an overwritten display value
} else if ( (display === "none" ? defaultDisplay( elem.nodeName ) : display) === "inline" ) {
style.display = display;
}
}
function propFilter( props, specialEasing ) {
var index, name, easing, value, hooks;
// camelCase, specialEasing and expand cssHook pass
for ( index in props ) {
name = jQuery.camelCase( index );
easing = specialEasing[ name ];
value = props[ index ];
if ( jQuery.isArray( value ) ) {
easing = value[ 1 ];
value = props[ index ] = value[ 0 ];
}
if ( index !== name ) {
props[ name ] = value;
delete props[ index ];
}
hooks = jQuery.cssHooks[ name ];
if ( hooks && "expand" in hooks ) {
value = hooks.expand( value );
delete props[ name ];
// Not quite $.extend, this won't overwrite existing keys.
// Reusing 'index' because we have the correct "name"
for ( index in value ) {
if ( !( index in props ) ) {
props[ index ] = value[ index ];
specialEasing[ index ] = easing;
}
}
} else {
specialEasing[ name ] = easing;
}
}
}
function Animation( elem, properties, options ) {
var result,
stopped,
index = 0,
length = animationPrefilters.length,
deferred = jQuery.Deferred().always( function() {
// Don't match elem in the :animated selector
delete tick.elem;
}),
tick = function() {
if ( stopped ) {
return false;
}
var currentTime = fxNow || createFxNow(),
remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ),
// Support: Android 2.3
// Archaic crash bug won't allow us to use `1 - ( 0.5 || 0 )` (#12497)
temp = remaining / animation.duration || 0,
percent = 1 - temp,
index = 0,
length = animation.tweens.length;
for ( ; index < length ; index++ ) {
animation.tweens[ index ].run( percent );
}
deferred.notifyWith( elem, [ animation, percent, remaining ]);
if ( percent < 1 && length ) {
return remaining;
} else {
deferred.resolveWith( elem, [ animation ] );
return false;
}
},
animation = deferred.promise({
elem: elem,
props: jQuery.extend( {}, properties ),
opts: jQuery.extend( true, { specialEasing: {} }, options ),
originalProperties: properties,
originalOptions: options,
startTime: fxNow || createFxNow(),
duration: options.duration,
tweens: [],
createTween: function( prop, end ) {
var tween = jQuery.Tween( elem, animation.opts, prop, end,
animation.opts.specialEasing[ prop ] || animation.opts.easing );
animation.tweens.push( tween );
return tween;
},
stop: function( gotoEnd ) {
var index = 0,
// If we are going to the end, we want to run all the tweens
// otherwise we skip this part
length = gotoEnd ? animation.tweens.length : 0;
if ( stopped ) {
return this;
}
stopped = true;
for ( ; index < length ; index++ ) {
animation.tweens[ index ].run( 1 );
}
// Resolve when we played the last frame; otherwise, reject
if ( gotoEnd ) {
deferred.resolveWith( elem, [ animation, gotoEnd ] );
} else {
deferred.rejectWith( elem, [ animation, gotoEnd ] );
}
return this;
}
}),
props = animation.props;
propFilter( props, animation.opts.specialEasing );
for ( ; index < length ; index++ ) {
result = animationPrefilters[ index ].call( animation, elem, props, animation.opts );
if ( result ) {
return result;
}
}
jQuery.map( props, createTween, animation );
if ( jQuery.isFunction( animation.opts.start ) ) {
animation.opts.start.call( elem, animation );
}
jQuery.fx.timer(
jQuery.extend( tick, {
elem: elem,
anim: animation,
queue: animation.opts.queue
})
);
// attach callbacks from options
return animation.progress( animation.opts.progress )
.done( animation.opts.done, animation.opts.complete )
.fail( animation.opts.fail )
.always( animation.opts.always );
}
jQuery.Animation = jQuery.extend( Animation, {
tweener: function( props, callback ) {
if ( jQuery.isFunction( props ) ) {
callback = props;
props = [ "*" ];
} else {
props = props.split(" ");
}
var prop,
index = 0,
length = props.length;
for ( ; index < length ; index++ ) {
prop = props[ index ];
tweeners[ prop ] = tweeners[ prop ] || [];
tweeners[ prop ].unshift( callback );
}
},
prefilter: function( callback, prepend ) {
if ( prepend ) {
animationPrefilters.unshift( callback );
} else {
animationPrefilters.push( callback );
}
}
});
jQuery.speed = function( speed, easing, fn ) {
var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : {
complete: fn || !fn && easing ||
jQuery.isFunction( speed ) && speed,
duration: speed,
easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing
};
opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default;
// Normalize opt.queue - true/undefined/null -> "fx"
if ( opt.queue == null || opt.queue === true ) {
opt.queue = "fx";
}
// Queueing
opt.old = opt.complete;
opt.complete = function() {
if ( jQuery.isFunction( opt.old ) ) {
opt.old.call( this );
}
if ( opt.queue ) {
jQuery.dequeue( this, opt.queue );
}
};
return opt;
};
jQuery.fn.extend({
fadeTo: function( speed, to, easing, callback ) {
// Show any hidden elements after setting opacity to 0
return this.filter( isHidden ).css( "opacity", 0 ).show()
// Animate to the value specified
.end().animate({ opacity: to }, speed, easing, callback );
},
animate: function( prop, speed, easing, callback ) {
var empty = jQuery.isEmptyObject( prop ),
optall = jQuery.speed( speed, easing, callback ),
doAnimation = function() {
// Operate on a copy of prop so per-property easing won't be lost
var anim = Animation( this, jQuery.extend( {}, prop ), optall );
// Empty animations, or finishing resolves immediately
if ( empty || data_priv.get( this, "finish" ) ) {
anim.stop( true );
}
};
doAnimation.finish = doAnimation;
return empty || optall.queue === false ?
this.each( doAnimation ) :
this.queue( optall.queue, doAnimation );
},
stop: function( type, clearQueue, gotoEnd ) {
var stopQueue = function( hooks ) {
var stop = hooks.stop;
delete hooks.stop;
stop( gotoEnd );
};
if ( typeof type !== "string" ) {
gotoEnd = clearQueue;
clearQueue = type;
type = undefined;
}
if ( clearQueue && type !== false ) {
this.queue( type || "fx", [] );
}
return this.each(function() {
var dequeue = true,
index = type != null && type + "queueHooks",
timers = jQuery.timers,
data = data_priv.get( this );
if ( index ) {
if ( data[ index ] && data[ index ].stop ) {
stopQueue( data[ index ] );
}
} else {
for ( index in data ) {
if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) {
stopQueue( data[ index ] );
}
}
}
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) {
timers[ index ].anim.stop( gotoEnd );
dequeue = false;
timers.splice( index, 1 );
}
}
// Start the next in the queue if the last step wasn't forced.
// Timers currently will call their complete callbacks, which
// will dequeue but only if they were gotoEnd.
if ( dequeue || !gotoEnd ) {
jQuery.dequeue( this, type );
}
});
},
finish: function( type ) {
if ( type !== false ) {
type = type || "fx";
}
return this.each(function() {
var index,
data = data_priv.get( this ),
queue = data[ type + "queue" ],
hooks = data[ type + "queueHooks" ],
timers = jQuery.timers,
length = queue ? queue.length : 0;
// Enable finishing flag on private data
data.finish = true;
// Empty the queue first
jQuery.queue( this, type, [] );
if ( hooks && hooks.stop ) {
hooks.stop.call( this, true );
}
// Look for any active animations, and finish them
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this && timers[ index ].queue === type ) {
timers[ index ].anim.stop( true );
timers.splice( index, 1 );
}
}
// Look for any animations in the old queue and finish them
for ( index = 0; index < length; index++ ) {
if ( queue[ index ] && queue[ index ].finish ) {
queue[ index ].finish.call( this );
}
}
// Turn off finishing flag
delete data.finish;
});
}
});
jQuery.each([ "toggle", "show", "hide" ], function( i, name ) {
var cssFn = jQuery.fn[ name ];
jQuery.fn[ name ] = function( speed, easing, callback ) {
return speed == null || typeof speed === "boolean" ?
cssFn.apply( this, arguments ) :
this.animate( genFx( name, true ), speed, easing, callback );
};
});
// Generate shortcuts for custom animations
jQuery.each({
slideDown: genFx("show"),
slideUp: genFx("hide"),
slideToggle: genFx("toggle"),
fadeIn: { opacity: "show" },
fadeOut: { opacity: "hide" },
fadeToggle: { opacity: "toggle" }
}, function( name, props ) {
jQuery.fn[ name ] = function( speed, easing, callback ) {
return this.animate( props, speed, easing, callback );
};
});
jQuery.timers = [];
jQuery.fx.tick = function() {
var timer,
i = 0,
timers = jQuery.timers;
fxNow = jQuery.now();
for ( ; i < timers.length; i++ ) {
timer = timers[ i ];
// Checks the timer has not already been removed
if ( !timer() && timers[ i ] === timer ) {
timers.splice( i--, 1 );
}
}
if ( !timers.length ) {
jQuery.fx.stop();
}
fxNow = undefined;
};
jQuery.fx.timer = function( timer ) {
jQuery.timers.push( timer );
if ( timer() ) {
jQuery.fx.start();
} else {
jQuery.timers.pop();
}
};
jQuery.fx.interval = 13;
jQuery.fx.start = function() {
if ( !timerId ) {
timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval );
}
};
jQuery.fx.stop = function() {
clearInterval( timerId );
timerId = null;
};
jQuery.fx.speeds = {
slow: 600,
fast: 200,
// Default speed
_default: 400
};
// Based off of the plugin by Clint Helfers, with permission.
// http://blindsignals.com/index.php/2009/07/jquery-delay/
jQuery.fn.delay = function( time, type ) {
time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
type = type || "fx";
return this.queue( type, function( next, hooks ) {
var timeout = setTimeout( next, time );
hooks.stop = function() {
clearTimeout( timeout );
};
});
};
(function() {
var input = document.createElement( "input" ),
select = document.createElement( "select" ),
opt = select.appendChild( document.createElement( "option" ) );
input.type = "checkbox";
// Support: iOS<=5.1, Android<=4.2+
// Default value for a checkbox should be "on"
support.checkOn = input.value !== "";
// Support: IE<=11+
// Must access selectedIndex to make default options select
support.optSelected = opt.selected;
// Support: Android<=2.3
// Options inside disabled selects are incorrectly marked as disabled
select.disabled = true;
support.optDisabled = !opt.disabled;
// Support: IE<=11+
// An input loses its value after becoming a radio
input = document.createElement( "input" );
input.value = "t";
input.type = "radio";
support.radioValue = input.value === "t";
})();
var nodeHook, boolHook,
attrHandle = jQuery.expr.attrHandle;
jQuery.fn.extend({
attr: function( name, value ) {
return access( this, jQuery.attr, name, value, arguments.length > 1 );
},
removeAttr: function( name ) {
return this.each(function() {
jQuery.removeAttr( this, name );
});
}
});
jQuery.extend({
attr: function( elem, name, value ) {
var hooks, ret,
nType = elem.nodeType;
// don't get/set attributes on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
// Fallback to prop when attributes are not supported
if ( typeof elem.getAttribute === strundefined ) {
return jQuery.prop( elem, name, value );
}
// All attributes are lowercase
// Grab necessary hook if one is defined
if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
name = name.toLowerCase();
hooks = jQuery.attrHooks[ name ] ||
( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook );
}
if ( value !== undefined ) {
if ( value === null ) {
jQuery.removeAttr( elem, name );
} else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
elem.setAttribute( name, value + "" );
return value;
}
} else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
ret = jQuery.find.attr( elem, name );
// Non-existent attributes return null, we normalize to undefined
return ret == null ?
undefined :
ret;
}
},
removeAttr: function( elem, value ) {
var name, propName,
i = 0,
attrNames = value && value.match( rnotwhite );
if ( attrNames && elem.nodeType === 1 ) {
while ( (name = attrNames[i++]) ) {
propName = jQuery.propFix[ name ] || name;
// Boolean attributes get special treatment (#10870)
if ( jQuery.expr.match.bool.test( name ) ) {
// Set corresponding property to false
elem[ propName ] = false;
}
elem.removeAttribute( name );
}
}
},
attrHooks: {
type: {
set: function( elem, value ) {
if ( !support.radioValue && value === "radio" &&
jQuery.nodeName( elem, "input" ) ) {
var val = elem.value;
elem.setAttribute( "type", value );
if ( val ) {
elem.value = val;
}
return value;
}
}
}
}
});
// Hooks for boolean attributes
boolHook = {
set: function( elem, value, name ) {
if ( value === false ) {
// Remove boolean attributes when set to false
jQuery.removeAttr( elem, name );
} else {
elem.setAttribute( name, name );
}
return name;
}
};
jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) {
var getter = attrHandle[ name ] || jQuery.find.attr;
attrHandle[ name ] = function( elem, name, isXML ) {
var ret, handle;
if ( !isXML ) {
// Avoid an infinite loop by temporarily removing this function from the getter
handle = attrHandle[ name ];
attrHandle[ name ] = ret;
ret = getter( elem, name, isXML ) != null ?
name.toLowerCase() :
null;
attrHandle[ name ] = handle;
}
return ret;
};
});
var rfocusable = /^(?:input|select|textarea|button)$/i;
jQuery.fn.extend({
prop: function( name, value ) {
return access( this, jQuery.prop, name, value, arguments.length > 1 );
},
removeProp: function( name ) {
return this.each(function() {
delete this[ jQuery.propFix[ name ] || name ];
});
}
});
jQuery.extend({
propFix: {
"for": "htmlFor",
"class": "className"
},
prop: function( elem, name, value ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// Don't get/set properties on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
if ( notxml ) {
// Fix name and attach hooks
name = jQuery.propFix[ name ] || name;
hooks = jQuery.propHooks[ name ];
}
if ( value !== undefined ) {
return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ?
ret :
( elem[ name ] = value );
} else {
return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ?
ret :
elem[ name ];
}
},
propHooks: {
tabIndex: {
get: function( elem ) {
return elem.hasAttribute( "tabindex" ) || rfocusable.test( elem.nodeName ) || elem.href ?
elem.tabIndex :
-1;
}
}
}
});
if ( !support.optSelected ) {
jQuery.propHooks.selected = {
get: function( elem ) {
var parent = elem.parentNode;
if ( parent && parent.parentNode ) {
parent.parentNode.selectedIndex;
}
return null;
}
};
}
jQuery.each([
"tabIndex",
"readOnly",
"maxLength",
"cellSpacing",
"cellPadding",
"rowSpan",
"colSpan",
"useMap",
"frameBorder",
"contentEditable"
], function() {
jQuery.propFix[ this.toLowerCase() ] = this;
});
var rclass = /[\t\r\n\f]/g;
jQuery.fn.extend({
addClass: function( value ) {
var classes, elem, cur, clazz, j, finalValue,
proceed = typeof value === "string" && value,
i = 0,
len = this.length;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).addClass( value.call( this, j, this.className ) );
});
}
if ( proceed ) {
// The disjunction here is for better compressibility (see removeClass)
classes = ( value || "" ).match( rnotwhite ) || [];
for ( ; i < len; i++ ) {
elem = this[ i ];
cur = elem.nodeType === 1 && ( elem.className ?
( " " + elem.className + " " ).replace( rclass, " " ) :
" "
);
if ( cur ) {
j = 0;
while ( (clazz = classes[j++]) ) {
if ( cur.indexOf( " " + clazz + " " ) < 0 ) {
cur += clazz + " ";
}
}
// only assign if different to avoid unneeded rendering.
finalValue = jQuery.trim( cur );
if ( elem.className !== finalValue ) {
elem.className = finalValue;
}
}
}
}
return this;
},
removeClass: function( value ) {
var classes, elem, cur, clazz, j, finalValue,
proceed = arguments.length === 0 || typeof value === "string" && value,
i = 0,
len = this.length;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).removeClass( value.call( this, j, this.className ) );
});
}
if ( proceed ) {
classes = ( value || "" ).match( rnotwhite ) || [];
for ( ; i < len; i++ ) {
elem = this[ i ];
// This expression is here for better compressibility (see addClass)
cur = elem.nodeType === 1 && ( elem.className ?
( " " + elem.className + " " ).replace( rclass, " " ) :
""
);
if ( cur ) {
j = 0;
while ( (clazz = classes[j++]) ) {
// Remove *all* instances
while ( cur.indexOf( " " + clazz + " " ) >= 0 ) {
cur = cur.replace( " " + clazz + " ", " " );
}
}
// Only assign if different to avoid unneeded rendering.
finalValue = value ? jQuery.trim( cur ) : "";
if ( elem.className !== finalValue ) {
elem.className = finalValue;
}
}
}
}
return this;
},
toggleClass: function( value, stateVal ) {
var type = typeof value;
if ( typeof stateVal === "boolean" && type === "string" ) {
return stateVal ? this.addClass( value ) : this.removeClass( value );
}
if ( jQuery.isFunction( value ) ) {
return this.each(function( i ) {
jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal );
});
}
return this.each(function() {
if ( type === "string" ) {
// Toggle individual class names
var className,
i = 0,
self = jQuery( this ),
classNames = value.match( rnotwhite ) || [];
while ( (className = classNames[ i++ ]) ) {
// Check each className given, space separated list
if ( self.hasClass( className ) ) {
self.removeClass( className );
} else {
self.addClass( className );
}
}
// Toggle whole class name
} else if ( type === strundefined || type === "boolean" ) {
if ( this.className ) {
// store className if set
data_priv.set( this, "__className__", this.className );
}
// If the element has a class name or if we're passed `false`,
// then remove the whole classname (if there was one, the above saved it).
// Otherwise bring back whatever was previously saved (if anything),
// falling back to the empty string if nothing was stored.
this.className = this.className || value === false ? "" : data_priv.get( this, "__className__" ) || "";
}
});
},
hasClass: function( selector ) {
var className = " " + selector + " ",
i = 0,
l = this.length;
for ( ; i < l; i++ ) {
if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) {
return true;
}
}
return false;
}
});
var rreturn = /\r/g;
jQuery.fn.extend({
val: function( value ) {
var hooks, ret, isFunction,
elem = this[0];
if ( !arguments.length ) {
if ( elem ) {
hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];
if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
return ret;
}
ret = elem.value;
return typeof ret === "string" ?
// Handle most common string cases
ret.replace(rreturn, "") :
// Handle cases where value is null/undef or number
ret == null ? "" : ret;
}
return;
}
isFunction = jQuery.isFunction( value );
return this.each(function( i ) {
var val;
if ( this.nodeType !== 1 ) {
return;
}
if ( isFunction ) {
val = value.call( this, i, jQuery( this ).val() );
} else {
val = value;
}
// Treat null/undefined as ""; convert numbers to string
if ( val == null ) {
val = "";
} else if ( typeof val === "number" ) {
val += "";
} else if ( jQuery.isArray( val ) ) {
val = jQuery.map( val, function( value ) {
return value == null ? "" : value + "";
});
}
hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];
// If set returns undefined, fall back to normal setting
if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
this.value = val;
}
});
}
});
jQuery.extend({
valHooks: {
option: {
get: function( elem ) {
var val = jQuery.find.attr( elem, "value" );
return val != null ?
val :
// Support: IE10-11+
// option.text throws exceptions (#14686, #14858)
jQuery.trim( jQuery.text( elem ) );
}
},
select: {
get: function( elem ) {
var value, option,
options = elem.options,
index = elem.selectedIndex,
one = elem.type === "select-one" || index < 0,
values = one ? null : [],
max = one ? index + 1 : options.length,
i = index < 0 ?
max :
one ? index : 0;
// Loop through all the selected options
for ( ; i < max; i++ ) {
option = options[ i ];
// IE6-9 doesn't update selected after form reset (#2551)
if ( ( option.selected || i === index ) &&
// Don't return options that are disabled or in a disabled optgroup
( support.optDisabled ? !option.disabled : option.getAttribute( "disabled" ) === null ) &&
( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) {
// Get the specific value for the option
value = jQuery( option ).val();
// We don't need an array for one selects
if ( one ) {
return value;
}
// Multi-Selects return an array
values.push( value );
}
}
return values;
},
set: function( elem, value ) {
var optionSet, option,
options = elem.options,
values = jQuery.makeArray( value ),
i = options.length;
while ( i-- ) {
option = options[ i ];
if ( (option.selected = jQuery.inArray( option.value, values ) >= 0) ) {
optionSet = true;
}
}
// Force browsers to behave consistently when non-matching value is set
if ( !optionSet ) {
elem.selectedIndex = -1;
}
return values;
}
}
}
});
// Radios and checkboxes getter/setter
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = {
set: function( elem, value ) {
if ( jQuery.isArray( value ) ) {
return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 );
}
}
};
if ( !support.checkOn ) {
jQuery.valHooks[ this ].get = function( elem ) {
return elem.getAttribute("value") === null ? "on" : elem.value;
};
}
});
// Return jQuery for attributes-only inclusion
jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
"change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) {
// Handle event binding
jQuery.fn[ name ] = function( data, fn ) {
return arguments.length > 0 ?
this.on( name, null, data, fn ) :
this.trigger( name );
};
});
jQuery.fn.extend({
hover: function( fnOver, fnOut ) {
return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
},
bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
},
unbind: function( types, fn ) {
return this.off( types, null, fn );
},
delegate: function( selector, types, data, fn ) {
return this.on( types, selector, data, fn );
},
undelegate: function( selector, types, fn ) {
// ( namespace ) or ( selector, types [, fn] )
return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn );
}
});
var nonce = jQuery.now();
var rquery = (/\?/);
// Support: Android 2.3
// Workaround failure to string-cast null input
jQuery.parseJSON = function( data ) {
return JSON.parse( data + "" );
};
// Cross-browser xml parsing
jQuery.parseXML = function( data ) {
var xml, tmp;
if ( !data || typeof data !== "string" ) {
return null;
}
// Support: IE9
try {
tmp = new DOMParser();
xml = tmp.parseFromString( data, "text/xml" );
} catch ( e ) {
xml = undefined;
}
if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
};
var
rhash = /#.*$/,
rts = /([?&])_=[^&]*/,
rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg,
// #7653, #8125, #8152: local protocol detection
rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/,
rnoContent = /^(?:GET|HEAD)$/,
rprotocol = /^\/\//,
rurl = /^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,
/* Prefilters
* 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
* 2) These are called:
* - BEFORE asking for a transport
* - AFTER param serialization (s.data is a string if s.processData is true)
* 3) key is the dataType
* 4) the catchall symbol "*" can be used
* 5) execution will start with transport dataType and THEN continue down to "*" if needed
*/
prefilters = {},
/* Transports bindings
* 1) key is the dataType
* 2) the catchall symbol "*" can be used
* 3) selection will start with transport dataType and THEN go to "*" if needed
*/
transports = {},
// Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
allTypes = "*/".concat( "*" ),
// Document location
ajaxLocation = window.location.href,
// Segment location into parts
ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];
// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
function addToPrefiltersOrTransports( structure ) {
// dataTypeExpression is optional and defaults to "*"
return function( dataTypeExpression, func ) {
if ( typeof dataTypeExpression !== "string" ) {
func = dataTypeExpression;
dataTypeExpression = "*";
}
var dataType,
i = 0,
dataTypes = dataTypeExpression.toLowerCase().match( rnotwhite ) || [];
if ( jQuery.isFunction( func ) ) {
// For each dataType in the dataTypeExpression
while ( (dataType = dataTypes[i++]) ) {
// Prepend if requested
if ( dataType[0] === "+" ) {
dataType = dataType.slice( 1 ) || "*";
(structure[ dataType ] = structure[ dataType ] || []).unshift( func );
// Otherwise append
} else {
(structure[ dataType ] = structure[ dataType ] || []).push( func );
}
}
}
};
}
// Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) {
var inspected = {},
seekingTransport = ( structure === transports );
function inspect( dataType ) {
var selected;
inspected[ dataType ] = true;
jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) {
var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR );
if ( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) {
options.dataTypes.unshift( dataTypeOrTransport );
inspect( dataTypeOrTransport );
return false;
} else if ( seekingTransport ) {
return !( selected = dataTypeOrTransport );
}
});
return selected;
}
return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" );
}
// A special extend for ajax options
// that takes "flat" options (not to be deep extended)
// Fixes #9887
function ajaxExtend( target, src ) {
var key, deep,
flatOptions = jQuery.ajaxSettings.flatOptions || {};
for ( key in src ) {
if ( src[ key ] !== undefined ) {
( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ];
}
}
if ( deep ) {
jQuery.extend( true, target, deep );
}
return target;
}
/* Handles responses to an ajax request:
* - finds the right dataType (mediates between content-type and expected dataType)
* - returns the corresponding response
*/
function ajaxHandleResponses( s, jqXHR, responses ) {
var ct, type, finalDataType, firstDataType,
contents = s.contents,
dataTypes = s.dataTypes;
// Remove auto dataType and get content-type in the process
while ( dataTypes[ 0 ] === "*" ) {
dataTypes.shift();
if ( ct === undefined ) {
ct = s.mimeType || jqXHR.getResponseHeader("Content-Type");
}
}
// Check if we're dealing with a known content-type
if ( ct ) {
for ( type in contents ) {
if ( contents[ type ] && contents[ type ].test( ct ) ) {
dataTypes.unshift( type );
break;
}
}
}
// Check to see if we have a response for the expected dataType
if ( dataTypes[ 0 ] in responses ) {
finalDataType = dataTypes[ 0 ];
} else {
// Try convertible dataTypes
for ( type in responses ) {
if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
finalDataType = type;
break;
}
if ( !firstDataType ) {
firstDataType = type;
}
}
// Or just use first one
finalDataType = finalDataType || firstDataType;
}
// If we found a dataType
// We add the dataType to the list if needed
// and return the corresponding response
if ( finalDataType ) {
if ( finalDataType !== dataTypes[ 0 ] ) {
dataTypes.unshift( finalDataType );
}
return responses[ finalDataType ];
}
}
/* Chain conversions given the request and the original response
* Also sets the responseXXX fields on the jqXHR instance
*/
function ajaxConvert( s, response, jqXHR, isSuccess ) {
var conv2, current, conv, tmp, prev,
converters = {},
// Work with a copy of dataTypes in case we need to modify it for conversion
dataTypes = s.dataTypes.slice();
// Create converters map with lowercased keys
if ( dataTypes[ 1 ] ) {
for ( conv in s.converters ) {
converters[ conv.toLowerCase() ] = s.converters[ conv ];
}
}
current = dataTypes.shift();
// Convert to each sequential dataType
while ( current ) {
if ( s.responseFields[ current ] ) {
jqXHR[ s.responseFields[ current ] ] = response;
}
// Apply the dataFilter if provided
if ( !prev && isSuccess && s.dataFilter ) {
response = s.dataFilter( response, s.dataType );
}
prev = current;
current = dataTypes.shift();
if ( current ) {
// There's only work to do if current dataType is non-auto
if ( current === "*" ) {
current = prev;
// Convert response if prev dataType is non-auto and differs from current
} else if ( prev !== "*" && prev !== current ) {
// Seek a direct converter
conv = converters[ prev + " " + current ] || converters[ "* " + current ];
// If none found, seek a pair
if ( !conv ) {
for ( conv2 in converters ) {
// If conv2 outputs current
tmp = conv2.split( " " );
if ( tmp[ 1 ] === current ) {
// If prev can be converted to accepted input
conv = converters[ prev + " " + tmp[ 0 ] ] ||
converters[ "* " + tmp[ 0 ] ];
if ( conv ) {
// Condense equivalence converters
if ( conv === true ) {
conv = converters[ conv2 ];
// Otherwise, insert the intermediate dataType
} else if ( converters[ conv2 ] !== true ) {
current = tmp[ 0 ];
dataTypes.unshift( tmp[ 1 ] );
}
break;
}
}
}
}
// Apply converter (if not an equivalence)
if ( conv !== true ) {
// Unless errors are allowed to bubble, catch and return them
if ( conv && s[ "throws" ] ) {
response = conv( response );
} else {
try {
response = conv( response );
} catch ( e ) {
return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current };
}
}
}
}
}
}
return { state: "success", data: response };
}
jQuery.extend({
// Counter for holding the number of active queries
active: 0,
// Last-Modified header cache for next request
lastModified: {},
etag: {},
ajaxSettings: {
url: ajaxLocation,
type: "GET",
isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
global: true,
processData: true,
async: true,
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
/*
timeout: 0,
data: null,
dataType: null,
username: null,
password: null,
cache: null,
throws: false,
traditional: false,
headers: {},
*/
accepts: {
"*": allTypes,
text: "text/plain",
html: "text/html",
xml: "application/xml, text/xml",
json: "application/json, text/javascript"
},
contents: {
xml: /xml/,
html: /html/,
json: /json/
},
responseFields: {
xml: "responseXML",
text: "responseText",
json: "responseJSON"
},
// Data converters
// Keys separate source (or catchall "*") and destination types with a single space
converters: {
// Convert anything to text
"* text": String,
// Text to html (true = no transformation)
"text html": true,
// Evaluate text as a json expression
"text json": jQuery.parseJSON,
// Parse text as xml
"text xml": jQuery.parseXML
},
// For options that shouldn't be deep extended:
// you can add your own custom options here if
// and when you create one that shouldn't be
// deep extended (see ajaxExtend)
flatOptions: {
url: true,
context: true
}
},
// Creates a full fledged settings object into target
// with both ajaxSettings and settings fields.
// If target is omitted, writes into ajaxSettings.
ajaxSetup: function( target, settings ) {
return settings ?
// Building a settings object
ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) :
// Extending ajaxSettings
ajaxExtend( jQuery.ajaxSettings, target );
},
ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
ajaxTransport: addToPrefiltersOrTransports( transports ),
// Main method
ajax: function( url, options ) {
// If url is an object, simulate pre-1.5 signature
if ( typeof url === "object" ) {
options = url;
url = undefined;
}
// Force options to be an object
options = options || {};
var transport,
// URL without anti-cache param
cacheURL,
// Response headers
responseHeadersString,
responseHeaders,
// timeout handle
timeoutTimer,
// Cross-domain detection vars
parts,
// To know if global events are to be dispatched
fireGlobals,
// Loop variable
i,
// Create the final options object
s = jQuery.ajaxSetup( {}, options ),
// Callbacks context
callbackContext = s.context || s,
// Context for global events is callbackContext if it is a DOM node or jQuery collection
globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ?
jQuery( callbackContext ) :
jQuery.event,
// Deferreds
deferred = jQuery.Deferred(),
completeDeferred = jQuery.Callbacks("once memory"),
// Status-dependent callbacks
statusCode = s.statusCode || {},
// Headers (they are sent all at once)
requestHeaders = {},
requestHeadersNames = {},
// The jqXHR state
state = 0,
// Default abort message
strAbort = "canceled",
// Fake xhr
jqXHR = {
readyState: 0,
// Builds headers hashtable if needed
getResponseHeader: function( key ) {
var match;
if ( state === 2 ) {
if ( !responseHeaders ) {
responseHeaders = {};
while ( (match = rheaders.exec( responseHeadersString )) ) {
responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
}
}
match = responseHeaders[ key.toLowerCase() ];
}
return match == null ? null : match;
},
// Raw string
getAllResponseHeaders: function() {
return state === 2 ? responseHeadersString : null;
},
// Caches the header
setRequestHeader: function( name, value ) {
var lname = name.toLowerCase();
if ( !state ) {
name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
requestHeaders[ name ] = value;
}
return this;
},
// Overrides response content-type header
overrideMimeType: function( type ) {
if ( !state ) {
s.mimeType = type;
}
return this;
},
// Status-dependent callbacks
statusCode: function( map ) {
var code;
if ( map ) {
if ( state < 2 ) {
for ( code in map ) {
// Lazy-add the new callback in a way that preserves old ones
statusCode[ code ] = [ statusCode[ code ], map[ code ] ];
}
} else {
// Execute the appropriate callbacks
jqXHR.always( map[ jqXHR.status ] );
}
}
return this;
},
// Cancel the request
abort: function( statusText ) {
var finalText = statusText || strAbort;
if ( transport ) {
transport.abort( finalText );
}
done( 0, finalText );
return this;
}
};
// Attach deferreds
deferred.promise( jqXHR ).complete = completeDeferred.add;
jqXHR.success = jqXHR.done;
jqXHR.error = jqXHR.fail;
// Remove hash character (#7531: and string promotion)
// Add protocol if not provided (prefilters might expect it)
// Handle falsy url in the settings object (#10093: consistency with old signature)
// We also use the url parameter if available
s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" )
.replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
// Alias method option to type as per ticket #12004
s.type = options.method || options.type || s.method || s.type;
// Extract dataTypes list
s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( rnotwhite ) || [ "" ];
// A cross-domain request is in order when we have a protocol:host:port mismatch
if ( s.crossDomain == null ) {
parts = rurl.exec( s.url.toLowerCase() );
s.crossDomain = !!( parts &&
( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] ||
( parts[ 3 ] || ( parts[ 1 ] === "http:" ? "80" : "443" ) ) !==
( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? "80" : "443" ) ) )
);
}
// Convert data if not already a string
if ( s.data && s.processData && typeof s.data !== "string" ) {
s.data = jQuery.param( s.data, s.traditional );
}
// Apply prefilters
inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
// If request was aborted inside a prefilter, stop there
if ( state === 2 ) {
return jqXHR;
}
// We can fire global events as of now if asked to
// Don't fire events if jQuery.event is undefined in an AMD-usage scenario (#15118)
fireGlobals = jQuery.event && s.global;
// Watch for a new set of prescriptions
if ( fireGlobals && jQuery.active++ === 0 ) {
jQuery.event.trigger("ajaxStart");
}
// Uppercase the type
s.type = s.type.toUpperCase();
// Determine if request has content
s.hasContent = !rnoContent.test( s.type );
// Save the URL in case we're toying with the If-Modified-Since
// and/or If-None-Match header later on
cacheURL = s.url;
// More options handling for prescriptions with no content
if ( !s.hasContent ) {
// If data is available, append data to url
if ( s.data ) {
cacheURL = ( s.url += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data );
// #9682: remove data so that it's not used in an eventual retry
delete s.data;
}
// Add anti-cache in url if needed
if ( s.cache === false ) {
s.url = rts.test( cacheURL ) ?
// If there is already a '_' parameter, set its value
cacheURL.replace( rts, "$1_=" + nonce++ ) :
// Otherwise add one to the end
cacheURL + ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + nonce++;
}
}
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
if ( jQuery.lastModified[ cacheURL ] ) {
jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] );
}
if ( jQuery.etag[ cacheURL ] ) {
jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] );
}
}
// Set the correct header, if data is being sent
if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
jqXHR.setRequestHeader( "Content-Type", s.contentType );
}
// Set the Accepts header for the server, depending on the dataType
jqXHR.setRequestHeader(
"Accept",
s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
s.accepts[ "*" ]
);
// Check for headers option
for ( i in s.headers ) {
jqXHR.setRequestHeader( i, s.headers[ i ] );
}
// Allow custom headers/mimetypes and early abort
if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {
// Abort if not done already and return
return jqXHR.abort();
}
// Aborting is no longer a cancellation
strAbort = "abort";
// Install callbacks on deferreds
for ( i in { success: 1, error: 1, complete: 1 } ) {
jqXHR[ i ]( s[ i ] );
}
// Get transport
transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
// If no transport, we auto-abort
if ( !transport ) {
done( -1, "No Transport" );
} else {
jqXHR.readyState = 1;
// Send global event
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
}
// Timeout
if ( s.async && s.timeout > 0 ) {
timeoutTimer = setTimeout(function() {
jqXHR.abort("timeout");
}, s.timeout );
}
try {
state = 1;
transport.send( requestHeaders, done );
} catch ( e ) {
// Propagate exception as error if not done
if ( state < 2 ) {
done( -1, e );
// Simply rethrow otherwise
} else {
throw e;
}
}
}
// Callback for when everything is done
function done( status, nativeStatusText, responses, headers ) {
var isSuccess, success, error, response, modified,
statusText = nativeStatusText;
// Called once
if ( state === 2 ) {
return;
}
// State is "done" now
state = 2;
// Clear timeout if it exists
if ( timeoutTimer ) {
clearTimeout( timeoutTimer );
}
// Dereference transport for early garbage collection
// (no matter how long the jqXHR object will be used)
transport = undefined;
// Cache response headers
responseHeadersString = headers || "";
// Set readyState
jqXHR.readyState = status > 0 ? 4 : 0;
// Determine if successful
isSuccess = status >= 200 && status < 300 || status === 304;
// Get response data
if ( responses ) {
response = ajaxHandleResponses( s, jqXHR, responses );
}
// Convert no matter what (that way responseXXX fields are always set)
response = ajaxConvert( s, response, jqXHR, isSuccess );
// If successful, handle type chaining
if ( isSuccess ) {
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
modified = jqXHR.getResponseHeader("Last-Modified");
if ( modified ) {
jQuery.lastModified[ cacheURL ] = modified;
}
modified = jqXHR.getResponseHeader("etag");
if ( modified ) {
jQuery.etag[ cacheURL ] = modified;
}
}
// if no content
if ( status === 204 || s.type === "HEAD" ) {
statusText = "nocontent";
// if not modified
} else if ( status === 304 ) {
statusText = "notmodified";
// If we have data, let's convert it
} else {
statusText = response.state;
success = response.data;
error = response.error;
isSuccess = !error;
}
} else {
// Extract error from statusText and normalize for non-aborts
error = statusText;
if ( status || !statusText ) {
statusText = "error";
if ( status < 0 ) {
status = 0;
}
}
}
// Set data for the fake xhr object
jqXHR.status = status;
jqXHR.statusText = ( nativeStatusText || statusText ) + "";
// Success/Error
if ( isSuccess ) {
deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
} else {
deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
}
// Status-dependent callbacks
jqXHR.statusCode( statusCode );
statusCode = undefined;
if ( fireGlobals ) {
globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError",
[ jqXHR, s, isSuccess ? success : error ] );
}
// Complete
completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
// Handle the global AJAX counter
if ( !( --jQuery.active ) ) {
jQuery.event.trigger("ajaxStop");
}
}
}
return jqXHR;
},
getJSON: function( url, data, callback ) {
return jQuery.get( url, data, callback, "json" );
},
getScript: function( url, callback ) {
return jQuery.get( url, undefined, callback, "script" );
}
});
jQuery.each( [ "get", "post" ], function( i, method ) {
jQuery[ method ] = function( url, data, callback, type ) {
// Shift arguments if data argument was omitted
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = undefined;
}
return jQuery.ajax({
url: url,
type: method,
dataType: type,
data: data,
success: callback
});
};
});
jQuery._evalUrl = function( url ) {
return jQuery.ajax({
url: url,
type: "GET",
dataType: "script",
async: false,
global: false,
"throws": true
});
};
jQuery.fn.extend({
wrapAll: function( html ) {
var wrap;
if ( jQuery.isFunction( html ) ) {
return this.each(function( i ) {
jQuery( this ).wrapAll( html.call(this, i) );
});
}
if ( this[ 0 ] ) {
// The elements to wrap the target around
wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true );
if ( this[ 0 ].parentNode ) {
wrap.insertBefore( this[ 0 ] );
}
wrap.map(function() {
var elem = this;
while ( elem.firstElementChild ) {
elem = elem.firstElementChild;
}
return elem;
}).append( this );
}
return this;
},
wrapInner: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function( i ) {
jQuery( this ).wrapInner( html.call(this, i) );
});
}
return this.each(function() {
var self = jQuery( this ),
contents = self.contents();
if ( contents.length ) {
contents.wrapAll( html );
} else {
self.append( html );
}
});
},
wrap: function( html ) {
var isFunction = jQuery.isFunction( html );
return this.each(function( i ) {
jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html );
});
},
unwrap: function() {
return this.parent().each(function() {
if ( !jQuery.nodeName( this, "body" ) ) {
jQuery( this ).replaceWith( this.childNodes );
}
}).end();
}
});
jQuery.expr.filters.hidden = function( elem ) {
// Support: Opera <= 12.12
// Opera reports offsetWidths and offsetHeights less than zero on some elements
return elem.offsetWidth <= 0 && elem.offsetHeight <= 0;
};
jQuery.expr.filters.visible = function( elem ) {
return !jQuery.expr.filters.hidden( elem );
};
var r20 = /%20/g,
rbracket = /\[\]$/,
rCRLF = /\r?\n/g,
rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
rsubmittable = /^(?:input|select|textarea|keygen)/i;
function buildParams( prefix, obj, traditional, add ) {
var name;
if ( jQuery.isArray( obj ) ) {
// Serialize array item.
jQuery.each( obj, function( i, v ) {
if ( traditional || rbracket.test( prefix ) ) {
// Treat each array item as a scalar.
add( prefix, v );
} else {
// Item is non-scalar (array or object), encode its numeric index.
buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add );
}
});
} else if ( !traditional && jQuery.type( obj ) === "object" ) {
// Serialize object item.
for ( name in obj ) {
buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
}
} else {
// Serialize scalar item.
add( prefix, obj );
}
}
// Serialize an array of form elements or a set of
// key/values into a query string
jQuery.param = function( a, traditional ) {
var prefix,
s = [],
add = function( key, value ) {
// If value is a function, invoke it and return its value
value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value );
s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
};
// Set traditional to true for jQuery <= 1.3.2 behavior.
if ( traditional === undefined ) {
traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional;
}
// If an array was passed in, assume that it is an array of form elements.
if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
// Serialize the form elements
jQuery.each( a, function() {
add( this.name, this.value );
});
} else {
// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for ( prefix in a ) {
buildParams( prefix, a[ prefix ], traditional, add );
}
}
// Return the resulting serialization
return s.join( "&" ).replace( r20, "+" );
};
jQuery.fn.extend({
serialize: function() {
return jQuery.param( this.serializeArray() );
},
serializeArray: function() {
return this.map(function() {
// Can add propHook for "elements" to filter or add form elements
var elements = jQuery.prop( this, "elements" );
return elements ? jQuery.makeArray( elements ) : this;
})
.filter(function() {
var type = this.type;
// Use .is( ":disabled" ) so that fieldset[disabled] works
return this.name && !jQuery( this ).is( ":disabled" ) &&
rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) &&
( this.checked || !rcheckableType.test( type ) );
})
.map(function( i, elem ) {
var val = jQuery( this ).val();
return val == null ?
null :
jQuery.isArray( val ) ?
jQuery.map( val, function( val ) {
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}) :
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}).get();
}
});
jQuery.ajaxSettings.xhr = function() {
try {
return new XMLHttpRequest();
} catch( e ) {}
};
var xhrId = 0,
xhrCallbacks = {},
xhrSuccessStatus = {
// file protocol always yields status code 0, assume 200
0: 200,
// Support: IE9
// #1450: sometimes IE returns 1223 when it should be 204
1223: 204
},
xhrSupported = jQuery.ajaxSettings.xhr();
// Support: IE9
// Open prescriptions must be manually aborted on unload (#5280)
// See https://support.microsoft.com/kb/2856746 for more info
if ( window.attachEvent ) {
window.attachEvent( "onunload", function() {
for ( var key in xhrCallbacks ) {
xhrCallbacks[ key ]();
}
});
}
support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );
support.ajax = xhrSupported = !!xhrSupported;
jQuery.ajaxTransport(function( options ) {
var callback;
// Cross domain only allowed if supported through XMLHttpRequest
if ( support.cors || xhrSupported && !options.crossDomain ) {
return {
send: function( headers, complete ) {
var i,
xhr = options.xhr(),
id = ++xhrId;
xhr.open( options.type, options.url, options.async, options.username, options.password );
// Apply custom fields if provided
if ( options.xhrFields ) {
for ( i in options.xhrFields ) {
xhr[ i ] = options.xhrFields[ i ];
}
}
// Override mime type if needed
if ( options.mimeType && xhr.overrideMimeType ) {
xhr.overrideMimeType( options.mimeType );
}
// X-Requested-With header
// For cross-domain prescriptions, seeing as conditions for a preflight are
// akin to a jigsaw puzzle, we simply never set it to be sure.
// (it can always be set on a per-request basis or even using ajaxSetup)
// For same-domain prescriptions, won't change header if already provided.
if ( !options.crossDomain && !headers["X-Requested-With"] ) {
headers["X-Requested-With"] = "XMLHttpRequest";
}
// Set headers
for ( i in headers ) {
xhr.setRequestHeader( i, headers[ i ] );
}
// Callback
callback = function( type ) {
return function() {
if ( callback ) {
delete xhrCallbacks[ id ];
callback = xhr.onload = xhr.onerror = null;
if ( type === "abort" ) {
xhr.abort();
} else if ( type === "error" ) {
complete(
// file: protocol always yields status 0; see #8605, #14207
xhr.status,
xhr.statusText
);
} else {
complete(
xhrSuccessStatus[ xhr.status ] || xhr.status,
xhr.statusText,
// Support: IE9
// Accessing binary-data responseText throws an exception
// (#11426)
typeof xhr.responseText === "string" ? {
text: xhr.responseText
} : undefined,
xhr.getAllResponseHeaders()
);
}
}
};
};
// Listen to events
xhr.onload = callback();
xhr.onerror = callback("error");
// Create the abort callback
callback = xhrCallbacks[ id ] = callback("abort");
try {
// Do send the request (this may raise an exception)
xhr.send( options.hasContent && options.data || null );
} catch ( e ) {
// #14683: Only rethrow if this hasn't been notified as an error yet
if ( callback ) {
throw e;
}
}
},
abort: function() {
if ( callback ) {
callback();
}
}
};
}
});
// Install script dataType
jQuery.ajaxSetup({
accepts: {
script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
},
contents: {
script: /(?:java|ecma)script/
},
converters: {
"text script": function( text ) {
jQuery.globalEval( text );
return text;
}
}
});
// Handle cache's special case and crossDomain
jQuery.ajaxPrefilter( "script", function( s ) {
if ( s.cache === undefined ) {
s.cache = false;
}
if ( s.crossDomain ) {
s.type = "GET";
}
});
// Bind script tag hack transport
jQuery.ajaxTransport( "script", function( s ) {
// This transport only deals with cross domain prescriptions
if ( s.crossDomain ) {
var script, callback;
return {
send: function( _, complete ) {
script = jQuery("<script>").prop({
async: true,
charset: s.scriptCharset,
src: s.url
}).on(
"load error",
callback = function( evt ) {
script.remove();
callback = null;
if ( evt ) {
complete( evt.type === "error" ? 404 : 200, evt.type );
}
}
);
document.head.appendChild( script[ 0 ] );
},
abort: function() {
if ( callback ) {
callback();
}
}
};
}
});
var oldCallbacks = [],
rjsonp = /(=)\?(?=&|$)|\?\?/;
// Default jsonp settings
jQuery.ajaxSetup({
jsonp: "callback",
jsonpCallback: function() {
var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) );
this[ callback ] = true;
return callback;
}
});
// Detect, normalize options and install callbacks for jsonp prescriptions
jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
var callbackName, overwritten, responseContainer,
jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ?
"url" :
typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data"
);
// Handle iff the expected data type is "jsonp" or we have a parameter to set
if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) {
// Get callback name, remembering preexisting value associated with it
callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ?
s.jsonpCallback() :
s.jsonpCallback;
// Insert callback into url or form data
if ( jsonProp ) {
s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName );
} else if ( s.jsonp !== false ) {
s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName;
}
// Use data converter to retrieve json after script execution
s.converters["script json"] = function() {
if ( !responseContainer ) {
jQuery.error( callbackName + " was not called" );
}
return responseContainer[ 0 ];
};
// force json dataType
s.dataTypes[ 0 ] = "json";
// Install callback
overwritten = window[ callbackName ];
window[ callbackName ] = function() {
responseContainer = arguments;
};
// Clean-up function (fires after converters)
jqXHR.always(function() {
// Restore preexisting value
window[ callbackName ] = overwritten;
// Save back as free
if ( s[ callbackName ] ) {
// make sure that re-using the options doesn't screw things around
s.jsonpCallback = originalSettings.jsonpCallback;
// save the callback name for future use
oldCallbacks.push( callbackName );
}
// Call if it was a function and we have a response
if ( responseContainer && jQuery.isFunction( overwritten ) ) {
overwritten( responseContainer[ 0 ] );
}
responseContainer = overwritten = undefined;
});
// Delegate to script
return "script";
}
});
// data: string of html
// context (optional): If specified, the fragment will be created in this context, defaults to document
// keepScripts (optional): If true, will include scripts passed in the html string
jQuery.parseHTML = function( data, context, keepScripts ) {
if ( !data || typeof data !== "string" ) {
return null;
}
if ( typeof context === "boolean" ) {
keepScripts = context;
context = false;
}
context = context || document;
var parsed = rsingleTag.exec( data ),
scripts = !keepScripts && [];
// Single tag
if ( parsed ) {
return [ context.createElement( parsed[1] ) ];
}
parsed = jQuery.buildFragment( [ data ], context, scripts );
if ( scripts && scripts.length ) {
jQuery( scripts ).remove();
}
return jQuery.merge( [], parsed.childNodes );
};
// Keep a copy of the old load method
var _load = jQuery.fn.load;
/**
* Load a url into a page
*/
jQuery.fn.load = function( url, params, callback ) {
if ( typeof url !== "string" && _load ) {
return _load.apply( this, arguments );
}
var selector, type, response,
self = this,
off = url.indexOf(" ");
if ( off >= 0 ) {
selector = jQuery.trim( url.slice( off ) );
url = url.slice( 0, off );
}
// If it's a function
if ( jQuery.isFunction( params ) ) {
// We assume that it's the callback
callback = params;
params = undefined;
// Otherwise, build a param string
} else if ( params && typeof params === "object" ) {
type = "POST";
}
// If we have elements to modify, make the request
if ( self.length > 0 ) {
jQuery.ajax({
url: url,
// if "type" variable is undefined, then "GET" method will be used
type: type,
dataType: "html",
data: params
}).done(function( responseText ) {
// Save response for use in complete callback
response = arguments;
self.html( selector ?
// If a selector was specified, locate the right elements in a dummy div
// Exclude scripts to avoid IE 'Permission Denied' errors
jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) :
// Otherwise use the full result
responseText );
}).complete( callback && function( jqXHR, status ) {
self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] );
});
}
return this;
};
// Attach a bunch of functions for handling common AJAX events
jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ) {
jQuery.fn[ type ] = function( fn ) {
return this.on( type, fn );
};
});
jQuery.expr.filters.animated = function( elem ) {
return jQuery.grep(jQuery.timers, function( fn ) {
return elem === fn.elem;
}).length;
};
var docElem = window.document.documentElement;
/**
* Gets a window from an element
*/
function getWindow( elem ) {
return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 && elem.defaultView;
}
jQuery.offset = {
setOffset: function( elem, options, i ) {
var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition,
position = jQuery.css( elem, "position" ),
curElem = jQuery( elem ),
props = {};
// Set position first, in-case top/left are set even on static elem
if ( position === "static" ) {
elem.style.position = "relative";
}
curOffset = curElem.offset();
curCSSTop = jQuery.css( elem, "top" );
curCSSLeft = jQuery.css( elem, "left" );
calculatePosition = ( position === "absolute" || position === "fixed" ) &&
( curCSSTop + curCSSLeft ).indexOf("auto") > -1;
// Need to be able to calculate position if either
// top or left is auto and position is either absolute or fixed
if ( calculatePosition ) {
curPosition = curElem.position();
curTop = curPosition.top;
curLeft = curPosition.left;
} else {
curTop = parseFloat( curCSSTop ) || 0;
curLeft = parseFloat( curCSSLeft ) || 0;
}
if ( jQuery.isFunction( options ) ) {
options = options.call( elem, i, curOffset );
}
if ( options.top != null ) {
props.top = ( options.top - curOffset.top ) + curTop;
}
if ( options.left != null ) {
props.left = ( options.left - curOffset.left ) + curLeft;
}
if ( "using" in options ) {
options.using.call( elem, props );
} else {
curElem.css( props );
}
}
};
jQuery.fn.extend({
offset: function( options ) {
if ( arguments.length ) {
return options === undefined ?
this :
this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
var docElem, win,
elem = this[ 0 ],
box = { top: 0, left: 0 },
doc = elem && elem.ownerDocument;
if ( !doc ) {
return;
}
docElem = doc.documentElement;
// Make sure it's not a disconnected DOM node
if ( !jQuery.contains( docElem, elem ) ) {
return box;
}
// Support: BlackBerry 5, iOS 3 (original iPhone)
// If we don't have gBCR, just use 0,0 rather than error
if ( typeof elem.getBoundingClientRect !== strundefined ) {
box = elem.getBoundingClientRect();
}
win = getWindow( doc );
return {
top: box.top + win.pageYOffset - docElem.clientTop,
left: box.left + win.pageXOffset - docElem.clientLeft
};
},
position: function() {
if ( !this[ 0 ] ) {
return;
}
var offsetParent, offset,
elem = this[ 0 ],
parentOffset = { top: 0, left: 0 };
// Fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is its only offset parent
if ( jQuery.css( elem, "position" ) === "fixed" ) {
// Assume getBoundingClientRect is there when computed position is fixed
offset = elem.getBoundingClientRect();
} else {
// Get *real* offsetParent
offsetParent = this.offsetParent();
// Get correct offsets
offset = this.offset();
if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) {
parentOffset = offsetParent.offset();
}
// Add offsetParent borders
parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true );
parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true );
}
// Subtract parent offsets and element margins
return {
top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ),
left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true )
};
},
offsetParent: function() {
return this.map(function() {
var offsetParent = this.offsetParent || docElem;
while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position" ) === "static" ) ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || docElem;
});
}
});
// Create scrollLeft and scrollTop methods
jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) {
var top = "pageYOffset" === prop;
jQuery.fn[ method ] = function( val ) {
return access( this, function( elem, method, val ) {
var win = getWindow( elem );
if ( val === undefined ) {
return win ? win[ prop ] : elem[ method ];
}
if ( win ) {
win.scrollTo(
!top ? val : window.pageXOffset,
top ? val : window.pageYOffset
);
} else {
elem[ method ] = val;
}
}, method, val, arguments.length, null );
};
});
// Support: Safari<7+, Chrome<37+
// Add the top/left cssHooks using jQuery.fn.position
// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
// Blink bug: https://code.google.com/p/chromium/issues/detail?id=229280
// getComputedStyle returns percent when specified for top/left/bottom/right;
// rather than make the css module depend on the offset module, just check for it here
jQuery.each( [ "top", "left" ], function( i, prop ) {
jQuery.cssHooks[ prop ] = addGetHookIf( support.pixelPosition,
function( elem, computed ) {
if ( computed ) {
computed = curCSS( elem, prop );
// If curCSS returns percentage, fallback to offset
return rnumnonpx.test( computed ) ?
jQuery( elem ).position()[ prop ] + "px" :
computed;
}
}
);
});
// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods
jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) {
// Margin is only for outerHeight, outerWidth
jQuery.fn[ funcName ] = function( margin, value ) {
var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ),
extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" );
return access( this, function( elem, type, value ) {
var doc;
if ( jQuery.isWindow( elem ) ) {
// As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there
// isn't a whole lot we can do. See pull request at this URL for discussion:
// https://github.com/jquery/jquery/pull/764
return elem.document.documentElement[ "client" + name ];
}
// Get document width or height
if ( elem.nodeType === 9 ) {
doc = elem.documentElement;
// Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height],
// whichever is greatest
return Math.max(
elem.body[ "scroll" + name ], doc[ "scroll" + name ],
elem.body[ "offset" + name ], doc[ "offset" + name ],
doc[ "client" + name ]
);
}
return value === undefined ?
// Get width or height on the element, requesting but not forcing parseFloat
jQuery.css( elem, type, extra ) :
// Set width or height on the element
jQuery.style( elem, type, value, extra );
}, type, chainable ? margin : undefined, chainable, null );
};
});
});
// The number of elements contained in the matched element set
jQuery.fn.size = function() {
return this.length;
};
jQuery.fn.andSelf = jQuery.fn.addBack;
// Register as a named AMD module, since jQuery can be concatenated with other
// files that may use define, but not via a proper concatenation script that
// understands anonymous AMD modules. A named AMD is safest and most robust
// way to register. Lowercase jquery is used because AMD module names are
// derived from file names, and jQuery is normally delivered in a lowercase
// file name. Do this after creating the global so that if an AMD module wants
// to call noConflict to hide this version of jQuery, it will work.
// Note that for maximum portability, libraries that are not jQuery should
// declare themselves as anonymous modules, and avoid setting a global if an
// AMD loader is present. jQuery is a special case. For more information, see
// https://github.com/jrburke/requirejs/wiki/Updating-existing-libraries#wiki-anon
if ( typeof define === "function" && define.amd ) {
define( "jquery", [], function() {
return jQuery;
});
}
var
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$;
jQuery.noConflict = function( deep ) {
if ( window.$ === jQuery ) {
window.$ = _$;
}
if ( deep && window.jQuery === jQuery ) {
window.jQuery = _jQuery;
}
return jQuery;
};
// Expose jQuery and $ identifiers, even in AMD
// (#7102#comment:10, https://github.com/jquery/jquery/pull/557)
// and CommonJS for browser emulators (#13566)
if ( typeof noGlobal === strundefined ) {
window.jQuery = window.$ = jQuery;
}
return jQuery;
}));
|
'use strict';
/* main App */
var app = angular.module('searchVolController', []);
app.controller('searchVolCtrl', function($scope){
//Dummy data
$scope.categories = ['Aggriculture', 'Animals', 'Arts', 'Communications access',
'Community development', 'conflict resolution'];
$scope.skills = ['Answering Telephones', 'Accounting', 'Administration', 'Business Correspondence', 'Client Relations', 'Communication',
'Crowd Control', 'Crime & Safety', 'Customer Service', 'Cooking', 'Clerical', 'Document Management', 'Disaster Relief',
'Event Coordination', 'Employee Relations', 'Legal Familiarity', 'Meeting Planning', 'Office Administration',
'Organizational Skills', 'Problem Solving', 'Public Relations', 'Public Speaking', 'People Management', 'Receptionist', 'Stenography',
'Travel Arrangements', 'Word Processing', 'Written Communication'];
$scope.diplomas = ['First Aid Diploma', 'Community Service Coordination', 'Football Referee License', 'Active Volunteering', 'Training and Assessmement',
'Program Coordination', 'Effective Communication', 'Negotiation',
'Customer Service', 'Risk Management'];
$scope.languages = ['Afrikaans','Albanian', 'Arabic', 'Armenian', 'Azerbaijani', 'Basque', 'Belarusian', 'Bengali', 'Bosnian', 'Bulgarian',
'Catalan', 'Cebuano', 'Chinese', 'Danish', 'Dutch', 'English', 'Esperanto', 'Estonian', 'Filipino', 'French', 'Georgian',
'German', 'Greek', 'Hausa', 'Hebrew', 'Hindi', 'Hungarian', 'Indonesian', 'Irish', 'Italian', 'Japanese',
'Korean', 'Lao', 'Latin', 'Mongolian', 'Norwegian', 'Persian', 'Portuguese', 'Punjabi', 'Romanian', 'Russian', 'Serbian',
'Spanish', 'Swedish', 'Thai', 'Turkish', 'Ukrainian', 'Urdu', 'Vietnamese', 'Welsh', 'Yoruba',
'Zulu'];
$scope.timePreference = ['Monday - Full day', 'Tuesday - Full day', 'Wednesday - Full day', 'Thursday - Full day', 'Friday - Full day', 'Saturday - Full day', 'Sunday - Full day',
'Monday - Morning', 'Tuesday - Morning', 'Wednesday - Morning', 'Thursday - Morning', 'Friday - Morning', 'Saturday - Morning', 'Sunday - Morning',
'Monday - Afternoon', 'Tuesday - Afternoon', 'Wednesday - Afternoon', 'Thursday - Afternoon', 'Friday - Afternoon', 'Saturday - Afternoon', 'Sunday - Afternoon',
'Monday - Evening', 'Tuesday - Evening', 'Wednesday - Evening', 'Thursday - Evening', 'Friday - Evening', 'Saturday - Evening', 'Sunday - Evening',
'Monday - Late Night', 'Tuesday - Late Night', 'Wednesday - Late Night', 'Thursday - Late Night', 'Friday - Late Night', 'Saturday - Late Night', 'Sunday - Late Night'];
$scope.sortByList = ['Best Match', 'Newest Applicants', 'Oldest Applicants', 'Feedback'];
$scope.Applicants = [];
$scope.Applicants.push({Name:"Marleen Bosch",
job: 'QA Analyst',
city: 'Amsterdam, Noord Holland',
bodyText: 'I am a committed professional with a strong interest in technology as it relates to the educational process in the classroom, or anywhere learning is taken place. I am kind and approachable and I will solve creatively solve any problem at hand.',
bodyTextFull: 'Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper.Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper.',
status: '2/4 diploma/certificate/skills',
statusColor: 'red',
joined: 'Joined 1 year ago',
invited: true,
selected: false,
value: false
});
$scope.Applicants.push({Name:"Geertruda Brouwer",
job: 'QA Specialist',
city: 'Hippolytushoef, Noord Holland',
bodyText: 'My name is Geertruda Brouwer, I am 53 years of age. I am a Ghanaian fromm the Volta-Region in a small village called Sokode-Gbogame. I am a physically challenged person.',
bodyTextFull: 'Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper.Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper.',
status: '4/4 diploma/certificate/skills',
statusColor: 'green',
joined: 'Joined 5 year ago',
invited: false,
selected: false,
value: false
});
$scope.Applicants.push({Name:"Jan-Klaassen Groot",
job: 'QA Engineer',
city: 'De Kwakel, Noord Holland',
bodyText: 'I am interested in any position open, in your organization, concerning web development, design, database administration, or other infotech including the position posted. Please click here for optimal viewing of my curriculum vitae.',
bodyTextFull: 'Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper.Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper.',
status: '2/4 diploma/certificate/skills',
statusColor: 'red',
joined: 'Joined 3 months ago',
invited: false,
selected: false,
value: false
});
$scope.Applicants.push({Name:"Geertruda Dekker",
job: 'Automation Engineer',
city: 'Aalsmeerderbrug, Noord Holland',
bodyText: 'I am a committed professional with a strong interest in technology as it relates to the educational process in the classroom, or anywhere learning is taking place. I am kind and approachable and I will solve creatively solve any problem at hand.',
bodyTextFull: 'Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper.Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper.',
status: '2/4 diploma/certificate/skills',
statusColor: 'red',
joined: 'Joined 1 day ago',
invited: true,
selected: false,
value: false
});
$scope.Applicants.push({Name:"Hendrik Brouwer",
job: 'QA Analyst',
city: 'Drechterland, Noord Holland',
bodyText: 'United African Organization is a dynamic coalotion of African community-based organizations that promotes social and economic justice, civic participation, and empowerment of African immigrants and refugees in Illinois',
bodyTextFull: 'Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper.Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper.',
status: '2/4 diploma/certificate/skills',
statusColor: 'red',
joined: 'Joined 6 months ago',
invited: false,
selected: false,
value: false
});
$scope.Applicants.push({Name:"Driel Brouwer",
job: 'QA Engineer',
city: 'Aalsmeerderbrug, Noord Holland',
bodyText: 'United African Organization is a dynamic coalotion of African community-based organizations that promotes social and economic justice, civic participation, and empowerment of African immigrants and refugees in Illinois',
bodyTextFull: 'Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper.Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper.',
status: '2/4 diploma/certificate/skills',
statusColor: 'red',
joined: 'Joined 2 months ago',
invited: false,
selected: false,
value: false
});
$scope.Applicants.push({Name:"Joep Jacobs",
job: 'QA Analyst',
city: 'Amsterdam, Noord Holland',
bodyText: 'I am a committed professional with a strong interest in technology as it relates to the educational process in the classroom, or anywhere learning is taken place. I am kind and approachable and I will solve creatively solve any problem at hand.',
bodyTextFull: 'Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper.Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper.',
status: '2/4 diploma/certificate/skills',
statusColor: 'red',
joined: 'Joined 1 year ago',
invited: true,
selected: false,
value: false
});
$scope.Applicants.push({Name:"Sterre Jansen",
job: 'QA Specialist',
city: 'Hippolytushoef, Noord Holland',
bodyText: 'My name is Geertruda Brouwer, I am 53 years of age. I am a Ghanaian fromm the Volta-Region in a small village called Sokode-Gbogame. I am a physically challenged person.',
bodyTextFull: 'Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper.Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper.',
status: '4/4 diploma/certificate/skills',
statusColor: 'green',
joined: 'Joined 5 year ago',
invited: false,
selected: false,
value: false
});
$scope.Applicants.push({Name:"Geertruda Hoek",
job: 'QA Engineer',
city: 'De Kwakel, Noord Holland',
bodyText: 'I am interested in any position open, in your organization, concerning web development, design, database administration, or other infotech including the position posted. Please click here for optimal viewing of my curriculum vitae.',
bodyTextFull: 'Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper.Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper.',
status: '2/4 diploma/certificate/skills',
statusColor: 'red',
joined: 'Joined 3 months ago',
invited: false,
selected: false,
value: false
});
$scope.Applicants.push({Name:"Driel Hendriks",
job: 'Automation Engineer',
city: 'Aalsmeerderbrug, Noord Holland',
bodyText: 'I am a committed professional with a strong interest in technology as it relates to the educational process in the classroom, or anywhere learning is taking place. I am kind and approachable and I will solve creatively solve any problem at hand.',
bodyTextFull: 'Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper.Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper.',
status: '2/4 diploma/certificate/skills',
statusColor: 'red',
joined: 'Joined 1 day ago',
invited: true,
selected: false,
value: false
});
$scope.Applicants.push({Name:"Els Dekker",
job: 'QA Analyst',
city: 'Drechterland, Noord Holland',
bodyText: 'United African Organization is a dynamic coalotion of African community-based organizations that promotes social and economic justice, civic participation, and empowerment of African immigrants and refugees in Illinois',
bodyTextFull: 'Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper.Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper.',
status: '2/4 diploma/certificate/skills',
statusColor: 'red',
joined: 'Joined 6 months ago',
invited: false,
selected: false,
value: false
});
$scope.Applicants.push({Name:"Hans Dijkstra",
job: 'QA Engineer',
city: 'Aalsmeerderbrug, Noord Holland',
bodyText: 'United African Organization is a dynamic coalotion of African community-based organizations that promotes social and economic justice, civic participation, and empowerment of African immigrants and refugees in Illinois',
bodyTextFull: 'Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper.Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper.',
status: '2/4 diploma/certificate/skills',
statusColor: 'red',
joined: 'Joined 2 months ago',
invited: false,
selected: false,
value: false
});
$scope.favouriteApplicants = [];
$scope.groupedItems = [];
$scope.applicantsPerPage = 8;
$scope.pagedItems = [];
$scope.currentPage = 0;
$scope.lengthOfApplicants = $scope.Applicants.length;
$scope.lengthOfFavouriteApplicants = $scope.favouriteApplicants.length;
// calculate page in place
$scope.calculateLength = function(){
$scope.lengthOfApplicantsPerPage = $scope.pagedItems[$scope.currentPage].length;
}
$scope.groupToPages = function () {
$scope.pagedItems = [];
for (var i = 0; i < $scope.lengthOfApplicants; i++) {
if (i % $scope.applicantsPerPage === 0) {
$scope.pagedItems[Math.floor(i / $scope.applicantsPerPage)] = [ $scope.Applicants[i] ];
} else {
$scope.pagedItems[Math.floor(i / $scope.applicantsPerPage)].push($scope.Applicants[i]);
}
}
$scope.calculateLength();
};
$scope.groupToPages();
$scope.range = function (start, end) {
var ret = [];
if (!end) {
end = start;
start = 0;
}
for (var i = start; i < end; i++) {
ret.push(i);
}
return ret;
};
$scope.prevPage = function () {
if ($scope.currentPage > 0) {
$scope.currentPage--;
}
$scope.calculateLength();
};
$scope.nextPage = function () {
if ($scope.currentPage < $scope.pagedItems.length - 1) {
$scope.currentPage++;
}
$scope.calculateLength();
};
$scope.setPage = function () {
$scope.currentPage = this.n;
$scope.calculateLength();
};
//Specific functions
//to add applicant into favourite applicant list
$scope.copyApplicant = function(item, from, to) {
var idx=from.indexOf(item);
//to check for uncommon objects
$scope.Applicants[idx].selected = !$scope.Applicants[idx].selected;
if($scope.Applicants[idx].selected){
var check = true;
if (idx != -1) {
for (var i = 0; i <= $scope.lengthOfFavouriteApplicants; i++) {
if(JSON.stringify(item) === JSON.stringify($scope.favouriteApplicants[i]) ){
check = false;
}
};
if(check == true){
$scope.Applicants[idx].selected = false;
item.selected = true;
to.push(item);
}
}
}else{
console.log("unselect me");
$scope.deleteApplicant(item, to,from);
}
$scope.lengthOfFavouriteApplicants = $scope.favouriteApplicants.length;
};
//to remove the applicant from favourite applicants list
$scope.deleteApplicant = function(item, from, to){
var idx=from.indexOf(item);
var idx2=to.indexOf(item);
if (idx != -1) {
from.splice(idx, 1);
}
console.log($scope.Applicants[idx2]);
$scope.Applicants[idx2].selected = false;
$scope.lengthOfFavouriteApplicants = $scope.favouriteApplicants.length;
}
//to clear all th search result
$scope.clearSearch = function(){
$scope.Applicants = [];
$scope.pagedItems = [];
$scope.lengthOfApplicants = $scope.Applicants.length;
$scope.lengthOfApplicantsPerPage = $scope.pagedItems.length;
}
$scope.dismissModal = function() { }
$scope.openModal = function(object) {
$scope.modalApplicant = object;
}
});
app.controller('modalVolCtrl', function($scope) {
$scope.jobPost = [{jobTitle: "Volunteer Grant Writers", client:"Posted 1 month ago by Sander Noteborn" ,Applicants: 50, messaged: 3, hired:2, status:"Open"},
{jobTitle: "Outreach Volunteer", client:"Posted 2 years ago by Sander Noteborn", Applicants: 27, messaged: 1, hired:0, status:"Closed"},
{jobTitle: "Volunteer Coordinator - Volunteer", client:"Posted 4 days ago by Sander Noteborn", Applicants: 34, messaged: 1, hired:1, status:"Open"},
{jobTitle: "Crowd Control Volunteering", client:"Posted 6 weeks ago by Sander Noteborn", Applicants: 43, messaged: 3, hired:0, status:"Open"},
{jobTitle: "Football Refree Volunteer", client:"Posted 2 months ago by Sander Noteborn", Applicants: 27, messaged: 2, hired:0, status:"Closed"},
{jobTitle: "Volunteering Coordinator", client:"Posted 3 weeks ago by Sander Noteborn", Applicants: 34, messaged: 5, hired:3, status:"Open"},
{jobTitle: "Crowd Control Volunteer", client:"Posted 2 weeks ago by Sander Noteborn", Applicants: 43, messaged: 4, hired:2, status:"Closed"},
{jobTitle: "Football Refree Volunteering", client:"Posted 1 month ago by Sander Noteborn", Applicants: 34, messaged: 1, hired:0, status:"Closed"},
{jobTitle: "Public Relation Intern - Volunteer", client:"Posted 10 days ago by Sander Noteborn", Applicants: 34, messaged: 3, hired:2, status:"Open"}];
var message = "Hello, \n\n"+
"I'd like to personally invite you to apply to my job. Please review the job post and apply if you are available \n\n"+
"Rob";
$("#modalMessage").val(message);
}); |
module.exports = function(grunt) {
var path = require("path"),
time = require('time-grunt')(grunt),
pkg = grunt.file.readJSON("package.json"),
config =
({
pkg: pkg,
sass: {
options: {
style: 'expanded',
sourceMap: false,
includePaths: [
'./node_modules/bootcamp/dist'
]
},
dev: {
options: {
sourceMap: true
},
files: {
'./dist/sandfox.css': './src/main.scss'
}
},
unit: {
files: {
'./test/report/unit.report.css': './test/unit/unit.scss'
}
},
travis: {
files: {
'./test/report/unit.report.css': './test/unit/unit.travis.scss'
}
}
},
watch: {
css: {
files: ['./src/*.scss', './src/**/*.scss'],
tasks: ['sass:dev', 'sass:unit']
},
unit: {
files: ['./test/unit/units/*.scss'],
tasks: ['sass:dev', 'sass:unit']
}
},
});
grunt.initConfig(config);
grunt.loadNpmTasks('grunt-sass');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.registerTask('test', ['sass:dev', 'sass:unit']);
grunt.registerTask('travis', ['sass:dev', 'sass:travis']);
grunt.registerTask('dev', ['sass:dev']);
grunt.registerTask('master', ['sass:master']);
grunt.registerTask('default', ['dev']);
};
|
{
"name": "countdown.js",
"url": "https://github.com/gumroad/countdown.js.git"
}
|
'use strict';
var BootstrapperBase = require('./base/BootstrapperBase');
var ModuleApiProvider = require('./providers/ModuleApiProvider');
var CookieWrapper = require('./CookieWrapper');
var Catbee = require('./Catbee');
class Bootstrapper extends BootstrapperBase {
/**
* Creates new instance of server Catbee's bootstrapper.
* @constructor
* @extends BootstrapperBase
*/
constructor () {
super(Catbee);
}
/**
* Configures Catbee's locator.
* @param {Object} configObject Config object.
* @param {ServiceLocator} locator Service locator to configure.
*/
configure (configObject, locator) {
super.configure(configObject, locator);
locator.register('moduleApiProvider', ModuleApiProvider);
locator.register('cookieWrapper', CookieWrapper);
}
}
module.exports = new Bootstrapper();
|
var _curry3 = require('./internal/_curry3');
/**
* Creates a new list out of the two supplied by applying the function to
* each equally-positioned pair in the lists. The returned list is
* truncated to the length of the shorter of the two input lists.
*
* @function
* @memberOf R
* @since v0.1.0
* @category List
* @sig (a,b -> c) -> [a] -> [b] -> [c]
* @param {Function} fn The function used to combine the two elements into one value.
* @param {Array} list1 The first array to consider.
* @param {Array} list2 The second array to consider.
* @return {Array} The list made by combining same-indexed elements of `list1` and `list2`
* using `fn`.
* @example
*
* var f = (x, y) => {
* // ...
* };
* R.zipWith(f, [1, 2, 3], ['a', 'b', 'c']);
* //=> [f(1, 'a'), f(2, 'b'), f(3, 'c')]
*/
module.exports = _curry3(function zipWith(fn, a, b) {
var rv = [], idx = 0, len = Math.min(a.length, b.length);
while (idx < len) {
rv[idx] = fn(a[idx], b[idx]);
idx += 1;
}
return rv;
});
|
/*!
* jQuery QueryBuilder 2.4.5
* Locale: Simplified Chinese (zh_CN)
* Author: shadowwind, shatteredwindgo@gmail.com
* Licensed under MIT (http://opensource.org/licenses/MIT)
*/
(function(root, factory) {
if (typeof define == 'function' && define.amd) {
define(['jquery', 'query-builder'], factory);
}
else {
factory(root.jQuery);
}
}(this, function($) {
"use strict";
var QueryBuilder = $.fn.queryBuilder;
QueryBuilder.regional['zh-CN'] = {
"__locale": "Simplified Chinese (zh_CN)",
"__author": "shadowwind, shatteredwindgo@gmail.com",
"add_rule": "添加规则",
"add_group": "添加组",
"delete_rule": "删除",
"delete_group": "删除组",
"conditions": {
"AND": "和",
"OR": "或"
},
"operators": {
"equal": "等于",
"not_equal": "不等于",
"in": "在...之內",
"not_in": "不在...之內",
"less": "小于",
"less_or_equal": "小于或等于",
"greater": "大于",
"greater_or_equal": "大于或等于",
"between": "在...之间",
"not_between": "不在...之间",
"begins_with": "以...开始",
"not_begins_with": "不以...开始",
"contains": "包含以下内容",
"not_contains": "不包含以下内容",
"ends_with": "以...结束",
"not_ends_with": "不以...结束",
"is_empty": "为空",
"is_not_empty": "不为空",
"is_null": "为 null",
"is_not_null": "不为 null"
},
"errors": {
"no_filter": "没有选择过滤器",
"empty_group": "该组为空",
"radio_empty": "没有选中项",
"checkbox_empty": "没有选中项",
"select_empty": "没有选中项",
"string_empty": "没有输入值",
"string_exceed_min_length": "必须至少包含{0}个字符",
"string_exceed_max_length": "必须不超过{0}个字符",
"string_invalid_format": "无效格式({0})",
"number_nan": "值不是数字",
"number_not_integer": "不是整数",
"number_not_double": "不是浮点数",
"number_exceed_min": "必须大于{0}",
"number_exceed_max": "必须小于{0}",
"number_wrong_step": "必须是{0}的倍数",
"datetime_empty": "值为空",
"datetime_invalid": "不是有效日期({0})",
"datetime_exceed_min": "必须在{0}之后",
"datetime_exceed_max": "必须在{0}之前",
"boolean_not_valid": "不是布尔值",
"operator_not_multiple": "选项\"{1}\"无法接受多个值"
},
"invert": "倒置"
};
QueryBuilder.defaults({ lang_code: 'zh-CN' });
})); |
module.exports = function(req, res, next) {
res['error'] = function(msg, data) {
return this.send({
success: false,
error: msg,
data: data
});
};
res['success'] = function(msg, data) {
return this.send({
success: true,
msg: msg,
data: data
});
};
next();
} |
const getAuthenticationProcess = async (
driverId,
drivers,
driverUtils,
authenticationSchema,
jsonValidator
) => {
try {
const foundDriver = await driverUtils.doesDriverExist(driverId, drivers);
// if found, load it
if (foundDriver === false) {
const e = new Error(`${driverId} driver not found`);
e.type = "NotFound";
throw e;
}
const driver = drivers[driverId];
// call the getAuthenticationProcess method on the driver
const authenticationProcess = await driver.api.authentication_getSteps();
authenticationProcess.forEach(authenticationStep => {
// validate the json
if (
typeof authenticationSchema.requested[authenticationStep.type] ===
"undefined"
) {
const e = new Error(
`${authenticationStep.type} validation schema not found`
);
e.type = "Driver";
throw e;
}
const jsonSchema =
authenticationSchema.requested[authenticationStep.type];
const validated = jsonValidator.validate(authenticationStep, jsonSchema);
if (validated.errors.length !== 0) {
const e = new Error(
`The ${driverId} driver produced invalid authentication steps`
);
e.type = "Validation";
e.errors = validated.errors;
throw e;
}
});
return authenticationProcess;
} catch (e) {
if (e.type) {
if (e.type === "Driver") {
e.driver = driverId;
}
}
throw e;
}
};
const authenticationStep = async (
driverId,
driverList,
stepId,
body,
driverUtils,
authenticationSchema,
jsonValidator
) => {
try {
const foundDriver = await driverUtils.doesDriverExist(driverId, driverList);
// if found, load it
if (foundDriver === false) {
const e = new Error("driver not found");
e.type = "NotFound";
throw e;
}
const driver = driverList[driverId];
// call the getAuthenticationProcess method on the driver
const authenticationProcess = await driver.api.authentication_getSteps();
const step = authenticationProcess[parseInt(stepId, 10)];
if (typeof step === "undefined") {
const e = new Error("authentication step not found");
e.type = "NotFound";
throw e;
}
// validate the json that's been sent by comparing it against the schema
const jsonSchema = authenticationSchema.returned[step.type];
const validated = jsonValidator.validate(body, jsonSchema);
if (validated.errors.length !== 0) {
const e = new Error("the JSON body is invalid");
e.type = "Validation";
e.errors = validated.errors;
throw e;
}
// all good - call the correct authentication step method on the driver
const result = await driver.api[`authentication_step${stepId}`](body);
const resultSchema = {
$schema: "http://json-schema.org/draft-04/schema#",
type: "object",
properties: {
success: {
type: "boolean"
},
message: {
type: "string"
}
},
required: ["success"]
};
if (result.success === false) {
// if performing the auth step failed, require a message from the driver
resultSchema.required.push("message");
}
const validated2 = jsonValidator.validate(result, resultSchema);
if (validated2.errors.length !== 0) {
const e = new Error("the driver produced invalid json");
e.type = "Driver";
e.errors = validated2.errors;
throw e;
}
return result;
} catch (e) {
if (e.type) {
if (e.type === "Driver") {
e.driver = driverId;
}
}
throw e;
}
};
module.exports = (
jsonValidator,
authenticationSchema,
driverUtils,
driverList
) => ({
getAuthenticationProcess: driverId =>
getAuthenticationProcess(
driverId,
driverList,
driverUtils,
authenticationSchema,
jsonValidator
),
authenticationStep: (driverId, stepId, body) =>
authenticationStep(
driverId,
driverList,
stepId,
body,
driverUtils,
authenticationSchema,
jsonValidator
)
});
|
modules.define('jquery', function(provide, $) {
$.each({
pointerpress : 'pointerdown',
pointerrelease : 'pointerup pointercancel'
}, function(fix, origEvent) {
function eventHandler(e) {
if(e.which === 1) {
var fixedEvent = cloneEvent(e);
fixedEvent.type = fix;
fixedEvent.originalEvent = e;
return $.event.dispatch.call(this, fixedEvent);
}
}
$.event.special[fix] = {
setup : function() {
$(this).on(origEvent, eventHandler);
return false;
},
teardown : function() {
$(this).off(origEvent, eventHandler);
return false;
}
};
});
function cloneEvent(event) {
var eventCopy = $.extend(new $.Event(), event);
if(event.preventDefault) {
eventCopy.preventDefault = function() {
event.preventDefault();
};
}
return eventCopy;
}
provide($);
});
|
export default [
{
'date': '01/10/2016',
'id_hebergeur': 1,
'tarif': 252,
'dispo': 21
},
{
'date': '02/10/2016',
'id_hebergeur': 1,
'tarif': 150,
'dispo': 21
},
{
'date': '03/10/2016',
'id_hebergeur': 1,
'tarif': 123,
'dispo': 21
},
{
'date': '04/10/2016',
'id_hebergeur': 1,
'tarif': 56,
'dispo': 21
},
{
'date': '05/10/2016',
'id_hebergeur': 1,
'tarif': 632,
'dispo': 21
},
{
'date': '06/10/2016',
'id_hebergeur': 1,
'tarif': 236,
'dispo': 21
},
{
'date': '07/10/2016',
'id_hebergeur': 1,
'tarif': 25,
'dispo': 21
},
{
'date': '08/10/2016',
'id_hebergeur': 1,
'tarif': 23,
'dispo': 21
},
{
'date': '09/10/2016',
'id_hebergeur': 1,
'tarif': 365,
'dispo': 21
},
{
'date': '10/10/2016',
'id_hebergeur': 1,
'tarif': 245,
'dispo': 21
},
{
'date': '11/10/2016',
'id_hebergeur': 1,
'tarif': 213,
'dispo': 21
},
{
'date': '12/10/2016',
'id_hebergeur': 1,
'tarif': 235,
'dispo': 21
},
{
'date': '13/10/2016',
'id_hebergeur': 1,
'tarif': 125,
'dispo': 21
},
{
'date': '14/10/2016',
'id_hebergeur': 1,
'tarif': 89,
'dispo': 21
},
{
'date': '15/10/2016',
'id_hebergeur': 1,
'tarif': 54,
'dispo': 21
},
{
'date': '16/10/2016',
'id_hebergeur': 1,
'tarif': 252,
'dispo': 21
},
{
'date': '17/10/2016',
'id_hebergeur': 1,
'tarif': 245,
'dispo': 21
},
{
'date': '18/10/2016',
'id_hebergeur': 1,
'tarif': 35,
'dispo': 21
},
{
'date': '19/10/2016',
'id_hebergeur': 1,
'tarif': 252,
'dispo': 21
},
{
'date': '20/10/2016',
'id_hebergeur': 1,
'tarif': 24,
'dispo': 21
},
{
'date': '21/10/2016',
'id_hebergeur': 1,
'tarif': 252,
'dispo': 21
},
{
'date': '22/10/2016',
'id_hebergeur': 1,
'tarif': 127,
'dispo': 21
},
{
'date': '23/10/2016',
'id_hebergeur': 1,
'tarif': 48,
'dispo': 21
},
{
'date': '24/10/2016',
'id_hebergeur': 1,
'tarif': 252,
'dispo': 21
},
{
'date': '25/10/2016',
'id_hebergeur': 1,
'tarif': 235,
'dispo': 21
},
{
'date': '26/10/2016',
'id_hebergeur': 1,
'tarif': 256,
'dispo': 21
},
{
'date': '28/10/2016',
'id_hebergeur': 1,
'tarif': 252,
'dispo': 21
},
{
'date': '29/10/2016',
'id_hebergeur': 1,
'tarif': 41,
'dispo': 21
},
{
'date': '30/10/2016',
'id_hebergeur': 1,
'tarif': 333,
'dispo': 21
},
{
'date': '31/10/2016',
'id_hebergeur': 1,
'tarif': 252,
'dispo': 21
},
{
'date': '01/11/2016',
'id_hebergeur': 1,
'tarif': 252,
'dispo': 21
},
{
'date': '02/11/2016',
'id_hebergeur': 1,
'tarif': 150,
'dispo': 21
},
{
'date': '03/11/2016',
'id_hebergeur': 1,
'tarif': 123,
'dispo': 21
},
{
'date': '04/11/2016',
'id_hebergeur': 1,
'tarif': 56,
'dispo': 21
},
{
'date': '05/11/2016',
'id_hebergeur': 1,
'tarif': 632,
'dispo': 21
},
{
'date': '06/11/2016',
'id_hebergeur': 1,
'tarif': 236,
'dispo': 21
},
{
'date': '07/11/2016',
'id_hebergeur': 1,
'tarif': 25,
'dispo': 21
},
{
'date': '08/11/2016',
'id_hebergeur': 1,
'tarif': 23,
'dispo': 21
},
{
'date': '09/11/2016',
'id_hebergeur': 1,
'tarif': 365,
'dispo': 21
},
{
'date': '10/11/2016',
'id_hebergeur': 1,
'tarif': 245,
'dispo': 21
},
{
'date': '11/11/2016',
'id_hebergeur': 1,
'tarif': 213,
'dispo': 21
},
{
'date': '12/11/2016',
'id_hebergeur': 1,
'tarif': 235,
'dispo': 21
},
{
'date': '13/11/2016',
'id_hebergeur': 1,
'tarif': 125,
'dispo': 21
},
{
'date': '14/11/2016',
'id_hebergeur': 1,
'tarif': 89,
'dispo': 21
},
{
'date': '15/11/2016',
'id_hebergeur': 1,
'tarif': 54,
'dispo': 21
},
{
'date': '16/11/2016',
'id_hebergeur': 1,
'tarif': 252,
'dispo': 21
},
{
'date': '17/11/2016',
'id_hebergeur': 1,
'tarif': 245,
'dispo': 21
},
{
'date': '18/11/2016',
'id_hebergeur': 1,
'tarif': 35,
'dispo': 21
},
{
'date': '19/11/2016',
'id_hebergeur': 1,
'tarif': 252,
'dispo': 21
},
{
'date': '20/11/2016',
'id_hebergeur': 1,
'tarif': 24,
'dispo': 21
},
{
'date': '21/11/2016',
'id_hebergeur': 1,
'tarif': 252,
'dispo': 21
},
{
'date': '22/11/2016',
'id_hebergeur': 1,
'tarif': 127,
'dispo': 21
},
{
'date': '23/11/2016',
'id_hebergeur': 1,
'tarif': 48,
'dispo': 21
},
{
'date': '24/11/2016',
'id_hebergeur': 1,
'tarif': 252,
'dispo': 21
},
{
'date': '25/11/2016',
'id_hebergeur': 1,
'tarif': 235,
'dispo': 21
},
{
'date': '26/11/2016',
'id_hebergeur': 1,
'tarif': 256,
'dispo': 21
},
{
'date': '28/11/2016',
'id_hebergeur': 1,
'tarif': 252,
'dispo': 21
},
{
'date': '29/11/2016',
'id_hebergeur': 1,
'tarif': 41,
'dispo': 21
},
{
'date': '30/11/2016',
'id_hebergeur': 1,
'tarif': 333,
'dispo': 21
},
{
'date': '01/10/2016',
'id_hebergeur': 2,
'tarif': 252,
'dispo': 12
},
{
'date': '02/10/2016',
'id_hebergeur': 2,
'tarif': 145,
'dispo': 12
},
{
'date': '03/10/2016',
'id_hebergeur': 2,
'tarif': 11,
'dispo': 12
},
{
'date': '04/10/2016',
'id_hebergeur': 2,
'tarif': 55,
'dispo': 12
},
{
'date': '05/10/2016',
'id_hebergeur': 2,
'tarif': 66,
'dispo': 12
},
{
'date': '06/10/2016',
'id_hebergeur': 2,
'tarif': 88,
'dispo': 12
},
{
'date': '07/10/2016',
'id_hebergeur': 2,
'tarif': 55,
'dispo': 12
},
{
'date': '08/10/2016',
'id_hebergeur': 2,
'tarif': 66,
'dispo': 12
},
{
'date': '09/10/2016',
'id_hebergeur': 2,
'tarif': 47,
'dispo': 12
},
{
'date': '10/10/2016',
'id_hebergeur': 2,
'tarif': 74,
'dispo': 12
},
{
'date': '11/10/2016',
'id_hebergeur': 2,
'tarif': 447,
'dispo': 12
},
{
'date': '12/10/2016',
'id_hebergeur': 2,
'tarif': 235,
'dispo': 12
},
{
'date': '13/10/2016',
'id_hebergeur': 2,
'tarif': 125,
'dispo': 12
},
{
'date': '14/10/2016',
'id_hebergeur': 2,
'tarif': 44,
'dispo': 12
},
{
'date': '15/10/2016',
'id_hebergeur': 2,
'tarif': 256,
'dispo': 12
},
{
'date': '16/10/2016',
'id_hebergeur': 2,
'tarif': 252,
'dispo': 12
},
{
'date': '17/10/2016',
'id_hebergeur': 2,
'tarif': 245,
'dispo': 12
},
{
'date': '18/10/2016',
'id_hebergeur': 2,
'tarif': 47,
'dispo': 12
},
{
'date': '19/10/2016',
'id_hebergeur': 2,
'tarif': 252,
'dispo': 12
},
{
'date': '20/10/2016',
'id_hebergeur': 2,
'tarif': 44,
'dispo': 12
},
{
'date': '21/10/2016',
'id_hebergeur': 2,
'tarif': 252,
'dispo': 12
},
{
'date': '22/10/2016',
'id_hebergeur': 2,
'tarif': 14,
'dispo': 12
},
{
'date': '23/10/2016',
'id_hebergeur': 2,
'tarif': 48,
'dispo': 12
},
{
'date': '24/10/2016',
'id_hebergeur': 2,
'tarif': 252,
'dispo': 12
},
{
'date': '25/10/2016',
'id_hebergeur': 2,
'tarif': 235,
'dispo': 12
},
{
'date': '26/10/2016',
'id_hebergeur': 2,
'tarif': 142,
'dispo': 12
},
{
'date': '28/10/2016',
'id_hebergeur': 2,
'tarif': 45,
'dispo': 12
},
{
'date': '29/10/2016',
'id_hebergeur': 2,
'tarif': 41,
'dispo': 12
},
{
'date': '30/10/2016',
'id_hebergeur': 2,
'tarif': 55,
'dispo': 12
},
{
'date': '31/10/2016',
'id_hebergeur': 2,
'tarif': 55,
'dispo': 12
},
{
'date': '01/11/2016',
'id_hebergeur': 2,
'tarif': 55,
'dispo': 12
},
{
'date': '02/11/2016',
'id_hebergeur': 2,
'tarif': 55,
'dispo': 12
},
{
'date': '03/11/2016',
'id_hebergeur': 2,
'tarif': 55,
'dispo': 12
},
{
'date': '04/11/2016',
'id_hebergeur': 2,
'tarif': 55,
'dispo': 12
},
{
'date': '05/11/2016',
'id_hebergeur': 2,
'tarif': 55,
'dispo': 12
},
{
'date': '06/11/2016',
'id_hebergeur': 2,
'tarif': 55,
'dispo': 12
},
{
'date': '07/11/2016',
'id_hebergeur': 2,
'tarif': 55,
'dispo': 12
},
{
'date': '08/11/2016',
'id_hebergeur': 2,
'tarif': 23,
'dispo': 12
},
{
'date': '09/11/2016',
'id_hebergeur': 2,
'tarif': 55,
'dispo': 12
},
{
'date': '10/11/2016',
'id_hebergeur': 2,
'tarif': 55,
'dispo': 12
},
{
'date': '11/11/2016',
'id_hebergeur': 2,
'tarif': 55,
'dispo': 12
},
{
'date': '12/11/2016',
'id_hebergeur': 2,
'tarif': 235,
'dispo': 12
},
{
'date': '13/11/2016',
'id_hebergeur': 2,
'tarif': 125,
'dispo': 12
},
{
'date': '14/11/2016',
'id_hebergeur': 2,
'tarif': 89,
'dispo': 12
},
{
'date': '15/11/2016',
'id_hebergeur': 2,
'tarif': 55,
'dispo': 12
},
{
'date': '16/11/2016',
'id_hebergeur': 2,
'tarif': 55,
'dispo': 12
},
{
'date': '17/11/2016',
'id_hebergeur': 2,
'tarif': 55,
'dispo': 12
},
{
'date': '18/11/2016',
'id_hebergeur': 2,
'tarif': 35,
'dispo': 12
},
{
'date': '19/11/2016',
'id_hebergeur': 2,
'tarif': 252,
'dispo': 12
},
{
'date': '20/11/2016',
'id_hebergeur': 2,
'tarif': 55,
'dispo': 12
},
{
'date': '21/11/2016',
'id_hebergeur': 2,
'tarif': 252,
'dispo': 12
},
{
'date': '22/11/2016',
'id_hebergeur': 2,
'tarif': 55,
'dispo': 12
},
{
'date': '23/11/2016',
'id_hebergeur': 2,
'tarif': 48,
'dispo': 12
},
{
'date': '24/11/2016',
'id_hebergeur': 2,
'tarif': 55,
'dispo': 12
},
{
'date': '25/11/2016',
'id_hebergeur': 2,
'tarif': 55,
'dispo': 12
},
{
'date': '26/11/2016',
'id_hebergeur': 2,
'tarif': 55,
'dispo': 12
},
{
'date': '28/11/2016',
'id_hebergeur': 2,
'tarif': 55,
'dispo': 12
},
{
'date': '29/11/2016',
'id_hebergeur': 2,
'tarif': 41,
'dispo': 12
},
{
'date': '30/11/2016',
'id_hebergeur': 2,
'tarif': 55,
'dispo': 12
},
{
'date': '01/10/2016',
'id_hebergeur': 3,
'tarif': 252,
'dispo': 58
},
{
'date': '02/10/2016',
'id_hebergeur': 3,
'tarif': 145,
'dispo': 58
},
{
'date': '03/10/2016',
'id_hebergeur': 3,
'tarif': 11,
'dispo': 58
},
{
'date': '04/10/2016',
'id_hebergeur': 3,
'tarif': 55,
'dispo': 58
},
{
'date': '05/10/2016',
'id_hebergeur': 3,
'tarif': 66,
'dispo': 58
},
{
'date': '06/10/2016',
'id_hebergeur': 3,
'tarif': 88,
'dispo': 58
},
{
'date': '07/10/2016',
'id_hebergeur': 3,
'tarif': 55,
'dispo': 58
},
{
'date': '08/10/2016',
'id_hebergeur': 3,
'tarif': 66,
'dispo': 58
},
{
'date': '09/10/2016',
'id_hebergeur': 3,
'tarif': 47,
'dispo': 58
},
{
'date': '10/10/2016',
'id_hebergeur': 3,
'tarif': 74,
'dispo': 58
},
{
'date': '11/10/2016',
'id_hebergeur': 3,
'tarif': 447,
'dispo': 58
},
{
'date': '58/10/2016',
'id_hebergeur': 3,
'tarif': 235,
'dispo': 58
},
{
'date': '13/10/2016',
'id_hebergeur': 3,
'tarif': 585,
'dispo': 58
},
{
'date': '14/10/2016',
'id_hebergeur': 3,
'tarif': 44,
'dispo': 58
},
{
'date': '15/10/2016',
'id_hebergeur': 3,
'tarif': 256,
'dispo': 58
},
{
'date': '16/10/2016',
'id_hebergeur': 3,
'tarif': 252,
'dispo': 58
},
{
'date': '17/10/2016',
'id_hebergeur': 3,
'tarif': 245,
'dispo': 58
},
{
'date': '18/10/2016',
'id_hebergeur': 3,
'tarif': 47,
'dispo': 58
},
{
'date': '19/10/2016',
'id_hebergeur': 3,
'tarif': 252,
'dispo': 58
},
{
'date': '20/10/2016',
'id_hebergeur': 3,
'tarif': 44,
'dispo': 58
},
{
'date': '21/10/2016',
'id_hebergeur': 3,
'tarif': 252,
'dispo': 58
},
{
'date': '22/10/2016',
'id_hebergeur': 3,
'tarif': 14,
'dispo': 58
},
{
'date': '23/10/2016',
'id_hebergeur': 3,
'tarif': 48,
'dispo': 58
},
{
'date': '24/10/2016',
'id_hebergeur': 3,
'tarif': 252,
'dispo': 58
},
{
'date': '25/10/2016',
'id_hebergeur': 3,
'tarif': 235,
'dispo': 58
},
{
'date': '26/10/2016',
'id_hebergeur': 3,
'tarif': 142,
'dispo': 58
},
{
'date': '28/10/2016',
'id_hebergeur': 3,
'tarif': 45,
'dispo': 58
},
{
'date': '29/10/2016',
'id_hebergeur': 3,
'tarif': 41,
'dispo': 58
},
{
'date': '30/10/2016',
'id_hebergeur': 3,
'tarif': 55,
'dispo': 58
},
{
'date': '31/10/2016',
'id_hebergeur': 3,
'tarif': 55,
'dispo': 58
},
{
'date': '01/11/2016',
'id_hebergeur': 3,
'tarif': 55,
'dispo': 58
},
{
'date': '02/11/2016',
'id_hebergeur': 3,
'tarif': 55,
'dispo': 58
},
{
'date': '03/11/2016',
'id_hebergeur': 3,
'tarif': 55,
'dispo': 58
},
{
'date': '04/11/2016',
'id_hebergeur': 3,
'tarif': 55,
'dispo': 58
},
{
'date': '05/11/2016',
'id_hebergeur': 3,
'tarif': 55,
'dispo': 58
},
{
'date': '06/11/2016',
'id_hebergeur': 3,
'tarif': 55,
'dispo': 58
},
{
'date': '07/11/2016',
'id_hebergeur': 3,
'tarif': 55,
'dispo': 58
},
{
'date': '08/11/2016',
'id_hebergeur': 3,
'tarif': 23,
'dispo': 58
},
{
'date': '09/11/2016',
'id_hebergeur': 3,
'tarif': 55,
'dispo': 58
},
{
'date': '10/11/2016',
'id_hebergeur': 3,
'tarif': 55,
'dispo': 58
},
{
'date': '11/11/2016',
'id_hebergeur': 3,
'tarif': 55,
'dispo': 58
},
{
'date': '58/11/2016',
'id_hebergeur': 3,
'tarif': 235,
'dispo': 58
},
{
'date': '13/11/2016',
'id_hebergeur': 3,
'tarif': 585,
'dispo': 58
},
{
'date': '14/11/2016',
'id_hebergeur': 3,
'tarif': 89,
'dispo': 58
},
{
'date': '15/11/2016',
'id_hebergeur': 3,
'tarif': 55,
'dispo': 58
},
{
'date': '16/11/2016',
'id_hebergeur': 3,
'tarif': 55,
'dispo': 58
},
{
'date': '17/11/2016',
'id_hebergeur': 3,
'tarif': 55,
'dispo': 58
},
{
'date': '18/11/2016',
'id_hebergeur': 3,
'tarif': 35,
'dispo': 58
},
{
'date': '19/11/2016',
'id_hebergeur': 3,
'tarif': 252,
'dispo': 58
},
{
'date': '20/11/2016',
'id_hebergeur': 3,
'tarif': 55,
'dispo': 58
},
{
'date': '21/11/2016',
'id_hebergeur': 3,
'tarif': 252,
'dispo': 58
},
{
'date': '22/11/2016',
'id_hebergeur': 3,
'tarif': 55,
'dispo': 58
},
{
'date': '23/11/2016',
'id_hebergeur': 3,
'tarif': 48,
'dispo': 58
},
{
'date': '24/11/2016',
'id_hebergeur': 3,
'tarif': 55,
'dispo': 58
},
{
'date': '25/11/2016',
'id_hebergeur': 3,
'tarif': 55,
'dispo': 58
},
{
'date': '26/11/2016',
'id_hebergeur': 3,
'tarif': 55,
'dispo': 58
},
{
'date': '28/11/2016',
'id_hebergeur': 3,
'tarif': 55,
'dispo': 58
},
{
'date': '29/11/2016',
'id_hebergeur': 3,
'tarif': 41,
'dispo': 58
},
{
'date': '30/11/2016',
'id_hebergeur': 3,
'tarif': 55,
'dispo': 58
},
{
'date': '01/10/2016',
'id_hebergeur': 4,
'tarif': 252,
'dispo': 23
},
{
'date': '02/10/2016',
'id_hebergeur': 4,
'tarif': 145,
'dispo': 23
},
{
'date': '03/10/2016',
'id_hebergeur': 4,
'tarif': 11,
'dispo': 23
},
{
'date': '04/10/2016',
'id_hebergeur': 4,
'tarif': 55,
'dispo': 23
},
{
'date': '05/10/2016',
'id_hebergeur': 4,
'tarif': 66,
'dispo': 23
},
{
'date': '06/10/2016',
'id_hebergeur': 4,
'tarif': 88,
'dispo': 23
},
{
'date': '07/10/2016',
'id_hebergeur': 4,
'tarif': 55,
'dispo': 23
},
{
'date': '08/10/2016',
'id_hebergeur': 4,
'tarif': 66,
'dispo': 23
},
{
'date': '09/10/2016',
'id_hebergeur': 4,
'tarif': 47,
'dispo': 23
},
{
'date': '10/10/2016',
'id_hebergeur': 4,
'tarif': 74,
'dispo': 23
},
{
'date': '11/10/2016',
'id_hebergeur': 4,
'tarif': 447,
'dispo': 23
},
{
'date': '23/10/2016',
'id_hebergeur': 4,
'tarif': 235,
'dispo': 23
},
{
'date': '13/10/2016',
'id_hebergeur': 4,
'tarif': 235,
'dispo': 23
},
{
'date': '14/10/2016',
'id_hebergeur': 4,
'tarif': 44,
'dispo': 23
},
{
'date': '15/10/2016',
'id_hebergeur': 4,
'tarif': 256,
'dispo': 23
},
{
'date': '16/10/2016',
'id_hebergeur': 4,
'tarif': 252,
'dispo': 23
},
{
'date': '17/10/2016',
'id_hebergeur': 4,
'tarif': 245,
'dispo': 23
},
{
'date': '18/10/2016',
'id_hebergeur': 4,
'tarif': 47,
'dispo': 23
},
{
'date': '19/10/2016',
'id_hebergeur': 4,
'tarif': 252,
'dispo': 23
},
{
'date': '20/10/2016',
'id_hebergeur': 4,
'tarif': 44,
'dispo': 23
},
{
'date': '21/10/2016',
'id_hebergeur': 4,
'tarif': 252,
'dispo': 23
},
{
'date': '22/10/2016',
'id_hebergeur': 4,
'tarif': 14,
'dispo': 23
},
{
'date': '23/10/2016',
'id_hebergeur': 4,
'tarif': 48,
'dispo': 23
},
{
'date': '24/10/2016',
'id_hebergeur': 4,
'tarif': 252,
'dispo': 23
},
{
'date': '25/10/2016',
'id_hebergeur': 4,
'tarif': 235,
'dispo': 23
},
{
'date': '26/10/2016',
'id_hebergeur': 4,
'tarif': 142,
'dispo': 23
},
{
'date': '28/10/2016',
'id_hebergeur': 4,
'tarif': 45,
'dispo': 23
},
{
'date': '29/10/2016',
'id_hebergeur': 4,
'tarif': 41,
'dispo': 23
},
{
'date': '30/10/2016',
'id_hebergeur': 4,
'tarif': 55,
'dispo': 23
},
{
'date': '31/10/2016',
'id_hebergeur': 4,
'tarif': 55,
'dispo': 23
},
{
'date': '01/11/2016',
'id_hebergeur': 4,
'tarif': 55,
'dispo': 23
},
{
'date': '02/11/2016',
'id_hebergeur': 4,
'tarif': 55,
'dispo': 23
},
{
'date': '03/11/2016',
'id_hebergeur': 4,
'tarif': 55,
'dispo': 23
},
{
'date': '04/11/2016',
'id_hebergeur': 4,
'tarif': 55,
'dispo': 23
},
{
'date': '05/11/2016',
'id_hebergeur': 4,
'tarif': 55,
'dispo': 23
},
{
'date': '06/11/2016',
'id_hebergeur': 4,
'tarif': 55,
'dispo': 23
},
{
'date': '07/11/2016',
'id_hebergeur': 4,
'tarif': 55,
'dispo': 23
},
{
'date': '08/11/2016',
'id_hebergeur': 4,
'tarif': 23,
'dispo': 23
},
{
'date': '09/11/2016',
'id_hebergeur': 4,
'tarif': 55,
'dispo': 23
},
{
'date': '10/11/2016',
'id_hebergeur': 4,
'tarif': 55,
'dispo': 23
},
{
'date': '11/11/2016',
'id_hebergeur': 4,
'tarif': 55,
'dispo': 23
},
{
'date': '23/11/2016',
'id_hebergeur': 4,
'tarif': 235,
'dispo': 23
},
{
'date': '13/11/2016',
'id_hebergeur': 4,
'tarif': 235,
'dispo': 23
},
{
'date': '14/11/2016',
'id_hebergeur': 4,
'tarif': 89,
'dispo': 23
},
{
'date': '15/11/2016',
'id_hebergeur': 4,
'tarif': 55,
'dispo': 23
},
{
'date': '16/11/2016',
'id_hebergeur': 4,
'tarif': 55,
'dispo': 23
},
{
'date': '17/11/2016',
'id_hebergeur': 4,
'tarif': 55,
'dispo': 23
},
{
'date': '18/11/2016',
'id_hebergeur': 4,
'tarif': 35,
'dispo': 23
},
{
'date': '19/11/2016',
'id_hebergeur': 4,
'tarif': 252,
'dispo': 23
},
{
'date': '20/11/2016',
'id_hebergeur': 4,
'tarif': 55,
'dispo': 23
},
{
'date': '21/11/2016',
'id_hebergeur': 4,
'tarif': 252,
'dispo': 23
},
{
'date': '22/11/2016',
'id_hebergeur': 4,
'tarif': 55,
'dispo': 23
},
{
'date': '23/11/2016',
'id_hebergeur': 4,
'tarif': 48,
'dispo': 23
},
{
'date': '24/11/2016',
'id_hebergeur': 4,
'tarif': 55,
'dispo': 23
},
{
'date': '25/11/2016',
'id_hebergeur': 4,
'tarif': 55,
'dispo': 23
},
{
'date': '26/11/2016',
'id_hebergeur': 4,
'tarif': 55,
'dispo': 23
},
{
'date': '28/11/2016',
'id_hebergeur': 4,
'tarif': 55,
'dispo': 23
},
{
'date': '29/11/2016',
'id_hebergeur': 4,
'tarif': 41,
'dispo': 23
},
{
'date': '30/11/2016',
'id_hebergeur': 4,
'tarif': 55,
'dispo': 23
},
{
'date': '01/10/2016',
'id_hebergeur': 5,
'tarif': 252,
'dispo': 18
},
{
'date': '02/10/2016',
'id_hebergeur': 5,
'tarif': 145,
'dispo': 18
},
{
'date': '03/10/2016',
'id_hebergeur': 5,
'tarif': 11,
'dispo': 18
},
{
'date': '04/10/2016',
'id_hebergeur': 5,
'tarif': 55,
'dispo': 18
},
{
'date': '05/10/2016',
'id_hebergeur': 5,
'tarif': 66,
'dispo': 18
},
{
'date': '06/10/2016',
'id_hebergeur': 5,
'tarif': 88,
'dispo': 18
},
{
'date': '07/10/2016',
'id_hebergeur': 5,
'tarif': 55,
'dispo': 18
},
{
'date': '08/10/2016',
'id_hebergeur': 5,
'tarif': 66,
'dispo': 18
},
{
'date': '09/10/2016',
'id_hebergeur': 5,
'tarif': 47,
'dispo': 18
},
{
'date': '10/10/2016',
'id_hebergeur': 5,
'tarif': 74,
'dispo': 18
},
{
'date': '11/10/2016',
'id_hebergeur': 5,
'tarif': 447,
'dispo': 18
},
{
'date': '18/10/2016',
'id_hebergeur': 5,
'tarif': 185,
'dispo': 18
},
{
'date': '13/10/2016',
'id_hebergeur': 5,
'tarif': 185,
'dispo': 18
},
{
'date': '14/10/2016',
'id_hebergeur': 5,
'tarif': 44,
'dispo': 18
},
{
'date': '15/10/2016',
'id_hebergeur': 5,
'tarif': 256,
'dispo': 18
},
{
'date': '16/10/2016',
'id_hebergeur': 5,
'tarif': 252,
'dispo': 18
},
{
'date': '17/10/2016',
'id_hebergeur': 5,
'tarif': 245,
'dispo': 18
},
{
'date': '18/10/2016',
'id_hebergeur': 5,
'tarif': 47,
'dispo': 18
},
{
'date': '19/10/2016',
'id_hebergeur': 5,
'tarif': 252,
'dispo': 18
},
{
'date': '20/10/2016',
'id_hebergeur': 5,
'tarif': 44,
'dispo': 18
},
{
'date': '21/10/2016',
'id_hebergeur': 5,
'tarif': 252,
'dispo': 18
},
{
'date': '22/10/2016',
'id_hebergeur': 5,
'tarif': 14,
'dispo': 18
},
{
'date': '18/10/2016',
'id_hebergeur': 5,
'tarif': 48,
'dispo': 18
},
{
'date': '24/10/2016',
'id_hebergeur': 5,
'tarif': 252,
'dispo': 18
},
{
'date': '25/10/2016',
'id_hebergeur': 5,
'tarif': 185,
'dispo': 18
},
{
'date': '26/10/2016',
'id_hebergeur': 5,
'tarif': 142,
'dispo': 18
},
{
'date': '28/10/2016',
'id_hebergeur': 5,
'tarif': 45,
'dispo': 18
},
{
'date': '29/10/2016',
'id_hebergeur': 5,
'tarif': 41,
'dispo': 18
},
{
'date': '30/10/2016',
'id_hebergeur': 5,
'tarif': 55,
'dispo': 18
},
{
'date': '31/10/2016',
'id_hebergeur': 5,
'tarif': 55,
'dispo': 18
},
{
'date': '01/11/2016',
'id_hebergeur': 5,
'tarif': 55,
'dispo': 18
},
{
'date': '02/11/2016',
'id_hebergeur': 5,
'tarif': 55,
'dispo': 18
},
{
'date': '03/11/2016',
'id_hebergeur': 5,
'tarif': 55,
'dispo': 18
},
{
'date': '04/11/2016',
'id_hebergeur': 5,
'tarif': 55,
'dispo': 18
},
{
'date': '05/11/2016',
'id_hebergeur': 5,
'tarif': 55,
'dispo': 18
},
{
'date': '06/11/2016',
'id_hebergeur': 5,
'tarif': 55,
'dispo': 18
},
{
'date': '07/11/2016',
'id_hebergeur': 5,
'tarif': 55,
'dispo': 18
},
{
'date': '08/11/2016',
'id_hebergeur': 5,
'tarif': 18,
'dispo': 18
},
{
'date': '09/11/2016',
'id_hebergeur': 5,
'tarif': 55,
'dispo': 18
},
{
'date': '10/11/2016',
'id_hebergeur': 5,
'tarif': 55,
'dispo': 18
},
{
'date': '11/11/2016',
'id_hebergeur': 5,
'tarif': 55,
'dispo': 18
},
{
'date': '18/11/2016',
'id_hebergeur': 5,
'tarif': 185,
'dispo': 18
},
{
'date': '13/11/2016',
'id_hebergeur': 5,
'tarif': 185,
'dispo': 18
},
{
'date': '14/11/2016',
'id_hebergeur': 5,
'tarif': 89,
'dispo': 18
},
{
'date': '15/11/2016',
'id_hebergeur': 5,
'tarif': 55,
'dispo': 18
},
{
'date': '16/11/2016',
'id_hebergeur': 5,
'tarif': 55,
'dispo': 18
},
{
'date': '17/11/2016',
'id_hebergeur': 5,
'tarif': 55,
'dispo': 18
},
{
'date': '18/11/2016',
'id_hebergeur': 5,
'tarif': 35,
'dispo': 18
},
{
'date': '19/11/2016',
'id_hebergeur': 5,
'tarif': 252,
'dispo': 18
},
{
'date': '20/11/2016',
'id_hebergeur': 5,
'tarif': 55,
'dispo': 18
},
{
'date': '21/11/2016',
'id_hebergeur': 5,
'tarif': 252,
'dispo': 18
},
{
'date': '22/11/2016',
'id_hebergeur': 5,
'tarif': 55,
'dispo': 18
},
{
'date': '18/11/2016',
'id_hebergeur': 5,
'tarif': 48,
'dispo': 18
},
{
'date': '24/11/2016',
'id_hebergeur': 5,
'tarif': 55,
'dispo': 18
},
{
'date': '25/11/2016',
'id_hebergeur': 5,
'tarif': 55,
'dispo': 18
},
{
'date': '26/11/2016',
'id_hebergeur': 5,
'tarif': 55,
'dispo': 18
},
{
'date': '28/11/2016',
'id_hebergeur': 5,
'tarif': 55,
'dispo': 18
},
{
'date': '29/11/2016',
'id_hebergeur': 5,
'tarif': 41,
'dispo': 18
},
{
'date': '30/11/2016',
'id_hebergeur': 5,
'tarif': 55,
'dispo': 18
},
{
'date': '01/10/2016',
'id_hebergeur': 6,
'tarif': 252,
'dispo': 9
},
{
'date': '02/10/2016',
'id_hebergeur': 6,
'tarif': 145,
'dispo': 9
},
{
'date': '03/10/2016',
'id_hebergeur': 6,
'tarif': 11,
'dispo': 9
},
{
'date': '04/10/2016',
'id_hebergeur': 6,
'tarif': 55,
'dispo': 9
},
{
'date': '05/10/2016',
'id_hebergeur': 6,
'tarif': 66,
'dispo': 9
},
{
'date': '06/10/2016',
'id_hebergeur': 6,
'tarif': 88,
'dispo': 9
},
{
'date': '07/10/2016',
'id_hebergeur': 6,
'tarif': 55,
'dispo': 9
},
{
'date': '08/10/2016',
'id_hebergeur': 6,
'tarif': 66,
'dispo': 9
},
{
'date': '09/10/2016',
'id_hebergeur': 6,
'tarif': 47,
'dispo': 9
},
{
'date': '10/10/2016',
'id_hebergeur': 6,
'tarif': 74,
'dispo': 9
},
{
'date': '11/10/2016',
'id_hebergeur': 6,
'tarif': 447,
'dispo': 9
},
{
'date': '9/10/2016',
'id_hebergeur': 6,
'tarif': 95,
'dispo': 9
},
{
'date': '13/10/2016',
'id_hebergeur': 6,
'tarif': 95,
'dispo': 9
},
{
'date': '14/10/2016',
'id_hebergeur': 6,
'tarif': 44,
'dispo': 9
},
{
'date': '15/10/2016',
'id_hebergeur': 6,
'tarif': 256,
'dispo': 9
},
{
'date': '16/10/2016',
'id_hebergeur': 6,
'tarif': 252,
'dispo': 9
},
{
'date': '17/10/2016',
'id_hebergeur': 6,
'tarif': 245,
'dispo': 9
},
{
'date': '9/10/2016',
'id_hebergeur': 6,
'tarif': 47,
'dispo': 9
},
{
'date': '19/10/2016',
'id_hebergeur': 6,
'tarif': 252,
'dispo': 9
},
{
'date': '20/10/2016',
'id_hebergeur': 6,
'tarif': 44,
'dispo': 9
},
{
'date': '21/10/2016',
'id_hebergeur': 6,
'tarif': 252,
'dispo': 9
},
{
'date': '22/10/2016',
'id_hebergeur': 6,
'tarif': 14,
'dispo': 9
},
{
'date': '9/10/2016',
'id_hebergeur': 6,
'tarif': 48,
'dispo': 9
},
{
'date': '24/10/2016',
'id_hebergeur': 6,
'tarif': 252,
'dispo': 9
},
{
'date': '25/10/2016',
'id_hebergeur': 6,
'tarif': 95,
'dispo': 9
},
{
'date': '26/10/2016',
'id_hebergeur': 6,
'tarif': 142,
'dispo': 9
},
{
'date': '28/10/2016',
'id_hebergeur': 6,
'tarif': 45,
'dispo': 9
},
{
'date': '29/10/2016',
'id_hebergeur': 6,
'tarif': 41,
'dispo': 9
},
{
'date': '30/10/2016',
'id_hebergeur': 6,
'tarif': 55,
'dispo': 9
},
{
'date': '31/10/2016',
'id_hebergeur': 6,
'tarif': 55,
'dispo': 9
},
{
'date': '01/11/2016',
'id_hebergeur': 6,
'tarif': 55,
'dispo': 9
},
{
'date': '02/11/2016',
'id_hebergeur': 6,
'tarif': 55,
'dispo': 9
},
{
'date': '03/11/2016',
'id_hebergeur': 6,
'tarif': 55,
'dispo': 9
},
{
'date': '04/11/2016',
'id_hebergeur': 6,
'tarif': 55,
'dispo': 9
},
{
'date': '05/11/2016',
'id_hebergeur': 6,
'tarif': 55,
'dispo': 9
},
{
'date': '06/11/2016',
'id_hebergeur': 6,
'tarif': 55,
'dispo': 9
},
{
'date': '07/11/2016',
'id_hebergeur': 6,
'tarif': 55,
'dispo': 9
},
{
'date': '08/11/2016',
'id_hebergeur': 6,
'tarif': 9,
'dispo': 9
},
{
'date': '09/11/2016',
'id_hebergeur': 6,
'tarif': 55,
'dispo': 9
},
{
'date': '10/11/2016',
'id_hebergeur': 6,
'tarif': 55,
'dispo': 9
},
{
'date': '11/11/2016',
'id_hebergeur': 6,
'tarif': 55,
'dispo': 9
},
{
'date': '9/11/2016',
'id_hebergeur': 6,
'tarif': 95,
'dispo': 9
},
{
'date': '13/11/2016',
'id_hebergeur': 6,
'tarif': 95,
'dispo': 9
},
{
'date': '14/11/2016',
'id_hebergeur': 6,
'tarif': 89,
'dispo': 9
},
{
'date': '15/11/2016',
'id_hebergeur': 6,
'tarif': 55,
'dispo': 9
},
{
'date': '16/11/2016',
'id_hebergeur': 6,
'tarif': 55,
'dispo': 9
},
{
'date': '17/11/2016',
'id_hebergeur': 6,
'tarif': 55,
'dispo': 9
},
{
'date': '9/11/2016',
'id_hebergeur': 6,
'tarif': 35,
'dispo': 9
},
{
'date': '19/11/2016',
'id_hebergeur': 6,
'tarif': 252,
'dispo': 9
},
{
'date': '20/11/2016',
'id_hebergeur': 6,
'tarif': 55,
'dispo': 9
},
{
'date': '21/11/2016',
'id_hebergeur': 6,
'tarif': 252,
'dispo': 9
},
{
'date': '22/11/2016',
'id_hebergeur': 6,
'tarif': 55,
'dispo': 9
},
{
'date': '9/11/2016',
'id_hebergeur': 6,
'tarif': 48,
'dispo': 9
},
{
'date': '24/11/2016',
'id_hebergeur': 6,
'tarif': 55,
'dispo': 9
},
{
'date': '25/11/2016',
'id_hebergeur': 6,
'tarif': 55,
'dispo': 9
},
{
'date': '26/11/2016',
'id_hebergeur': 6,
'tarif': 55,
'dispo': 9
},
{
'date': '28/11/2016',
'id_hebergeur': 6,
'tarif': 55,
'dispo': 9
},
{
'date': '29/11/2016',
'id_hebergeur': 6,
'tarif': 41,
'dispo': 9
},
{
'date': '30/11/2016',
'id_hebergeur': 6,
'tarif': 55,
'dispo': 9
},
{
'date': '01/10/2016',
'id_hebergeur': 7,
'tarif': 252,
'dispo': 25
},
{
'date': '02/10/2016',
'id_hebergeur': 7,
'tarif': 145,
'dispo': 25
},
{
'date': '03/10/2016',
'id_hebergeur': 7,
'tarif': 11,
'dispo': 25
},
{
'date': '04/10/2016',
'id_hebergeur': 7,
'tarif': 55,
'dispo': 25
},
{
'date': '05/10/2016',
'id_hebergeur': 7,
'tarif': 66,
'dispo': 25
},
{
'date': '06/10/2016',
'id_hebergeur': 7,
'tarif': 88,
'dispo': 25
},
{
'date': '07/10/2016',
'id_hebergeur': 7,
'tarif': 55,
'dispo': 25
},
{
'date': '08/10/2016',
'id_hebergeur': 7,
'tarif': 66,
'dispo': 25
},
{
'date': '025/10/2016',
'id_hebergeur': 7,
'tarif': 47,
'dispo': 25
},
{
'date': '10/10/2016',
'id_hebergeur': 7,
'tarif': 74,
'dispo': 25
},
{
'date': '11/10/2016',
'id_hebergeur': 7,
'tarif': 447,
'dispo': 25
},
{
'date': '25/10/2016',
'id_hebergeur': 7,
'tarif': 255,
'dispo': 25
},
{
'date': '13/10/2016',
'id_hebergeur': 7,
'tarif': 255,
'dispo': 25
},
{
'date': '14/10/2016',
'id_hebergeur': 7,
'tarif': 44,
'dispo': 25
},
{
'date': '15/10/2016',
'id_hebergeur': 7,
'tarif': 256,
'dispo': 25
},
{
'date': '16/10/2016',
'id_hebergeur': 7,
'tarif': 252,
'dispo': 25
},
{
'date': '17/10/2016',
'id_hebergeur': 7,
'tarif': 245,
'dispo': 25
},
{
'date': '25/10/2016',
'id_hebergeur': 7,
'tarif': 47,
'dispo': 25
},
{
'date': '125/10/2016',
'id_hebergeur': 7,
'tarif': 252,
'dispo': 25
},
{
'date': '20/10/2016',
'id_hebergeur': 7,
'tarif': 44,
'dispo': 25
},
{
'date': '21/10/2016',
'id_hebergeur': 7,
'tarif': 252,
'dispo': 25
},
{
'date': '22/10/2016',
'id_hebergeur': 7,
'tarif': 14,
'dispo': 25
},
{
'date': '25/10/2016',
'id_hebergeur': 7,
'tarif': 48,
'dispo': 25
},
{
'date': '24/10/2016',
'id_hebergeur': 7,
'tarif': 252,
'dispo': 25
},
{
'date': '25/10/2016',
'id_hebergeur': 7,
'tarif': 255,
'dispo': 25
},
{
'date': '26/10/2016',
'id_hebergeur': 7,
'tarif': 142,
'dispo': 25
},
{
'date': '28/10/2016',
'id_hebergeur': 7,
'tarif': 45,
'dispo': 25
},
{
'date': '225/10/2016',
'id_hebergeur': 7,
'tarif': 41,
'dispo': 25
},
{
'date': '30/10/2016',
'id_hebergeur': 7,
'tarif': 55,
'dispo': 25
},
{
'date': '31/10/2016',
'id_hebergeur': 7,
'tarif': 55,
'dispo': 25
},
{
'date': '01/11/2016',
'id_hebergeur': 7,
'tarif': 55,
'dispo': 25
},
{
'date': '02/11/2016',
'id_hebergeur': 7,
'tarif': 55,
'dispo': 25
},
{
'date': '03/11/2016',
'id_hebergeur': 7,
'tarif': 55,
'dispo': 25
},
{
'date': '04/11/2016',
'id_hebergeur': 7,
'tarif': 55,
'dispo': 25
},
{
'date': '05/11/2016',
'id_hebergeur': 7,
'tarif': 55,
'dispo': 25
},
{
'date': '06/11/2016',
'id_hebergeur': 7,
'tarif': 55,
'dispo': 25
},
{
'date': '07/11/2016',
'id_hebergeur': 7,
'tarif': 55,
'dispo': 25
},
{
'date': '08/11/2016',
'id_hebergeur': 7,
'tarif': 25,
'dispo': 25
},
{
'date': '025/11/2016',
'id_hebergeur': 7,
'tarif': 55,
'dispo': 25
},
{
'date': '10/11/2016',
'id_hebergeur': 7,
'tarif': 55,
'dispo': 25
},
{
'date': '11/11/2016',
'id_hebergeur': 7,
'tarif': 55,
'dispo': 25
},
{
'date': '25/11/2016',
'id_hebergeur': 7,
'tarif': 255,
'dispo': 25
},
{
'date': '13/11/2016',
'id_hebergeur': 7,
'tarif': 255,
'dispo': 25
},
{
'date': '14/11/2016',
'id_hebergeur': 7,
'tarif': 825,
'dispo': 25
},
{
'date': '15/11/2016',
'id_hebergeur': 7,
'tarif': 55,
'dispo': 25
},
{
'date': '16/11/2016',
'id_hebergeur': 7,
'tarif': 55,
'dispo': 25
},
{
'date': '17/11/2016',
'id_hebergeur': 7,
'tarif': 55,
'dispo': 25
},
{
'date': '25/11/2016',
'id_hebergeur': 7,
'tarif': 35,
'dispo': 25
},
{
'date': '125/11/2016',
'id_hebergeur': 7,
'tarif': 252,
'dispo': 25
},
{
'date': '20/11/2016',
'id_hebergeur': 7,
'tarif': 55,
'dispo': 25
},
{
'date': '21/11/2016',
'id_hebergeur': 7,
'tarif': 252,
'dispo': 25
},
{
'date': '22/11/2016',
'id_hebergeur': 7,
'tarif': 55,
'dispo': 25
},
{
'date': '25/11/2016',
'id_hebergeur': 7,
'tarif': 48,
'dispo': 25
},
{
'date': '24/11/2016',
'id_hebergeur': 7,
'tarif': 55,
'dispo': 25
},
{
'date': '25/11/2016',
'id_hebergeur': 7,
'tarif': 55,
'dispo': 25
},
{
'date': '26/11/2016',
'id_hebergeur': 7,
'tarif': 55,
'dispo': 25
},
{
'date': '28/11/2016',
'id_hebergeur': 7,
'tarif': 55,
'dispo': 25
},
{
'date': '225/11/2016',
'id_hebergeur': 7,
'tarif': 41,
'dispo': 25
},
{
'date': '30/11/2016',
'id_hebergeur': 7,
'tarif': 55,
'dispo': 25
}
];
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isString;
var _isObjectLike = require('./isObjectLike');
var _isObjectLike2 = _interopRequireDefault(_isObjectLike);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Checks if `value` is classified as a `String` primitive or object.
*
* @param {*} value
* @returns {boolean}
*/
function isString(value) {
return typeof value === 'string' || (0, _isObjectLike2.default)(value) && Object.prototype.toString.call(value) === '[object String]' || false;
} |
/*
---
name: Picker.Attach
description: Adds attach and detach methods to the Picker, to attach it to element events
authors: Arian Stolwijk
requires: [Picker, Core/Element.Event]
provides: Picker.Attach
...
*/
Picker.Attach = new Class({
Extends: Picker,
options: {/*
onAttachedEvent: function(event){},
toggleElements: null, // deprecated
toggle: null, // When set it deactivate toggling by clicking on the input */
showOnInit: false
},
initialize: function(attachTo, options){
this.parent(options);
this.attachedEvents = [];
this.attachedElements = [];
this.toggles = [];
this.inputs = [];
var documentEvent = function(event){
if (this.attachedElements.contains(event.target)) return null;
this.close();
}.bind(this);
var document = this.picker.getDocument().addEvent('click', documentEvent);
var preventPickerClick = function(event){
event.stopPropagation();
return false;
};
this.picker.addEvent('click', preventPickerClick);
// Support for deprecated toggleElements
if (this.options.toggleElements) this.options.toggle = document.getElements(this.options.toggleElements);
this.attach(attachTo, this.options.toggle);
},
attach: function(attachTo, toggle){
if (typeOf(attachTo) == 'string') attachTo = document.id(attachTo);
if (typeOf(toggle) == 'string') toggle = document.id(toggle);
var elements = Array.from(attachTo),
toggles = Array.from(toggle),
allElements = [].append(elements).combine(toggles),
self = this;
var eventWrapper = function(fn, element){
return function(event){
if (event.type == 'keydown' && ['tab', 'esc'].contains(event.key) == false) return false;
if (event.target.get('tag') == 'a') event.stop();
self.fireEvent('attachedEvent', [event, element]);
self.position(element);
fn();
};
};
allElements.each(function(element, i){
// The events are already attached!
if (self.attachedElements.contains(element)) return null;
var tag = element.get('tag');
var events = {};
if (tag == 'input'){
// Fix in order to use togglers only
if (!toggles.length){
events = {
focus: eventWrapper(self.open.bind(self), element),
keydown: eventWrapper(self.close.bind(self), element),
click: eventWrapper(self.open.bind(self), element)
};
}
self.inputs.push(element);
} else {
if (toggles.contains(element)){
self.toggles.push(element);
events.click = eventWrapper(self.toggle.bind(self), element);
} else {
events.click = eventWrapper(self.open.bind(self), element);
}
}
element.addEvents(events);
self.attachedElements.push(element);
self.attachedEvents.push(events);
});
return this;
},
detach: function(attachTo, toggle){
if (typeOf(attachTo) == 'string') attachTo = document.id(attachTo);
if (typeOf(toggle) == 'string') toggle = document.id(toggle);
var elements = Array.from(attachTo),
toggles = Array.from(toggle),
allElements = [].append(elements).combine(toggles),
self = this;
if (!allElements.length) allElements = self.attachedElements;
allElements.each(function(element){
var i = self.attachedElements.indexOf(element);
if (i < 0) return null;
var events = self.attachedEvents[i];
element.removeEvents(events);
delete self.attachedEvents[i];
delete self.attachedElements[i];
var toggleIndex = self.toggles.indexOf(element);
if (toggleIndex != -1) delete self.toggles[toggleIndex];
var inputIndex = self.inputs.indexOf(element);
if (toggleIndex != -1) delete self.inputs[inputIndex];
});
return this;
},
destroy: function(){
this.detach();
this.parent();
}
});
|
/*
@license
dhtmlxGantt v.4.1.0 Stardard
This software is covered by GPL license. You also can obtain Commercial or Enterprise license to use it in non-GPL project - please contact sales@dhtmlx.com. Usage without proper license is prohibited.
(c) Dinamenta, UAB.
*/
gantt.locale = {
date: {
month_full: ["Januar", "Februar", "Mars", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Desember"],
month_short: ["Jan", "Feb", "Mar", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Des"],
day_full: ["Søndag", "Mandag", "Tirsdag", "Onsdag", "Torsdag", "Fredag", "Lørdag"],
day_short: ["Søn", "Mon", "Tir", "Ons", "Tor", "Fre", "Lør"]
},
labels: {
dhx_cal_today_button: "I dag",
day_tab: "Dag",
week_tab: "Uke",
month_tab: "Måned",
new_event: "Ny hendelse",
icon_save: "Lagre",
icon_cancel: "Avbryt",
icon_details: "Detaljer",
icon_edit: "Rediger",
icon_delete: "Slett",
confirm_closing: "", //Your changes will be lost, are your sure ?
confirm_deleting: "Hendelsen vil bli slettet permanent. Er du sikker?",
section_description: "Beskrivelse",
section_time: "Tidsperiode",
section_type:"Type",
/* grid columns */
column_text : "Task name",
column_start_date : "Start time",
column_duration : "Duration",
column_add : "",
/* link confirmation */
link: "Link",
confirm_link_deleting:"will be deleted",
link_start: " (start)",
link_end: " (end)",
type_task: "Task",
type_project: "Project",
type_milestone: "Milestone",
minutes: "Minutes",
hours: "Hours",
days: "Days",
weeks: "Week",
months: "Months",
years: "Years",
/* message popup */
message_ok: "OK",
message_cancel: "Avbryt"
}
};
|
'use strict';
var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var StatsPlugin = require('stats-webpack-plugin');
module.exports = {
entry: [
path.join(__dirname, 'app/main.js')
],
output: {
path: path.join(__dirname, '/dist/'),
filename: '[name]-[hash].min.js',
publicPath: '/'
},
plugins: [
new webpack.optimize.OccurrenceOrderPlugin(),
new HtmlWebpackPlugin({
template: 'app/index.tpl.html',
inject: 'body',
filename: 'index.html'
}),
new ExtractTextPlugin('[name]-[hash].min.css'),
new webpack.optimize.UglifyJsPlugin({
compressor: {
warnings: false,
screw_ie8: true
}
}),
new StatsPlugin('webpack.stats.json', {
source: false,
modules: false
}),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
})
],
module: {
loaders: [{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
"presets": ["es2015", "stage-0", "react"]
}
}, {
test: /\.json?$/,
loader: 'json-loader'
}, {
test: /\.css$/,
loader: ExtractTextPlugin.extract('style', 'css?modules&localIdentName=[name]---[local]---[hash:base64:5]!postcss')
}]
},
postcss: [
require('autoprefixer')
]
};
|
define([
'aeris/util',
'aeris/api/models/aerisapimodel',
'aeris/errors/apiresponseerror'
], function(_, AerisApiModel, ApiResponseError) {
/**
* Represents data from multiple Aeris API endpoints
* combined into a single model.
*
* Note that AerisBatchModel does not currently support
* per-model actions or queries.
*
* @class AerisBatchModel
* @namespace aeris.api.models
* @extends aeris.api.models.AerisApiModel
*
* @constructor
* @override
*
* @param {Object=} opt_attrs
* @param {Object=} opt_options
* @param {Object.<string,aeris.api.models.AerisApiModel>} opt_options.models See addModels documentation.
*
* @param {aeris.api.params.Params} opt_options.params
*/
var AerisBatchModel = function(opt_attrs, opt_options) {
/**
* A list of nested models, in the order of the last
* API requests.
*
* @property modelsInOrder_
* @type {Array.<aeris.api.models.AerisApiModel>}
* @private
*/
this.modelsInOrder_ = [];
AerisApiModel.call(this, opt_attrs, opt_options);
};
_.inherits(AerisBatchModel, AerisApiModel);
/**
* @method getEndpointUrl_
* @protected
* @return {string}
*/
AerisBatchModel.prototype.getEndpointUrl_ = function() {
return _.compact([
this.server_,
'batch',
this.id
]).join('/');
};
/**
* @method serializeParams_
* @protected
* @param {aeris.api.params.models.Params} params
* @return {Object}
*/
AerisBatchModel.prototype.serializeParams_ = function(params) {
// Save models in order,
// so that we can parse the response based
// on the order of the `responses` array
// (because javascript does not necessarily maintain order in objects)
this.modelsInOrder_ = this.getNestedModels_();
return _.extend(params.toJSON(), {
requests: this.getEncodedEndpoints_(this.modelsInOrder_)
});
};
/**
* Return component models, which
* are attributes of the batch model.
*
* @method getNestedModels_
* @private
* @return {Array.<aeris.api.models.AerisApiModel>}
*/
AerisBatchModel.prototype.getNestedModels_ = function() {
return this.values().filter(function(attr) {
return attr instanceof AerisApiModel;
});
};
/**
* @method getEncodedEndpoints_
* @private
* @param {Array.<aeris.api.models.AerisApiModel>} apiModels
*/
AerisBatchModel.prototype.getEncodedEndpoints_ = function(apiModels) {
var requests = apiModels.map(function(model) {
var endpoint = '/' + model.getEndpoint();
return [
endpoint,
this.encodeModelParams_(model)
].join(encodeURIComponent('?'));
}, this);
return requests.join(',');
};
/**
* @method encodeModelParams_
* @private
* @param {aeris.api.models.AerisApiModel} model
* @return {string} Encoded model params.
*/
AerisBatchModel.prototype.encodeModelParams_ = function(model) {
var params = model.getParams().toJSON();
var paramsStr = _.map(params, function(val, key) {
return key + '=' + val;
}).join('&');
return this.encodeParamsString_(paramsStr);
};
/**
* @method encodeParamsString_
* @private
*/
AerisBatchModel.prototype.encodeParamsString_ = function(string) {
// Aeris API only needs ? and & encoded.
return string.
replace('?', '%3F').
replace('&', '%26');
};
/**
* @method isSuccessResponse_
* @param {Object} res
* @protected
* @return {Boolean}
*/
AerisBatchModel.prototype.isSuccessResponse_ = function(res) {
var isBatchSuccess = !!res && res.success;
if (!isBatchSuccess) {
return false;
}
return res.response.responses.every(function(r) {
return !!r && r.success;
});
};
/**
* Sets batch response data onto nested models
*
* @override
* @method parse
* @param {Object} raw Raw response data.
* @return {Object}
*/
AerisBatchModel.prototype.parse = function(raw) {
try {
var responses = raw.response.responses;
this.modelsInOrder_.forEach(function(model, index) {
this.updateModelWithResponseData_(model, responses[index]);
}, this);
}
catch (e) {
throw new ApiResponseError('Unable to parse batch response data: ' +
e.message);
}
return this.attributes;
};
/**
* @method updateModelWithResponseData_
* @private
* @param {aeris.api.models.AerisApiModel} model
* @param {Object} data Response data
*/
AerisBatchModel.prototype.updateModelWithResponseData_ = function(model, data) {
var modelAttrs = model.parse(data);
model.set(modelAttrs);
};
/**
* @method toJSON
* @return {Object}
*/
AerisBatchModel.prototype.toJSON = function() {
var json = AerisApiModel.prototype.toJSON.call(this);
// toJSON'ify nested models
_.each(json, function(val, key) {
if (val instanceof AerisApiModel) {
json[key] = val.toJSON();
}
});
return json;
};
return AerisBatchModel;
});
|
fis.config.set('project.include', ['pages/**', 'macros/**', 'static/**']);
fis.config.set('project.exclude', ['pages/**.less', 'macros/**.less', 'static/**.less']);
fis.config.set('modules.postpackager', 'simple');
fis.config.set('pack', {
'pkg/libs.js': [
'static/js/libs/jquery.min.js',
'static/js/libs/bootstrap.min.js',
'static/js/libs/respond.min.js',
'static/js/init.js'
],
'pkg/layout.js': [
'static/js/layout.js',
'static/output/macros.js'
],
'pkg/libs.css': [
'static/css/libs/*.css'
],
'pkg/layout.css': [
'static/css/bootstrap.theme.css',
'static/css/common.css',
'static/output/macros.css',
'static/css/layout.css'
]
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.